Affichage des articles dont le libellé est Active questions tagged java - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged java - Stack Overflow. Afficher tous les articles

dimanche 29 mars 2015

Binary Search Tree searching in java



I'm attempting to make a BST program that is capable of inserting a given number and then telling the user if the number is in the BST by saying either true or false. However, even if the number is inserted, it always registers as false. Would anyone be able to tell me where I am going wrong here? I can supply the rest of my class files if they are needed.



public class BinarySearchTree implements BST
{
private int n;
private Node r;
private Node l;

public void enter(int num)
{
Node node = new Node(num);

if (num < node.getData())
{
if (node.getL() != null)
{
insert(num);
}

else
{
node.setL(new Node(num));
}
}

else if (num > node.getData())
{
if (node.getR() != null)
{
insert(num);
}

else
{
node.setR(new Node(num));
}
}
}

public boolean search (int num)
{
if (num == this.n)
{
return true;
}

else if (num > this.n)
{
if (r == null)
{
return false;
}

else
{
return true;
}
}
else if (num < this.n)
{
if (l == null)
{
return false;
}
else
{
return true;
}
}
return false;
}
}



Using write method to save a picture file in Java



I need to save a picture object into the working directory with a specific file name using the write method. Here's my code:


public void storePhotos(String directory){



for(int i = 0; i < labelledPhotos.length; i++){
Picture currentPhoto = new Picture(labelledPhotos[i].getLabelledPhoto());

String fileName = directory + "/" + labelledPhotos[i].getYear() + "_" + labelledPhotos[i].getCategory() + "_" + labelledPhotos[i].getId() + ".jpg";
currentPhoto.write(fileName);

}


The user is suppose to input the director as the parameter and I need to save the image to the directory. For some reason the write method isn't saving it. If I hard code in the directory into the write parameter like:


currentPhoto.write("pic.jpg");


then the photo gets saved into directory. So I know its something wrong with the String fileName and how it gets passed into the write method, but I'm not sure what. Any help would be greatly appreciated.




Java vs JavaScript increment operator



In Java, if I do this



int value = 3;
int incr = value++;


incr is 4


but in JavaScript,



int value = 3;
int incr = value++;


incr is 3


in order for incr to be 4 in JS I have to do



int incr = ++value;


why is this?




Program loops where it shouldnt [duplicate]




This question already has an answer here:




I want the interface to go back to 'Enter a command' menu after it has completed a command (unless the user inputs "exit")but it keeps repeating the same interface for that command over and over again. e.g when the user inputs "register" the system should ask for name then phone number then email address and then says the staff member has been created (given the user input the correct type of input). The system should then ask for another command but instead it will ask for name, phone number and email address and will register another staff member. Please help?



public static void main(String args[]){
RoomBookSystem rbs = new RoomBookSystem();

//add rooms to the system
Room room1=new Room();
Room room2=new Room();
Room room3=new Room();
Room room4=new Room();

room1.setName("1");
room1.setCapacity(247);
room1.setEquipment("Projector");;
room1.setID(2);

room2.setName("2");
room2.setCapacity(18);
room2.setEquipment("Waffle maker, television");
room2.setID(2);

room3.setName("3");
room3.setCapacity(10);
room3.setEquipment("Television");
room3.setID(3);

room4.setName("4");
room4.setCapacity(12);
room4.setEquipment("Piano");
room1.setID(4);

rbs.addRoom(room1);
rbs.addRoom(room2);
rbs.addRoom(room3);
rbs.addRoom(room4);

//adds staff to the system
Staff kai = new Staff();
Staff sehun = new Staff();
Staff xiumin = new Staff();
Staff chen = new Staff();

kai.setName("Kai");
kai.setPhoneNumber("123456789");
kai.setEmailAddress("kai@exo.com");

sehun.setName("Sehun");
sehun.setPhoneNumber("6758302");
sehun.setEmailAddress("yehet@exo.com");

xiumin.setName("Xiumin");
xiumin.setPhoneNumber("90");
xiumin.setEmailAddress("xiurista@exo.com");


chen.setName("Chen");
chen.setPhoneNumber("609090900");
chen.setEmailAddress("chensingmachine@exo.com");

rbs.registerStaff(kai);
rbs.registerStaff(xiumin);
rbs.registerStaff(sehun);
rbs.registerStaff(chen);


//Starts the room booking interface
System.out.println("*************************************************");
System.out.println("Welcome to the room booking system!");
System.out.println("*************************************************");
System.out.println("The following rooms are available: ");
rbs.printRooms();
System.out.println("-------------------------------------------------");
System.out.println("Enter a command: (register, book, rooms, print, cancel, exit)");


Scanner scan = new Scanner(System.in);
String userCommand = scan.nextLine();
//while(userCommand!="exit"){
while(userCommand=="register"){

System.out.println("enter your name: ");
Staff newStaff = new Staff();
String name = scan.nextLine();
newStaff.setName(name);

System.out.println("Enter your email address: ");
String emailAddress = scan.nextLine();
newStaff.setEmailAddress(emailAddress);

System.out.println("Enter your phone number");
String phoneNumber=scan.nextLine();
newStaff.setPhoneNumber(phoneNumber);

rbs.registerStaff(newStaff);

System.out.println("Staff member: "+name+", "+emailAddress+", "+phoneNumber+" has been registered");


} if(userCommand=="book"){
System.out.println("Booking a new meeting: ");
System.out.println("Enter staff name");

String staffName = scan.nextLine();

if(rbs.isRegistered(staffName)){
Staff staffBooker = new Staff();
for(int i =0; i<rbs.currentStaff.length;i++){
if(rbs.currentStaff[i].getName()==staffName){
staffBooker=rbs.currentStaff[i];
}

Room newRoom = new Room();
System.out.println("Enter a room ID: ");
int roomID = scan.nextInt();

System.out.println("Enter a month: ");
int month= scan.nextInt();

System.out.println("Enter day: ");
int day = scan.nextInt();

System.out.println("Enter starting hour: ");
int startingHour=scan.nextInt();

System.out.println("Enter duration: ");
int duration = scan.nextInt();

newRoom.setID(roomID);

TimeInterval newTimeInterval = new TimeInterval(startingHour,day,month,duration);

Meeting newMeeting = new Meeting(staffBooker, newTimeInterval, newRoom);

rbs.bookMeeting(newMeeting);

}
}

} else if(userCommand=="rooms"){
Room newRoom = new Room();
System.out.println("Add a new room");
System.out.println("Enter room ID: ");
int roomID = scan.nextInt();

System.out.println("Enter room capacity: ");
int roomCapacity = scan.nextInt();

System.out.println("Enter equipment available in room: ");
String equipment = scan.nextLine();

newRoom.setID(roomID);
newRoom.setCapacity(roomCapacity);
newRoom.setEquipment(equipment);

rbs.addRoom(newRoom);

} else if(userCommand=="print"){
rbs.printRooms();
rbs.printMeeting();
rbs.printStaff();

scan.close();
System.out.println("Goodbye");
System.exit(0);


}


}




How to consume a Jax-RS 2.0 Response from Mule Apikit



I am trying to consume a JAX-RS 2 Response with Jersey client 2.17.



Response response = ClientBuilder.newClient()
.target("http://localhost:8080/api")
.path("organisations")
.request(MediaType.APPLICATION_JSON)
.get(); //[1] .get(GetOrganisationsResponse.class);
//[2] System.out.println("headers=" + response.getHeaders());
//[3] String json = response.readEntity(String.class);
//[4] System.out.println("json=" + json);
Organisations orgs = response.readEntity(Organisations.class);


The response is served by Mule apikit.



<flow name="get:/organisations:my-api-config" >
<set-payload value="#[app.registry['organisations'].getOrganisations(message.inboundProperties['start'], message.inboundProperties['pages'])]" doc:name="Set Payload" />
</flow>


POJOs are generated from a RAML description. Here is the generated POJO for the above service:



/**
* A collection of organisations
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("org.jsonschema2pojo")
@JsonPropertyOrder({
"size",
"organisations"
})
public class Organisations {

/**
*
* (Required)
*
*/
@JsonProperty("size")
private Integer size;
@JsonProperty("organisations")
private List<Organisation> organisations = new ArrayList<Organisation>();
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
*
* (Required)
*
* @return
* The size
*/
@JsonProperty("size")
public Integer getSize() {
return size;
}

/**
*
* (Required)
*
* @param size
* The size
*/
@JsonProperty("size")
public void setSize(Integer size) {
this.size = size;
}

public Organisations withSize(Integer size) {
this.size = size;
return this;
}

/**
*
* @return
* The organisations
*/
@JsonProperty("organisations")
public List<Organisation> getOrganisations() {
return organisations;
}

/**
*
* @param organisations
* The organisations
*/
@JsonProperty("organisations")
public void setOrganisations(List<Organisation> organisations) {
this.organisations = organisations;
}

public Organisations withOrganisations(List<Organisation> organisations) {
this.organisations = organisations;
return this;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

public Organisations withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}


... and here is the generated GetOrganisationsResponse for the same service:



public class GetOrganisationsResponse
extends support.ResponseWrapper
{


private GetOrganisationsResponse(Response delegate) {
super(delegate);
}

/**
* OK
*
* @param entity
*
*/
public static Organisations.GetOrganisationsResponse withJsonOK(model.Organisations entity) {
Response.ResponseBuilder responseBuilder = Response.status(200).header("Content-Type", "application/json");
responseBuilder.entity(entity);
return new Organisations.GetOrganisationsResponse(responseBuilder.build());
}

}


In trying to GET an instance of Organisations on the client side, I observed the following:



  • All the properties from Organisations end up populated in the additionalProperties member suggesting none were recognized by the parser,

  • If I comment out the additionalProperties member and getter/setter, the parser's error is this:



com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "date" (class model.Organisations), not marked as ignorable (2 known properties: "size", "organisations"])




  • ... this makes sense if the date, headers (and others) fields were not mapped to the Response, but to the Organisations instead but why?

  • when uncommenting the lines marked 2, 3 and 4, the Response converted to String looks as follows. Shouldn't the GetOrganisationsResponse headers have been parsed and returned as a result of response.getHeaders() ?



headers={X-MULE_ENCODING=[UTF-8], Date=[Mon, 30 Mar 2015 02:16:57 +0000], Content-Length=[746], X-MULE_SESSION=[...], Connection=[close], http.status=[200], Content-Type=[application/json], Server=[Mule Core/3.6.1]} json={"date":null,"lastModified":null,"headers":{"Content-Type":["application/json"]},"entity":{"size":3,"organisations":[{"oid":"54df33936d725e370b000004","name":"org1","additionalProperties":{}},{"oid":"54df34406d725e370b000006","name":"org2","additionalProperties":{}},{"oid":"54df33c96d725e370b000005","name":"org3","additionalProperties":{}}],"additionalProperties":{}},"status":200,"mediaType":{"type":"application","subtype":"json","parameters":{},"wildcardType":false,"wildcardSubtype":false},"allowedMethods":[],"links":[],"cookies":{},"entityTag":null,"statusInfo":"OK","metadata":{"Content-Type":["application/json"]},"stringHeaders":{"Content-Type":["application/json"]},"length":-1,"language":null,"location":null}




  • Finally when trying to force the Response as generated on the server side with .get(GetOrganisationsResponse.class) (uncommenting 1), the outcome is:



Can not find a deserializer for non-concrete Map type [map type; class javax.ws.rs.core.MultivaluedMap, [simple type, class java.lang.String] -> [collection type; class java.util.List, contains [simple type, class java.lang.String]]]





  • The culprit is the following code in the parent class of GetOrganisationResponse called ResponseWrapper:


    @Override public MultivaluedMap getHeaders() { return delegate.getHeaders(); }


    @Override public MultivaluedMap getStringHeaders() { return delegate.getStringHeaders(); }




Thanks for pointing me in the right direction:



  1. Is client.get() or client.get(GetOrganisationsResponse.class) the recommended aproach to parse a Mule Apikit response on the client? (I could not find answers in Mule docs)

  2. Considering I get errors for either option: Thanks for your help&ideas on how to fix them.




Issue in checkstyle configuaration in IntelliJ Idea



My objective is to implement Google's Java Style Checkstyle as stated in http://ift.tt/1ET0LMG .


In IntelliJ I have enabled Checkstyle plugin and try to point checkstyle xml ( downloaded from http://ift.tt/1EuY6wf).


I got following exception stated Property 'fileExtensions' in module Checker does not exist though this property is defined in the xml as "property name="fileExtensions" value="java, properties, xml"


Exception details:


org.infernus.idea.checkstyle.exception.CheckStylePluginException: The CheckStyle rules file could not be loaded.

Property 'fileExtensions' in module Checker does not exist, please check the documentation at org.infernus.idea.checkstyle.checker.CheckerFactory.blacklistAndShowMessage(CheckerFactory.java:248) at org.infernus.idea.checkstyle.checker.CheckerFactory.createChecker(CheckerFactory.java:202)




where is a sample JAX-RS client sample?



I'm aware of the Java API for Yahoo Finance. I'm looking for a sample "hello world" client which uses, for example, Yahoo Finance, or, perhaps, some other publicly available RESTful API to test against.


see also:


http://ift.tt/1a8TSiN


http://ift.tt/1sXQ3j6


The Jersey example above seems ok. Just adapt it to Yahoo Finance?


(Not a well researched question, admittedly. Only trying to avoid going down a rabbit hole.)




Neet to connect a join table to a separate table



I need to keep record of various businesses their cities and their branches in each city. Each business might be in different cities and in each city might have different branches. Take a bank as an example. It might be in Cities A and B and in city A might have two branches and in city b only one.


I suppose the branch table should have branchid and foreign keys of both primary keys of the join table. In this way I can make sure no branch will be associate to more than one combination of city and business.



Business City
\ /
BusinessID CityID <<join table has primary keys of Business and City tables
|
Branch
BranchID BusinessID CityID


Sample data



Business Table
1
2
3

City Table
A
B
C

Join Table
Business_City
1 A
1 B
2 A
3 C

Branch Table
Business City Branch
1 A I1
1 A I2
1 B I6
2 A I5
3 C I3


My current entities



@Entity
public class Business {
@Id
long id;
@ManyToMany
List<City> cities;
...
}

@Entity
public class City {
@Id
long id;
}

@Entity
public class Branch {
?????
}



Conversion from parsing a String to double is returning 0.0:



This is a follow up on the last question I made regarding this topic. It's a different issue though.


My code is working, except it's copying some sort of address using the copyOfRange. It always returns 0.0 due to an address of some sort, instead of the section of the array getBits.


Can someone please scan this is and make a suggestion? I am going crazy over this (it's not an assignment).



> package runTests;
>
> import java.util.Arrays;
>
> public class runTestGetBinaryStrands {
> protected static int getBits[] = {1,0,1,1,0,1,0,0,0,1,1,0,1,0,1,0};
> double numerator, denominator, x, y;
>
> public static void main (String[] args)
> {
> runTestGetBinaryStrands test = new runTestGetBinaryStrands();
> test.getNumber(null, getBits);
> }
> /*NOTE OF THIS FORLOOP: * Divided the bits array in half & convert two different binary values to a string * I parsed the string
> to an int value, which can be put saved to a double and be treated
> like a decimal value. * I got the first 8 elements and stashed them
> into numerator, and did the same for denominator for the remaining
> array bits. *
> * The chromosome has one binary string, made up of a bunch of smaller parts.
> * You use getNumber in the chromosome to get out the values of the parts. * */ public void getNumber(String convert, int[]
> tempBinary) {
> for (int i = 0; i < getBits.length; i++)
> {
> for(int j = 0; j < getBits.length; j++) //start at index 0 to 7 = 8.
> {
> tempBinary = Arrays.copyOfRange(getBits, 0, 7); //Get first set of 8 elements.
> convert = tempBinary.toString();
> System.out.println(convert);
> try
> {
> numerator = Integer.parseInt(convert); //converts string to one whole section in
> }
> catch (NumberFormatException ex)
> {
> }
> System.out.println("See Numerator's value: " + numerator);
>
> tempBinary= Arrays.copyOfRange(getBits, 8, 15); //Get Second set of 8 elements.
> convert = tempBinary.toString();
> try
> {
> denominator = Integer.parseInt(convert); //converts string to one whole section in
> }
> catch (NumberFormatException ex)
> {
> } System.out.println("See Denominator's value: " + denominator);
> }
> }
}
}



Casting to an indirect subclass



I have been playing around with the google drive api and am having a hard time understanding why I cannot cast Result to DriveFolder.DriveFolderResult. In the documentation DriveFolder.DriveFolderResult is a indirect known subclass of Result, but when I try casting Result to DriveFolder.DriveFolderResult I get the exception,



`java.lang.ClassCastException: com.google.android.gms.drive.internal.v$e cannot be cast to com.google.android.gms.drive.DriveApi$DriveIdResult`


Why is this happening? Since DriveFolder.DriveFolderResult is a indirect known subclass shouldn't I be able to cast it to 'Result'?


Also to help you guys I pasted some code down below. This is taken directly from here. Why would this code work? How can I implement the interface ResultCallback to give me back DriveFolder.DriveFolderResult? The best solution for me would be to have a class implement ResultCallback, have the method onResult return some object that has the method getStatus() and I then can cast it to any indirect subclass I want. Is this possible?



ResultCallback<DriveFolderResult> folderCreatedCallback = new
ResultCallback<DriveFolderResult>() {
@Override
public void onResult(DriveFolderResult result) {
if (!result.getStatus().isSuccess()) {
showMessage("Error while trying to create the folder");
return;
}
showMessage("Created a folder: " + result.getDriveFolder().getDriveId());
}
}



Java Please help. So many Errors I don't know what I'm doing wrong but apparently its a lot



You'll Just have to run it yourself everything goes wrong when I hit calculate.


This is all the errors I get:



Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at java.lang.Double.valueOf(Unknown Source)
at school.TravelExpenses$CalcButtonListener.actionPerformed(TravelExpenses.java:139)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)


Code:



package school;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JOptionPane;

/**
* The TravelExpense class creates the GUI for the Travel Expenses application.
*/

public class TravelExpenses extends JFrame {
// The following variables will reference the
// custom panel objects
private JPanel travelInfoPanel; // TravelInfo panel
private JPanel buttonPanel; // Buttons panel

// Labels for the Travel Information fields.
private JLabel DaysLabel;
private JLabel AirfareLabel;
private JLabel CarLabel;
private JLabel MilesLabel;
private JLabel ParkingLabel;
private JLabel CabLabel;
private JLabel RegistrLabel;
private JLabel LodgingLabel;

// Text Fields for Travel Information entry
private JTextField DaysTextField;
private JTextField AirfareTextField;
private JTextField CarTextField;
private JTextField MilesTextField;
private JTextField ParkingTextField;
private JTextField CabTextField;
private JTextField RegistrTextField;
private JTextField LodgingTextField;

private JButton calcButton;

private double mealsReimbursed = 37.00;
private double parkingReimbursed = 10.00;
private double taxiChargesReimbursed = 20.00;
private double lodgingChargesReimbursed = 95.00;
private double perMileReimbursed = 0.27;
public TravelExpenses() {
super("Travel Expenses");

setLocationRelativeTo(null);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

buildTravelInfoPanel();
buildButtonPanel();

add(travelInfoPanel, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);

pack();
setVisible(true);
}


private void buildTravelInfoPanel() {
DaysLabel = new JLabel("Number of days on trip: ");
AirfareLabel = new JLabel("Amount of airfare: ");
CarLabel = new JLabel("Amount of car rental: ");
MilesLabel = new JLabel("Miles driven: ");
ParkingLabel = new JLabel("Parking Fees: ");
CabLabel = new JLabel("Taxi fees: ");
RegistrLabel = new JLabel("Conference registration: ");
LodgingLabel = new JLabel("Lodging charges per night: ");

DaysTextField = new JTextField(3);
AirfareTextField = new JTextField(8);
CarTextField = new JTextField(8);
MilesTextField = new JTextField(4);
ParkingTextField = new JTextField(6);
CabTextField = new JTextField(6);
RegistrTextField = new JTextField(8);
LodgingTextField = new JTextField(6);

travelInfoPanel = new JPanel();

travelInfoPanel.setLayout(new GridLayout(10, 2));

travelInfoPanel.add(DaysLabel);
travelInfoPanel.add(DaysTextField);
travelInfoPanel.add(AirfareLabel);
travelInfoPanel.add(AirfareTextField);
travelInfoPanel.add(CarLabel);
travelInfoPanel.add(CarTextField);
travelInfoPanel.add(MilesLabel);
travelInfoPanel.add(MilesTextField);
travelInfoPanel.add(ParkingLabel);
travelInfoPanel.add(ParkingTextField);
travelInfoPanel.add(CabLabel);
travelInfoPanel.add(CabTextField);
travelInfoPanel.add(RegistrLabel);
travelInfoPanel.add(RegistrTextField);
travelInfoPanel.add(LodgingLabel);
travelInfoPanel.add(LodgingTextField);

// Add an empty border around the panel for spacing.
travelInfoPanel.setBorder(BorderFactory
.createEmptyBorder(10, 10, 1, 10));
}

private void buildButtonPanel() {
// Create the calcButton.
calcButton = new JButton("Calculate");

calcButton.addActionListener(new CalcButtonListener());

buttonPanel = new JPanel();

buttonPanel.setLayout(new BorderLayout(5, 5));

// Add the two buttons to the buttonPanel.
buttonPanel.add(calcButton, BorderLayout.CENTER);

buttonPanel.setBorder(BorderFactory.createEmptyBorder(1, 10, 10, 10));
}

private class CalcButtonListener implements ActionListener {

String days = DaysTextField.getText();
String air = AirfareTextField.getText();
String carRental = CarTextField.getText();
String miles = MilesTextField.getText();
String parking =ParkingTextField.getText();
String taxi = CabTextField.getText();
String Registr = RegistrTextField.getText();
String lodging = LodgingTextField.getText();

public void actionPerformed(ActionEvent e) {
// Declare variables for calculated items
double actualExpenses=Double.valueOf(air) + Double.valueOf(carRental) + Double.valueOf(parking) + Double.valueOf(taxi) + Double.valueOf(Registr) + Double.valueOf(lodging) + (Double.valueOf(miles)*.27);
double allowableExpenses=(mealsReimbursed+parkingReimbursed+taxiChargesReimbursed+lodgingChargesReimbursed)*Integer.valueOf(days)+perMileReimbursed;
double excessAmount=actualExpenses-allowableExpenses;
String savedMoney="Owed";
if(excessAmount<0){
savedMoney="Saved";
excessAmount*=-1;
}
JOptionPane.showMessageDialog(null, "Total Expenses: "+actualExpenses+"\nAllowable Expenses: "+allowableExpenses+"\n"+"Money "+savedMoney+": "+excessAmount);
}
}

public static void main(String[] args) {
new TravelExpenses();
}
}



How to create SharePoint 2013 User Group using LDAP Java API



How do I create a user group in SharePoint 2013 using the LDAP Java API ?




Magnolia Blossom module can't find .jsp templates



I'm trying to create some simple template using magnolia blossom module. The problem occurs when I'm trying to display site, it says that it can't render template (.jsp file not found).


Project Structure


Project Structure


MainTemplate.java



@Template(id = "websiteModule:pages/mainTemplate", title = "Main Template")
@TemplateDescription("Main Template example with Blossom")
@Controller
public class MainTemplate {

@RequestMapping("/mainTemplate")
public String render() {
return "pages/mainTemplate.jsp";
}

@TabFactory("Site Settings")
public void homeDialog(UiConfig cfg, TabBuilder tab) {

tab.fields(
cfg.fields.text("title").label("Title").description("The HTML page title"),
cfg.fields.text("metaDescription").label("Meta Description").description("HTML Meta Description of the web site"),
cfg.fields.text("metaKeywords").label("Meta Keywords").description("HTML Meta Keywords of the web site")
);
}
}


blossom-servlet.xml



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:context="http://ift.tt/GArMu7"
xsi:schemaLocation="http://ift.tt/GArMu6 http://ift.tt/1jdM0fG http://ift.tt/GArMu7 http://ift.tt/1jdLYo7">

<context:annotation-config/>

<context:component-scan base-package="com.brightit" use-default-filters="false">
<context:include-filter type="annotation" expression="info.magnolia.module.blossom.annotation.Template"/>
<context:include-filter type="annotation" expression="info.magnolia.module.blossom.annotation.Area"/>
<context:include-filter type="annotation" expression="info.magnolia.module.blossom.annotation.DialogFactory"/>
<context:include-filter type="annotation" expression="info.magnolia.module.blossom.annotation.VirtualURIMapper"/>
<context:include-filter type="assignable" expression="info.magnolia.cms.beans.config.VirtualURIMapping"/>
</context:component-scan>

<bean class="info.magnolia.module.blossom.web.BlossomRequestMappingHandlerAdapter">
<property name="customArgumentResolvers">
<list>
<bean class="info.magnolia.module.blossom.web.BlossomHandlerMethodArgumentResolver" />
</list>
</property>
<!-- For @Valid - JSR-303 Bean Validation API -->
<property name="webBindingInitializer">
<bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator">
<bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</property>
</bean>
</property>
<property name="redirectPatterns">
<list>
<value>website:*</value>
</list>
</property>
</bean>

<bean class="info.magnolia.module.blossom.preexecution.BlossomHandlerMapping">
<property name="targetHandlerMappings">
<list>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
<property name="useSuffixPatternMatch" value="false" />
</bean>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
</list>
</property>
</bean>

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />

<bean class="info.magnolia.module.blossom.view.UuidRedirectViewResolver">
<property name="order" value="1" />
</bean>

<!-- JSP - renders all views that end with .jsp -->
<bean class="info.magnolia.module.blossom.view.TemplateViewResolver">
<property name="order" value="2"/>
<property name="prefix" value="/templates/websiteModule/"/>
<property name="viewNames" value="*.jsp"/>
<property name="viewRenderer">
<bean class="info.magnolia.module.blossom.view.JspTemplateViewRenderer">
<property name="contextAttributes">
<map>
<entry key="damfn">
<bean class="info.magnolia.rendering.renderer.ContextAttributeConfiguration">
<property name="name" value="damfn"/>
<property name="componentClass" value="info.magnolia.dam.templating.functions.DamTemplatingFunctions"/>
</bean>
</entry>
</map>
</property>
</bean>
</property>
</bean>

<!-- Freemarker - renders all views that end with .ftl -->
<bean class="info.magnolia.module.blossom.view.TemplateViewResolver">
<property name="order" value="3"/>
<property name="prefix" value="/websiteModule/"/>
<property name="viewNames" value="*.ftl"/>
<property name="viewRenderer">
<bean class="info.magnolia.module.blossom.view.FreemarkerTemplateViewRenderer">
<property name="contextAttributes">
<map>
<entry key="cms">
<bean class="info.magnolia.rendering.renderer.ContextAttributeConfiguration">
<property name="name" value="cms"/>
<property name="componentClass" value="info.magnolia.templating.freemarker.Directives"/>
</bean>
</entry>
<entry key="cmsfn">
<bean class="info.magnolia.rendering.renderer.ContextAttributeConfiguration">
<property name="name" value="cmsfn"/>
<property name="componentClass" value="info.magnolia.templating.functions.TemplatingFunctions"/>
</bean>
</entry>
<entry key="stkfn">
<bean class="info.magnolia.rendering.renderer.ContextAttributeConfiguration">
<property name="name" value="stkfn"/>
<property name="componentClass" value="info.magnolia.module.templatingkit.functions.STKTemplatingFunctions"/>
</bean>
</entry>
<!-- If you need the DAM templating functions in Freemarker uncomment this block to have them set as an attribute named 'damfn'.
-->
<entry key="damfn">
<bean class="info.magnolia.rendering.renderer.ContextAttributeConfiguration">
<property name="name" value="damfn"/>
<property name="componentClass" value="info.magnolia.dam.templating.functions.DamTemplatingFunctions"/>
</bean>
</entry>
</map>
</property>
</bean>
</property>
</bean>
</beans>


Exception



2015-03-29 13:04:01,494 ERROR rendering.engine.ModeDependentRenderExceptionHandler: Error while rendering [/brightit-website] with template [websiteModule:pages/mainTemplate] for URI [/brightit-website.html=mgnlPreview=false&mgnlChannel=desktop]:
RenderException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is info.magnolia.rendering.engine.RenderException: Can't render template /templates/websiteModule/pages/mainTemplate.jsp
info.magnolia.rendering.engine.RenderException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is info.magnolia.rendering.engine.RenderException: Can't render template /templates/websiteModule/pages/mainTemplate.jsp
at info.magnolia.module.blossom.render.BlossomTemplateRenderer.render(BlossomTemplateRenderer.java:86)
at info.magnolia.rendering.engine.DefaultRenderingEngine.render(DefaultRenderingEngine.java:106)
at info.magnolia.rendering.engine.DefaultRenderingEngine$$EnhancerByCGLIB$$f67b9c97.render(<generated>)
at info.magnolia.rendering.engine.RenderingFilter.render(RenderingFilter.java:204)
at info.magnolia.rendering.engine.RenderingFilter.handleTemplateRequest(RenderingFilter.java:139)
at info.magnolia.rendering.engine.RenderingFilter.doFilter(RenderingFilter.java:91)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.module.blossom.preexecution.BlossomFilter.doFilter(BlossomFilter.java:82)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.rendering.model.ModelExecutionFilter.doFilter(ModelExecutionFilter.java:101)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.AggregatorFilter.doFilter(AggregatorFilter.java:103)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.security.BaseSecurityFilter.doFilter(BaseSecurityFilter.java:57)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.RepositoryMappingFilter.doFilter(RepositoryMappingFilter.java:108)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.CompositeFilter.doFilter(CompositeFilter.java:65)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:74)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.CompositeFilter.doFilter(CompositeFilter.java:65)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.VirtualUriFilter.doFilter(VirtualUriFilter.java:68)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.module.cache.executor.Bypass.processCacheRequest(Bypass.java:58)
at info.magnolia.module.cache.executor.CompositeExecutor.processCacheRequest(CompositeExecutor.java:66)
at info.magnolia.module.cache.filter.CacheFilter.doFilter(CacheFilter.java:153)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.i18n.I18nContentSupportFilter.doFilter(I18nContentSupportFilter.java:73)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.RangeSupportFilter.doFilter(RangeSupportFilter.java:84)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.security.BaseSecurityFilter.doFilter(BaseSecurityFilter.java:57)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.security.SecurityCallbackFilter.doFilter(SecurityCallbackFilter.java:83)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.security.LogoutFilter.doFilter(LogoutFilter.java:94)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.module.templatingkit.filters.SiteMergeFilter.doFilter(SiteMergeFilter.java:112)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.MultiChannelFilter.doFilter(MultiChannelFilter.java:82)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.module.cache.filter.GZipFilter.doFilter(GZipFilter.java:73)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.security.auth.login.LoginFilter.doFilter(LoginFilter.java:120)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:82)
at info.magnolia.cms.filters.CosMultipartRequestFilter.doFilter(CosMultipartRequestFilter.java:89)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.module.devicedetection.filter.DeviceDetectionFilter.doFilter(DeviceDetectionFilter.java:71)
at info.magnolia.cms.filters.OncePerRequestAbstractMgnlFilter.doFilter(OncePerRequestAbstractMgnlFilter.java:58)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.ContentTypeFilter.doFilter(ContentTypeFilter.java:112)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.ContextFilter.doFilter(ContextFilter.java:129)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.MgnlFilterChain.doFilter(MgnlFilterChain.java:80)
at info.magnolia.cms.filters.CompositeFilter.doFilter(CompositeFilter.java:65)
at info.magnolia.cms.filters.AbstractMgnlFilter.doFilter(AbstractMgnlFilter.java:89)
at info.magnolia.cms.filters.SafeDestroyMgnlFilterWrapper.doFilter(SafeDestroyMgnlFilterWrapper.java:106)
at info.magnolia.cms.filters.MgnlFilterDispatcher.doDispatch(MgnlFilterDispatcher.java:66)
at info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:107)
at info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:93)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1074)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is info.magnolia.rendering.engine.RenderException: Can't render template /templates/websiteModule/pages/mainTemplate.jsp
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:965)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:844)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at info.magnolia.module.blossom.render.BlossomDispatcherServlet.forward(BlossomDispatcherServlet.java:132)
at info.magnolia.module.blossom.render.BlossomTemplateRenderer.render(BlossomTemplateRenderer.java:78)
... 113 more
Caused by: info.magnolia.rendering.engine.RenderException: Can't render template /templates/websiteModule/pages/mainTemplate.jsp
at info.magnolia.rendering.renderer.JspRenderer.onRender(JspRenderer.java:80)
at info.magnolia.module.blossom.view.JspTemplateViewRenderer.onRender(JspTemplateViewRenderer.java:95)
at info.magnolia.rendering.renderer.AbstractRenderer.render(AbstractRenderer.java:151)
at info.magnolia.module.blossom.view.TemplateView.renderMergedOutputModel(TemplateView.java:74)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
... 118 more
Caused by: java.lang.RuntimeException: javax.servlet.ServletException: File &quot;/templates/websiteModule/pages/mainTemplate.jsp&quot; not found
at info.magnolia.context.WebContextImpl.include(WebContextImpl.java:197)
at info.magnolia.rendering.renderer.JspRenderer.onRender(JspRenderer.java:74)
... 127 more
Caused by: javax.servlet.ServletException: File &quot;/templates/websiteModule/pages/mainTemplate.jsp&quot; not found
at org.apache.jasper.servlet.JspServlet.handleMissingResource(JspServlet.java:417)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:384)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at info.magnolia.cms.filters.MgnlFilterDispatcher.doDispatch(MgnlFilterDispatcher.java:74)
at info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:107)
at info.magnolia.cms.filters.MgnlMainFilter.doFilter(MgnlMainFilter.java:93)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:748)
at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:604)
at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:543)
at info.magnolia.module.blossom.support.ForwardRequestWrapper$1.include(ForwardRequestWrapper.java:192)
at info.magnolia.context.WebContextImpl.include(WebContextImpl.java:194)
... 128 more


If I'm using FreeMaker(.ftl) instead of .jsp everything works fine. Any ideas what am I doing wrong?




How to parse large files using flatpack



I need to parse files that may be quite large, possibly 100s of megabytes and millions of lines. I have been trying to do this using FlatPack. I would think the way to do this would be to use the buffered parsers and the new stream methods. But, despite that dataset.next() returns true for the correct number of records, the Optional returned by dataset.getRecord() never contains a value.


I have looked at this example/test but it only counts the number of record and does not actually do anything with the content. example/test




how to save a image recieved through network in java



image is successfully recieved at the server side and i can display it on label but my Problem is how to save that image i used



JFileChooser.showSaveDialog()



i tried printstream i can save the file but whenever i opened the file in image viewer it is showing as this type of file is cant be opened


Plz help me with this guys





BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(sock.getInputStream()));

System.out.println("Image received!!!!");

JFileChooser fc = new JFileChooser();
int i=fc.showSaveDialog(null);
if( i == JFileChooser.APPROVE_OPTION ) {

PrintStream ps = new PrintStream(fc.getSelectedFile());

// ImageIO.write(bimg,"JPG",fc.getInputStream());
ps.print( img);
ps.close();
lblNewLabel.setIcon(new ImageIcon(img)); //image is successfully displaying on the label
}



Connection persistence in HTTPClient 4.2.5



In the code below I will request 5 urls for million times, is there any way to establish a persistent connection?



//HTTPClient 4.2.5
static HttpClient httpClient;
static {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 1000);
HttpConnectionParams.setSoTimeout(params, 1000);
httpClient = new DefaultHttpClient(params);
}
public static String sendRequest(UUICRequest requset) throws
ClientProtocolException, IOException
{
HttpGet httpGet = new HttpGet(requset.toUrl());//only 5 urls will be request
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
String ret = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
httpGet.releaseConnection();
return ret;
}



Typical Hierarchical inheritance in Java



Consider this below code snippet



public class SuperClass {
public void move()
{
System.out.println("i am in super class");
}
}
public class SubClass1 extends SuperClass{
public void move()
{
System.out.println("i am in sub1 class");
}

}
public class SubClass2 extends SuperClass {

public void move()
{
System.out.println("i am in sub2 class");
}

}


Now i am creating object like this.



public class program {
public static void main(String[] args) {
SubClass1 obj = new SubClass2(); // Compile error - Type mismatch: cannot convert from SubClass2 to SubClass1
obj.move();
}
}


Why i can't do like this ? What stopping me to write this ??




Magnolia CMS create page/component template programmatically



I would like to keep all my settings, templates etc. in the repository. So it would be nice, to have it in separate files.


Is is possible to create magnolia template programmatically using the Standard Templating Kit? If yes, where can I find any useful information about that? I have searched in the magnolia documentation, but I didn't find anything about that.




How to Make a Diamond Shape Using Asterisks in Java (While Loop)?



I have to make a diamond shape using asterisks-* (shift-8). Compile and run the code and you will see that I have the first 3 lines, I just need the last 2 lines. I am only allowed to use a while loop for this assignment. And please, explain the logic for the whole code.



public class StarWhileLoop {
public static void main (String[] args) {
int row = 0;
while(row<3) {
int space = 2 - row;
while(space !=0) {
space--;
System.out.print(" ");

}
int asterisk = 1 + (row*2);
while(asterisk != 0) {
asterisk--;
System.out.print("*");
}
row++;
System.out.println();
}
while(row<2) {
int space = 2 - row;
while(space !=0) {
space--;
System.out.print(" ");
}
}
}
}



Putting data from an Array into a 2D array Java



Lets say I have an array of strings as followed



[red,black,blue,orange,green]


What I want to do is put this in a 2D array as so:



[red][black][blue][orange][green]
[red][black][blue][orange][green]
[red][black][blue][orange][green]


How can I accomplish this?