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?




Can I find jdk version of jsp project(Build using apache ant) using Can i find jdk version of a project using serialVersionUID number?



How can I find the version of jdk used for a jsp project using serialVersionUID number inside of a class file?





package com.bsh.kimclient.configuration;

import java.io.PrintStream;
import javax.servlet.http.HttpServlet;

public class ServiceInitServlet extends HttpServlet {

private static final long serialVersionUID = 3256726165010986496;

public ServiceInitServlet ()
public void init()
public void doGet(HttpServletRequest, HttpServletResponse)

}





Best technique in an offline and online newsfeed app like facebook



I am currently developing an android app that has newsfeed and relies the data from the backend. I just want to know what's the best technique to load it offline like facebook app. Do i have to create my local db?


And I want also to know how to load it faster when fetching data online. Because when I fetch data online it needs more seconds or minutes inorder to load my data from the backend. I am using libraries, retrofit and universal image loader.




mCamera.setpreview{@override onPreviewFrame() } not work




  • I want to record videos and analysis the current bitmap in service.

  • So I register surfaceHolder.addCallback in onStartCommand function.

  • And set mCamera.setPreviewCallback in surfaceCreated function.

  • When I start the Service, it seems that the onPreviewFrame function never work.


I don't know why, Can anybody give me a hand?


Here is my code of onStartCommand function in Service.



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Util.checkCameraHardware(this)) {
mCamera = Util.getCameraInstance();
if (mCamera != null) {
SurfaceView sv = new SurfaceView(this);

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);


SurfaceHolder sh = sv.getHolder();

sv.setZOrderOnTop(true);
sh.setFormat(PixelFormat.TRANSPARENT);


sh.addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
Camera.Parameters params = mCamera.getParameters();
mCamera.setParameters(params);
Camera.Parameters p = mCamera.getParameters();

List<Camera.Size> listSize;

listSize = p.getSupportedPreviewSizes();
Camera.Size mPreviewSize = listSize.get(2);
Log.v("TAG", "preview width = " + mPreviewSize.width
+ " preview height = " + mPreviewSize.height);
p.setPreviewSize(mPreviewSize.width, mPreviewSize.height);

listSize = p.getSupportedPictureSizes();
Camera.Size mPictureSize = listSize.get(2);
Log.v("TAG", "capture width = " + mPictureSize.width
+ " capture height = " + mPictureSize.height);
p.setPictureSize(mPictureSize.width, mPictureSize.height);
mCamera.setParameters(p);
try {
mCamera.setPreviewDisplay(holder);

/***************************************************************************/
mCamera.setPreviewCallback(new Camera.PreviewCallback() {
@Override
public void onPreviewFrame(byte[] data, Camera camera) {
if (_calibrationsLeft == -1)
return;

if (_calibrationsLeft > 0) {
// Doing calibration !

if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
// Drop Frame
return;
}

// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();

if (_currentFaceDetectionThread != null) {
_calibrationsLeft--;
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());

if (_calibrationsLeft == 0) {
doneCalibrating();
return;
}
}

_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();

} else {
// Simple Measurement

if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
// Drop Frame
return;
}

// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();

if (_currentFaceDetectionThread != null)
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());

_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
}
}
});
/****************************************************************************/
} catch (IOException e) {
e.printStackTrace();
}
mCamera.startPreview();
MessageHUB.get().sendMessage(MessageHUB.LOG_PREVIEW, null);
mCamera.unlock();
calibrate();
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});


wm.addView(sv, params);

} else {
Log.d("TAG", "==== get Camera from service failed");

}
} else {
Log.d("TAG", "==== There is no camera hardware on device.");
}

return super.onStartCommand(intent, flags, startId);
}



Is it safe to assume Spring ApplicationContext is initialized only once?



We have built a messaging server using PubNub which listens for chat messages from Android device. For this, our J2EE based spring, we have created a Pubnub listener (which is basically a listening socket) as follows. Since this needs to be created only once and at a application startup, we are using ContextRefreshedEvent for the same.


I am particularly doubtful about the use isContextLoaded variable since we are observing WTF: Not initialising incoming listener logs in our server randomly which I believe should not be there since context is initialised only once.



public class IncomingListener implements ApplicationListener < ContextRefreshedEvent > {

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {

private static volatile boolean isContextLoaded = false;

@Autowired
ServletContext application;

synchronized(IncomingListener.class) {

if (isContextLoaded) {
System.out.println("WTF: Not initializing incoming listener");
return;
}
try {
initialiseIncomingListener();
isContextLoaded = true;
} catch (JSONException e) {
e.printStackTrace();
} catch (AkoshaException e) {
e.printStackTrace();
}

}
}

private void initialiseIncomingListener()
{
// Initialize our Pubnub Listener

pubnub.subscribe(serverchannel, new Callback() {

// Subscribe to pubnub
});
}
}



Play Framework 2.3 jvm memory on run



I'm trying to increase Jvm memory of my application but doesn't matter what I use I get 256Mb as max memory. To see the max memory I am using



val instance = Runtime.getRuntime();
val mb = 1024 * 1024;
val maxm = ("Max Memory: " + instance.maxMemory() / mb);


I tried to to run the app with...



activator -Xms512M -Xmx512M run
activator -mem 512 -J-server run //this doesn't run
env JAVA_OPTS="-Xms512m -Xmx512m" && activator run
env JAVA_OPTS="-mem 512" && activator run
env JAVA_OPTS="-XX:MetaspaceSize=64M -XX:MaxMetaspaceSize=512M" && activator run
env JAVA_OPTS="-DX:MetaspaceSize=64m -DX:MaxMetaspaceSize=512m" && activator run


Am I doing this on the wrong way?




servlet dependency error after add browsermob-proxy lib



after add browsermob-proxy to the pom.xml, when I was trying to start the webapp, it threw an exception: enter image description here




Reading long binary numbers in java



I am trying to write a program which converts binary numbers into decimal, however as soon as I have a binary number which is bigger than 10 digits I get a java.lang.numberformatexception error. I was wondering how I should rewrite my code in order to handle binary numbers:



try{
//will throw an exception if the user's input contains a non-Integer
int inputNumber = Integer.parseInt(returnEnterNumber());
//when our user wants to convert from binary to decimal
if(binaryToDecimal.isSelected()){
//checks if number is binary
int checkNumber = inputNumber;
while (checkNumber != 0) {
if (checkNumber % 10 > 1) {
throw new InvalidBinaryException();
}
checkNumber = checkNumber / 10;
}
//converts from binary and outputs result
int n = Integer.parseInt(returnEnterNumber(), 2);
displayConvertedNumber(Integer.toString(n));
}
}
catch(Exception e) {
displayConvertedNumber("WRONG INPUT! - TRY again");
}



How do I fix this program that transforms into bit pattern all numbers that are multiply of 5 between 5 and 100 (inclusive)



How do I make this program count from 5 to 100 using for loops. For example it should be like this:

bit pattern representation of 5 is 101.

bit pattern representation of 10 is 1010.

bit pattern representation of 15 is 1111


I already did the code to convert decimal to binary, but I want it to start at 5 and go to 100 from multiples of 5. I know you have to put a for loop statement somewhere but don't know where.



public static void main(String[] args) {

int x=5;
String binaryString = " ";
int remainder = 0;
int decimalNumber=x;

for (int i = 1; decimalNumber > 0; i++) {
binaryString = String.valueOf(decimalNumber&1) + binaryString;
remainder = decimalNumber % 2;
decimalNumber /= 2;
}

System.out.println("bit pattern representation of "+x+" is "+binaryString);
}



Modifying Iterator to Display the Elements in the Order they were Received



I'm having difficulty printing elements out in the order they were entered. My program is reading a .txt file.


I'm using a Queue to store the elements which I thought was a FIFO. But when I run my program I get the elements in reverse order. I thought I'd try a Priority Que but instead I was rewarded with an alphabetically sorted order.


If anyone has any ideas or directions I should go to find the answer I'd really appreciate it. Thanks.



public Iterable<Key> keys()
{
Queue<Key> queue = new Queue<Key>();

for (Node x = first; x != null; x = x.next)

queue.enqueue(x.key);

return queue;
}



Hi 99tm . Do you know anyway to export PDF by Java with Japanese language. I try to use Itext but it have a large fee



Do you know anyway to export PDF by Java with Japanese language. I try to use Itext but it have a large fee




Getting stack overflow error when running recursive linear search



I realize that a binary search would be much more efficient and I even have one working but I'm required to write a recursive linear search for a lab. i keep getting stack overflow on the method linSearch(), specifically on line 33.


I'm required to search arrays as big as 1,280,000.



import java.util.Scanner;
public class linSearch {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("enter size");
int size = in.nextInt();
System.out.println("enter numb");
double numb = in.nextDouble();
double [] array = new double[size];
for(int i = 0; i < 30; i++){
for(int j = 0; j < size-1; j++){
double random = (int)(Math.random() * 1000000);
array[j] = (double)(random / 100);
}
int position = linSearch(array, numb, 0);
if(position == -1){
System.out.println("the term was not found");
}
else{
System.out.println("the term was found");
}
}
}
public static int linSearch(double[] array, double key, int counter){
if(counter == array.length){
return -1;
}
if(array[counter] == key){
return counter;
}
else{
counter += 1;
return linSearch(array, key, counter); //error occurs here
}
}
}



Iterative deepening depth first search in a 2d array



I am trying to implement iterative deepening search in a 2d array (a maze).



static void Run_Ids(int x, int y)
{
int depth_limit = 0;

while(!cutoff)
{
out.println("Doing search at depth: " + depth_limit);
depthLimitedSearch(x, y, depth_limit);
depth_limit++;
}
}


And here's my Limited depth first search using a stack. For some reason, it goes back and forth between two cells. It doesn't expand like it should. I think its something wrong with my DFS algorithm here.



static void depthLimitedSearch(int x, int y, int depth){
Pair successor; //pair is the x, y co-ordinate
successor = starting(); //set the successor to starting cell

stack = new Stack<>();
int i = 0;
stack.push(successor);

while (!stack.isEmpty())
{
out.println("i level: " + i);
Pair parent = stack.peek(); //pop it here?

if (parent.x == Environment.goal[0] && parent.y == Environment.goal[1]){ //check to see if it is the goal
cutoff = true;
out.println("goal found ");
break;
}
if (i == depth){
//stack.pop(); //pop here?
break;
}
else{

Pair leftPos,rightPos,upPos,downPos;
leftPos = leftPosition(parent.x, parent.y);
rightPos = rightPosition(parent.x, parent.y);
upPos = upPosition(parent.x, parent.y);
downPos = downPosition(parent.x, parent.y);


if(Environment.isMovePossible(rightPos.x, rightPos.y))
//if it can go right
stack.push(rightPos);

if(Environment.isMovePossible(leftPos.x, leftPos.y))
// if it can go left
stack.push(leftPos);

if(Environment.isMovePossible(downPos.x, downPos.y))
//if it can go down
stack.push(downPos);

if(Environment.isMovePossible(upPos.x, upPos.y))
//if it can go up
stack.push(upPos);


stack.pop(); //pop here?


} //else

i++;

}//while
}


I don't have that much experience with stack, and i am confused as to where to push it and where to pop. if somebody in here can point me to the right direction, that would be great!




java animation, making an object change color every 'x' seconds



hi there i was just wondering if someone could help me or give me some advice with timers, the problem i have got is that i need an object to change color every x seconds on click of a button 'flash' and stay a single color on click of a button 'steady' so far i have got my buttons to work i just cant seem to get the object to 'flash'(change color on its own). my code is below and works without problems.



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


/**
* Created by joe on 26/03/15.
*/

class Beacon extends JPanel {
private boolean lightOn = true;

private int x = 150;
private int y = 90;
private int ballSize = 55;

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
if (lightOn){
g2.setColor(Color.BLACK);
g2.fillRect(172, 140, 12, 30);
g2.drawRect(172, 170, 11, 30);
g2.fillRect(172, 200, 12, 30);
g2.drawRect(172, 230, 11, 30);
g2.fillRect(172, 260, 12, 30);
g2.drawRect(172, 290, 11, 30);
g2.fillRect(172, 320, 12, 30);
g2.drawRect(172, 350, 11, 30);
g2.setColor(Color.ORANGE);
g2.fillOval(x, y, ballSize, ballSize);
}
else{
g2.setColor(Color.BLACK);
g2.fillRect(172, 140, 12, 30);
g2.drawRect(172, 170, 11, 30);
g2.fillRect(172, 200, 12, 30);
g2.drawRect(172, 230, 11, 30);
g2.fillRect(172, 260, 12, 30);
g2.drawRect(172, 290, 11, 30);
g2.fillRect(172, 320, 12, 30);
g2.drawRect(172, 350, 11, 30);
g2.setColor(Color.GRAY);
g2.fillOval(x, y, ballSize, ballSize);
} }
public void lightOn() { lightOn = true; }
public void lightOff() { lightOn = false; }
}

public class BeaconViewer extends JFrame
{
JButton Flash = new JButton("Flash");
JButton Steady = new JButton("Steady");
JPanel bPanel = new JPanel();
Beacon bbPanel = new Beacon();



public BeaconViewer()
{
bPanel.add(Flash);
this.add(bPanel, BorderLayout.SOUTH);
bPanel.add(Steady);
this.add(bbPanel, BorderLayout.CENTER);
Flash.addActionListener(new FlashListener());
Steady.addActionListener(new SteadyListener());
}

class FlashListener implements ActionListener {

public void actionPerformed(ActionEvent e) {
bbPanel.lightOff();
repaint();

}

}

class SteadyListener implements ActionListener {

public void actionPerformed(ActionEvent a) {
bbPanel.lightOn();
repaint();
}

}

public static void main(String[] args) {
JFrame scFrame = new BeaconViewer();
scFrame.setTitle("Belish Beacon");
scFrame.setSize(300, 500);
scFrame.setDefaultCloseOperation((JFrame.EXIT_ON_CLOSE));
scFrame.setVisible(true); }}



services.xml build.xml cannot generate the stubs



build xml file



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE project>
<project name="3500259" basedir="." default="generate.stubs">
<property environment="env"/>
<property file="build.properties"/>
<property name="build.dir" value="build"/>
<path id="axis2.classpath">
<!-- pick up log4j.properties in the project root -->
<pathelement location="./src"/>
<fileset dir="F:\axisServiceHome\axis2-1.6.2/lib">
<include name="*.jar"/>
</fileset>
</path>
<target name="generate.stubs">
<!-- modified and commented by 3500259 -->
<java classname="org.apache.axis2.wsdl.WSDL2Java" classpathref="axis2.classpath">
<!-- the location of the wsdl (which is automatically generated
by Axis) -->
<arg line="-uri ${librarywsdl.uri}"/>
<!-- overwrite existing generated code (if it exists) -->
<arg line="-or"/>
<!-- Generate Java stub (since axis is multi-language) -->
<arg line="-l java"/>
<!-- unwrap paramaters to java types -->
<arg line="-uw"/>
<!-- specifiy destination package -->
<arg line="-p stubs"/>
<!-- databinding technique between SOAP and Java (ADB=proprietry
Axis data binding) -->
<arg line="-d adb"/>
</java>
</target>
</project>


build properties file



librarywsdl.uri=http://localhost:8080/axis2/services/Library?wsdl
axis2.home=F:/axisServiceHome/axis2-1.6.2


services xml file



<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<servicegroup>
<service name="AccommodationServiceImpl"class="accommodation.AccommodationServiceImpl"scope="application" targetNamespace="http://AccommodationServiceImpl/">
<description>AccommodationService</description>
<messageReceivers>
<messageReceiver mep="http://ift.tt/1v6LyEG"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://ift.tt/1sYKKjP"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</messageReceivers>
<schema schemaNamespace="http://AccommodationServiceImpl/xsd" />
<parameter name="AccommodationServiceImpl">AccommodationServiceImpl</parameter>
</service>
<service name="AirlineServiceImpl" class="airline.AirlineServiceImpl" scope="application" targetNamespace="http://AirlineServiceImpl/">
<description>AirlineService</description>
<messageReceivers>
<messageReceiver mep="http://ift.tt/1v6LyEG"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://ift.tt/1sYKKjP"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver" />
</messageReceivers>
<schema schemaNamespace="http://AirlineServiceImpl/xsd" />
<parameter name="AirlineServiceImpl">AirlineServiceImpl</parameter>
</service>
</servicegroup>


error are throw out



Retrieving document at '${librarywsdl.uri}'.
[java] org.apache.axis2.wsdl.codegen.CodeGenerationException: Error parsing WSDL


Is there anything wrong with the three files? I cannot generate the .arr file. These three files are from a web service project I am working on.




Using Icon and myIcon



I am practicing using Icon and myIcon and am getting an error saying that myIcon must be defined in its own file. I am pretty sure I defined it within the code and am confused what I did wrong.



import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class TestIcon {
public static void main(String[] args) {
myIcon icn = new myIcon(40,50);
JOptionPane.showMessageDialog(null, "Hello World!", "Message", JOptionPane.INFORMATION_MESSAGE, icn);
}
}

public class myIcon implements Icon{
private int width;
private int height;

public myIcon(int width, int height) {
this.width=width;
this.height=height;
}
public int getIconWidth(){
return width;
}
public int getIconHeight(){
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y){
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double ellipse = new Ellipse2D.Double(x,y,width, height);

g2.setColor(Color.RED);
g2.fill(ellipse);
}
}



Define a Dual array to be an array where every value occurs exactly twice




  1. Define a Dual array to be an array where every value occurs exactly twice.


For example, {1, 2, 1, 3, 3, 2} is a dual array.


The following arrays are not Dual arrays {2, 5, 2, 5, 5} (5 occurs three times instead of two times) {3, 1, 1, 2, 2} (3 occurs once instead of two times)


Write a function named isDual that returns 1 if its array argument is a Dual array. Otherwise it returns 0.


If you are programming in Java or C#, the function signature is int isDual (int[ ] a)




Spring Templates in Docker Container



So I've been trying to dockerify my spring-mvc 4 app using the java:8 base image:


I'm having trouble on the following line when running in docker, but outside of docker everything works fine! It has to do with finding the template files for my project:



@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("classpath:/pages/");
}


As a note, I've tried running with the template files inside of a jarfile and outside of a jarfile. The url debugging code has shown that it's finding the right files, but when it tries to use them, I get the following exception:



engine_1 | jvm 1 |java.io.FileNotFoundException: class path resource [pages/saga-index.html] cannot be resolved in the file system for resolving its last-modified timestamp
engine_1 | jvm 1 | at org.springframework.core.io.AbstractResource.lastModified(AbstractResource.java:155)
engine_1 | jvm 1 | at org.springframework.core.io.AbstractFileResolvingResource.lastModified(AbstractFileResolvingResource.java:169)
engine_1 | jvm 1 | at org.springframework.web.servlet.resource.ResourceHttpRequestHandler.handleRequest(ResourceHttpRequestHandler.java:229)
engine_1 | jvm 1 | at org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter.handle(HttpRequestHandlerAdapter.java:51)
engine_1 | jvm 1 | at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
engine_1 | jvm 1 | at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
engine_1 | jvm 1 | at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
engine_1 | jvm 1 | at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
engine_1 | jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
engine_1 | jvm 1 | at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
engine_1 | jvm 1 | at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
engine_1 | jvm 1 | at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:684)
engine_1 | jvm 1 | at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:503)
engine_1 | jvm 1 | at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)


How can i get through this exception? Why am I not able to get a timestamp?


(More stats)



$ docker exec siteconfiguration_engine_1 java -version
openjdk version "1.8.0_40-internal"
OpenJDK Runtime Environment (build 1.8.0_40-internal-b27)
OpenJDK 64-Bit Server VM (build 25.40-b25, mixed mode)

$ docker exec siteconfiguration_engine_1 df -h
Filesystem Size Used Avail Use% Mounted on
none 19G 2.5G 15G 15% /
tmpfs 1004M 0 1004M 0% /dev
shm 64M 0 64M 0% /dev/shm
/dev/sda1 19G 2.5G 15G 15% /etc/hosts



ActivityNotFoundException not resolving



I want to open activity via broadcast receiver , i tried any ways , but i am getting ActivityNotFoundException , my activity is working on normal mode, but when i want to open it from BroadCastRecevier it cause ActivityNotFoundException error,


It is my manifest ,



<activity
android:excludeFromRecents="true"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:name="com.alexis.abc.ui.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


And it is my broadcast receiver ,



Intent intent2 = new Intent(context, MainActivity.class);
intent2.addCategory("android.intent.category.LAUNCHER");
intent2.setAction("android.intent.action.MAIN");
context.startActivity(intent2);


Here is steps :

1 - I opening application and hiding launcher icon via following code



PackageManager packageManager = getContext().getPackageManager();
ComponentName componentName = new ComponentName(getContext(), MainActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);


2 - I exiting to application and dialing a number (To triggering broadcast event) and i getting following exception



android.content.ActivityNotFoundException: Unable to find explicit activity class {http://ift.tt/1ESr3ib}; have you declared this activity in your AndroidManifest.xml?