Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, April 25, 2015

Threads share static variable but behave differently with respect to it

Here is my code. Obviously this doesn't do a lot but that's only because I abstracted out the problem so that you guys didn't have so many lines to decipher.

Java Code:

import java.util.Scanner;

class threadOne extends threadTwo {
        
        public static void main(String[] args) {
                
                threadTwo threadTwoObj = new threadTwo();
                threadTwoObj.start();
                
                while (!userInput.equals("exit")) {
                        Scanner scannerObj = new Scanner(System.in);
                        userInput = scannerObj.nextLine();
                }
                
        }
        
}

Java Code:

class threadTwo implements Runnable {

        private Thread threadObj;
        public static String userInput = "default";

        public void start() {
                threadObj = new Thread (this, "Thread Two");
                threadObj.start();
        }
        
        public void run() {
                while (!userInput.equals("exit")) {}
        }
}
What its supposed to do: When the user returns "exit" in the console it is supposed to break out of both while loops in both threads.
What it actually does: breaks out of the while loop in threadOne and not in threadTwo.

In case you are wondering the idea behind this, basically the idea is to have a thread running doing computation and another thread able to query it for updates or interact to make changes to the flow. This will be useful, among other ways, for the sorts of problems where finding a solution is easy but where a better solution can always be found with more time. So for example finding directions on a map. Its easy to find a solution, but if you search longer you can find a faster route, if you search longer still than faster still.

Sunday, April 19, 2015

Implementing a card game in JAVA - Help with deck


I have jsut simplified the construtor to jsut print the value of masterPack[0].

I get an exception, the problem is masterPack is not accepted in the Construtor.. i dont know why?


public Dec(int val)

{

allocateMasterPack();

System.out.println("Printing the values in constructor");

cards = new Card[52];

for (int k = 0; k < cards.length; k++)

cards[k]= new Card();

System.out.println ( masterPack[0]);

// init(val);


}


Output:

======

allocateMasterPack() activated

Construting the masterPAck

Value at index 8 is9 of Clubs

Printing the values now

Value at index 0 isA of Clubs


Printing the values now

Value at index 1 is2 of Clubs


Exception in thread "main" Printing the values now

Value at index 2 is3 of Clubs


Printing the values now

Value at index 3 is4 of Clubs


Printing the values now

Value at index 4 is5 of Clubs


Printing the values now

Value at index 5 is6 of Clubs


Printing the values now

Value at index 6 is7 of Clubs


Printing the values now

Value at index 7 is8 of Clubs


Printing the values now

Value at index 8 is9 of Clubs


Printing the values now

Value at index 9 isT of Clubs


Printing the values now

Value at index 10 isJ of Clubs


Printing the values now

Value at index 11 isQ of Clubs


Printing the values now

Value at index 12 isK of Clubs


Printing the values now

Value at index 13 isA of diamonds


Printing the values now

Value at index 14 is2 of diamonds


Printing the values now

Value at index 15 is3 of diamonds


Printing the values now

Value at index 16 is4 of diamonds


Printing the values now

Value at index 17 is5 of diamonds


Printing the values now

Value at index 18 is6 of diamonds


Printing the values now

Value at index 19 is7 of diamonds


Printing the values now

Value at index 20 is8 of diamonds


Printing the values now

Value at index 21 is9 of diamonds


Printing the values now

Value at index 22 isT of diamonds


Printing the values now

Value at index 23 isJ of diamonds


Printing the values now

Value at index 24 isQ of diamonds


Printing the values now

Value at index 25 isK of diamonds


Printing the values now

Value at index 26 isA of Hearts


Printing the values now

Value at index 27 is2 of Hearts


Printing the values now

Value at index 28 is3 of Hearts


Printing the values now

Value at index 29 is4 of Hearts


Printing the values now

Value at index 30 is5 of Hearts


Printing the values now

Value at index 31 is6 of Hearts


Printing the values now

Value at index 32 is7 of Hearts


Printing the values now

Value at index 33 is8 of Hearts


Printing the values now

Value at index 34 is9 of Hearts


Printing the values now

Value at index 35 isT of Hearts


Printing the values now

Value at index 36 isJ of Hearts


Printing the values now

Value at index 37 isQ of Hearts


Printing the values now

Value at index 38 isK of Hearts


Printing the values now

Value at index 39 isA of Spades


Printing the values now

Value at index 40 is2 of Spades


Printing the values now

Value at index 41 is3 of Spades


Printing the values now

Value at index 42 is4 of Spades


Printing the values now

Value at index 43 is5 of Spades


Printing the values now

Value at index 44 is6 of Spades


Printing the values now

Value at index 45 is7 of Spades


Printing the values now

Value at index 46 is8 of Spades


Printing the values now

Value at index 47 is9 of Spades


Printing the values now

Value at index 48 isT of Spades


Printing the values now

Value at index 49 isJ of Spades


Printing the values now

Value at index 50 isQ of Spades


Printing the values now

Value at index 51 isK of Spades


Printing the values in constructor

java.lang.NullPointerException

at Dec.<init>(debug.java:195)

at debug.main(debug.java:7)



JavaFX adding spots to linked list


For javafx code, I made a KeyEvent and a MouseEvent where the user clicks on the screen and a spot will appear (spot is an inner class that I defined), but how can I add each spot that appears on the screen into my dotList? I am not sure how to do that?



Java Code:



public void start(Stage stage) {
dotList = new SinglyLinkedList<>();
Pane root = new Pane();

root.setOnMouseClicked(event ->
root.getChildren().add(
new Spot(
event.getX(),
event.getY()
)
)
);

Scene scene = new Scene(root, SIZE, SIZE, Color.BLACK);
scene.setOnKeyTyped(event -> {
switch (event.getCharacter()) {
case "1":
currentColor = Color.RED;
break;
case "2":
currentColor = Color.BLUE;
break;
case "3":
currentColor = Color.GREEN;
}
});

stage.setScene(scene);
stage.show();
}


Friday, April 17, 2015

So lost


Alright guys, I am a little lost at this point I feel like I have gotten the majority of the program down but when it comes to coming up with the weighted average Im lost. Here is the assignment:


. write a program in JAVA in response to the following prompt:


Design a GUI program to find the weighted average of four test scores. The four test scores and their respective weights are given in the following format:


testscore1 weight1

...


For example, the sample data is as follows:


75 0.20

95 0.35

85 0.15

65 0.30


The user is supposed to enter the data and press a Calculate button. The program must display the weighted average.


Here is what I have written:


import javax.swing.*;

import java.awt.*;

import java.awt.event.*;


public class weightedaverage2 extends JFrame

{

private JLabel Score1L,Score2L,Score3L,Score4L;

private JLabel Weight1L,Weight2L,Weight3L,Weight4L;


private JTextField Score1TF,Score2TF,Score3TF,Score4TF;

private JTextField Weight1TF,Weight2TF,Weight3TF,Weight4TF;


private JLabel ResultMessage;

private JTextField Result;


private JButton CalculateB, ExitB;


private CalculateButtonHandler cbHandler;

private ExitButtonHandler ebHandler;


private static final int WIDTH = 400;

private static final int HEIGHT = 800;


public weightedaverage2()

{


Score1L = new JLabel("Score 1: ", SwingConstants.RIGHT);

Weight1L = new JLabel("Weight: ", SwingConstants.RIGHT);

Score2L = new JLabel("Score 2: ", SwingConstants.RIGHT);

Weight2L = new JLabel("Weight: ", SwingConstants.RIGHT);

Score3L = new JLabel("Score 2: ", SwingConstants.RIGHT);

Weight3L = new JLabel("Weight: ", SwingConstants.RIGHT);

Score4L = new JLabel("Score 4: ", SwingConstants.RIGHT);

Weight4L = new JLabel("Weight: ", SwingConstants.RIGHT);


ResultMessage = new JLabel("Average Weight: ", SwingConstants.RIGHT);


Score1TF = new JTextField(10);

Weight1TF = new JTextField(10);

Score2TF = new JTextField(10);

Weight2TF = new JTextField(10);

Score3TF = new JTextField(10);

Weight3TF = new JTextField(10);

Score4TF = new JTextField(10);

Weight4TF = new JTextField(10);


Result = new JTextField(10);


Calculate.add(ResultMessage);

Calculate.add(Result);


CalculateB = new JButton("Calculate");

cbHandler = new CalculateButtonHandler();

CalculateB.addActionListener(cbHandler);


ExitB = new JButton("Exit");

ebHandler = new ExitButtonHandler();

ExitB.addActionListener(ebHandler);


setTitle("Weighted Average Calculator");


Container pane = getContentPane();


pane.setLayout(new GridLayout(9,2));


pane.add(Score1L);

pane.add(Score1TF);


pane.add(Weight1L);

pane.add(Weight1TF);


pane.add(Score2L);

pane.add(Score2TF);


pane.add(Weight2L);

pane.add(Weight2TF);


pane.add(Score3L);

pane.add(Score3TF);


pane.add(Weight3L);

pane.add(Weight3TF);


pane.add(Score4L);

pane.add(Score4TF);


pane.add(Weight4L);

pane.add(Weight4TF);


pane.add(CalculateB);

pane.add(ExitB);


setSize(WIDTH, HEIGHT);

setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}


private class CalculateButtonHandler implements ActionListener

{


public void actionPerformed(ActionEvent e)

{


double Score1, Weight1, Score2, Weight2, Score3, Weight3, Score4, Weight4;


Score1 = Double.parseDouble(Score1TF.getText ());

Weight1 = Double.parseDouble(Weight1TF.getText ());

Score2 = Double.parseDouble(Score2TF.getText ());

Weight2 = Double.parseDouble(Weight2TF.getText ());

Score3 = Double.parseDouble(Score3TF.getText ());

Weight3 = Double.parseDouble(Weight3TF.getText ());

Score4 = Double.parseDouble(Score4TF.getText ());

Weight4 = Double.parseDouble(Weight4TF.getText ());


Result = Weight1+Weight2+Weight3+Weight4;


}

}



Thursday, April 16, 2015

Injection not working!


I need some help here, Injection not working!

I am missing something (getting a null pointer for the entityManager)


The spring entry point, web.xml



Java Code:



<web-app version="2.4" xmlns="http://ift.tt/qzwahU"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/qzwahU http://ift.tt/16hRdKA">

<display-name>score progress</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>


<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>

The mayor spring.xml (after resolving I will split this file into two)

Java Code:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xmlns:aop="http://ift.tt/OpNdV1"
xmlns:context="http://ift.tt/GArMu7"
xmlns:tx="http://ift.tt/OGfeU2"
xmlns:jee="http://ift.tt/OpNaZ5"

xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e
http://ift.tt/OpNdV1
http://ift.tt/QEDs1g
http://ift.tt/GArMu7
http://ift.tt/QEDs1k
http://ift.tt/OGfeU2
http://ift.tt/1cQrvTl
http://ift.tt/OpNaZ5
http://ift.tt/1j5lSTg"
default-lazy-init="true" default-autowire="byName">

<context:component-scan base-package="com.canteratech.scoreprogress" />
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager" />
<!--
<import resource="classpath:scoreprogress-spring-core.xml" />
<import resource="scoreprogress-spring/jpa.xml" />
-->

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/scoreprogress"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--
<property name="persistenceUnitName" value="scoreprogress-jpa"/>
-->
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="packagesToScan" value="com.canteratech.scoreprogress" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
</props>
</property>
</bean>

<tx:annotation-driven/>
<!--
<tx:annotation-driven transaction-manager="transactionManager" />
-->
<bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="entityManager" class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
<property name="entityManagerFactory" ref="entityManagerFactory"/>

</bean>
</beans>

and finally the entityManger injection (which turns out to be null)

Java Code:



@Component(value = "userDao")
public class UserDaoImpl implements UserDao {

//@Autowired
@PersistenceContext(name="dataSource")
protected EntityManager entityManager;
….


Wednesday, April 15, 2015

Cannot Link ActionListener with ActionEvent


I need to crerate the interface for the input iof data for rectangle and then to display it by coordinates (and color fill).

Here is rectangl class, rectanglview class, mainview (input) class, Controller, Aplication classes.

1)

package recct;

import java.awt.Color;

import java.awt.EventQueue;

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Rectangle2D;

import javax.swing.JComponent;

import javax.swing.JFrame;

import java.lang.Object;

import java.awt.geom.RectangularShape;

import java.awt.geom.Rectangle2D.Double;


public class Pkutnyk extends Rectangle2D.Double {

private double x1;

private double y1;

private double w;

private double h;

private String color;

public Pkutnyk(double x1, double y1, double w, double h) {

this.x1=x1;

this.y1=y1;

this.w=w;

this.h=h;

}


public double getWidth(){ return w;}

public double getHeight(){ return h;}

public double getX1(){return x1;}

public double getY1(){return y1;}


public String getColor() {

return color;

}


public void setColor(String color) {

this.color = color;

}

}

2)

package recct;

import java.awt.GridBagConstraints;

import java.awt.GridBagLayout;

import java.awt.Insets;

import java.awt.event.ActionListener;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import javax.swing.JTextField;

public class MainView extends JFrame {

private JLabel firstPointX = new JLabel(

"Enter X coordinate of first point");

private JTextField firstPointXt = new JTextField(10);

private JLabel firstPointY = new JLabel(

"Enter Y coordinate of first point");

private JTextField firstPointYt = new JTextField(10);

private JLabel secondPointX = new JLabel(

"Enter X coordinate of second point");

private JTextField secondPointXt = new JTextField(10);

private JLabel secondPointY = new JLabel(

"Enter Y coordinate of second point");

private JTextField secondPointYt = new JTextField(10);

private JLabel rectangleColor = new JLabel("Enter Color");

private JTextField rectangleColort = new JTextField(10);

private JButton button = new JButton("Draw");

public MainView() {

JPanel panel = new JPanel();

this.setTitle("Main");

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );

this.setSize(200, 500);

this.setLocationRelativeTo(null);

this.setLayout(new GridBagLayout());

this.setVisible(true);

panel.add(firstPointX);

panel.add(firstPointXt);

panel.add(firstPointY);

panel.add(firstPointYt);

panel.add(secondPointX);

panel.add(secondPointXt);

panel.add(secondPointY);

panel.add(secondPointYt);

panel.add(rectangleColor);

panel.add(rectangleColort);

panel.add(button);

this.add(panel, new GridBagConstraints(0, 0, 1, 1, 1, 1,

GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(

2, 2, 2, 2), 0, 0));

}

public double getFirstPointX() {

return Double.parseDouble(firstPointXt.getText());

}

public double getFirstPointY() {

return Double.parseDouble(firstPointYt.getText());

}

public double getWidtht() {

return Double.parseDouble(secondPointXt.getText())-getFirstPointX();

}

public double getHeightt() {

return Double.parseDouble(secondPointYt.getText())-getFirstPointY();

}

public String getrectangleColor() {

return rectangleColort.getText();

}

public void addButtonListener(ActionListener listenForButton) {

button.addActionListener(listenForButton);

}

void displayErrorMessage(String errorMessage){

JOptionPane.showMessageDialog(this, errorMessage);

}

}


3)

package recct;

import java.awt.Color;

import java.awt.Graphics;

import java.awt.Graphics2D;

import javax.swing.JFrame;

import javax.swing.JPanel;

import java.awt.geom.Rectangle2D;

public class RectangleView extends JPanel {

double x;

double y;

double w;

double h;


public void paintComponent(Graphics g) {

Graphics2D g2 = (Graphics2D) g;

Pkutnyk rect = new Pkutnyk(x, y, w, h);

g2.setPaint(Color.RED);

g2.fill(rect);


}

public void main() {

RectangleView rects = new RectangleView();

JFrame frame = new JFrame("Pryamokutnyk");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);

frame.add(rects);

frame.setSize(360, 300);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

4)

package recct;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class Controller {


private Pkutnyk pkut;

private MainView mainView;

private RectangleView rview;


public Controller(Pkutnyk pkut, MainView mainView) {

this.pkut = pkut;

this.mainView = mainView;

this.mainView.addButtonListener(new ButtonListener());

}


class ButtonListener implements ActionListener {


public void actionPerformed(ActionEvent arg0) {

try {

rview.x = mainView.getFirstPointX();

rview.y = mainView.getFirstPointY();

rview.w = mainView.getWidtht();

rview.h = mainView.getHeightt();

rview.main();

mainView.setVisible(false);

rview.setVisible(true);


} catch (NumberFormatException ex) {

System.out.println(ex);


}

}

}

}


5)

package recct;

public class Appl {

public static void main(String[] args) {

MainView mainView = new MainView();

RectangleView rectView=new RectangleView();

mainView.setVisible(true);

rectView.setVisible(false);

}

}



Tuesday, April 14, 2015

Cannot Find symbol compile error, need help!


I decided to code this quiz I took in class about asking the user to input a string and the code is suppose to check for upper case letters. If a upper case letter is found, it should increase a count by one. Once the check is done, it should display the number of uppercase letters. For some reason I am getting this weird compile error stating that symbols can't be found. Can anyone help me?



Java Code:



import java.util.*;
import java.lang.*;
public class StringCheck{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("please enter a string: " );
String s = input.nextLine();
int count = 0;
for(int i = 0; i < s.length(); i++){
if(Character.s.charAt(isUpperCase(i))){
count++;
}
}
System.out.println("the number of uppercase letters is: " + count);
}
}


Method to return object's human readable name?


Dear Experts,


I've been doing internet searches and experimenting for

a good two hours now.


I'd like the code that would return an object's human readable name.


ie. myObject.getObjectsName();


Which would return the name of the object.

That is, the name of the object that I use as I code.


In the code below, I'm trying to find the correct code to return the string,

btnTTT_01


The results of the testing follow.

NO luck so far.


Is this possible in Java?

If so, what is the secret?


Thanks a lot!


-----


public static void main(String []args) {


tictactoe game ;

game = new tictactoe();

game.setVisible(true);


System.out.println ("main") ;

System.out.println ( "game.getName() is: " + game.getName() ) ;


System.out.println ( " " );


System.out.println ( "game.btnTTT_01.toString() is: " + game.btnTTT_01.toString() ) ;


System.out.println ( "game.btnTTT_01.getName() is: " + game.btnTTT_01.getName () ) ;


System.out.println ( "game.btnTTT_01.getClass().getSimpleName() is: "

+ game.btnTTT_01.getClass().getSimpleName() ) ;


System.out.println ( "game.btnTTT_01.getClass().getCanonicalName() is: "

+ game.btnTTT_01.getClass().getCanonicalName() ) ;


System.out.println ( "game.btnTTT_01.getClass().getFields() is: "

+ game.btnTTT_01.getClass().getFields() );


} // end main


main

game.getName() is: frame0


game.btnTTT_01.toString() is: javax.swing.JButton[,1,1,130x103,alignmentX=0.0,alignmentY=0.5,border= javax.swing.plaf.BorderUIResource$CompoundBorderUI Resource@40055f9f,flags=296,maximumSize=,minimumSi ze=,preferredSize=,defaultIcon=,disabledIcon=,disa bledSelectedIcon=,margin=javax.swing.plaf.InsetsUI Resource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rol loverEnabled=true,rolloverIcon=,rolloverSelectedIc on=,selectedIcon=,text=,defaultCapable=true]

game.btnTTT_01.getName() is: null

game.btnTTT_01.getClass().getSimpleName() is: JButton

game.btnTTT_01.getClass().getCanonicalName() is: javax.swing.JButton

game.btnTTT_01.getClass().getFields() is: [Ljava.lang.reflect.Field;@6744719c



what is smali file in android?


All times are GMT +2. The time now is 01:27 PM.


VBulletin, Copyright ©2000 - 2015, Jelsoft Enterprises Ltd.


Copyright ©2006 - 2015, Java Programming Forum



request.getRequestDispatcher(resource).forward(req uest, response); help!


Rather than trying to focus on code, try to research what a "servlet forward" is.


And to make that more specific, try to research what the difference between a redirect and a forward is.



Monday, April 13, 2015

Netty Encoder


See: java - Netty Encoder Not Being Called - Stack Overflow


Using Netty 4.0.27 & Java 1.8.0_20


So I am attempting to learn how Netty works by building a simple chat server (the typical networking tutorial program, I guess?). Designing my own simple protocol, called ARC (Andrew's Relay Chat)... so that's why you see ARC in the code a lot. K, so here's the issue.


So here I start the server and register the various handlers...



Java Code:



public void start()
{
System.out.println("Registering handlers...");
ArcServerInboundHandler inboundHandler = new ArcServerInboundHandler(this);

EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try
{
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>()
{
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ch.pipeline().addLast(new ArcDecoder(), inboundHandler);
ch.pipeline().addLast(new ArcEncoder());
}
}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);

try
{
System.out.println("Starting Arc Server on port " + port);
ChannelFuture f = bootstrap.bind(port).sync();
f.channel().closeFuture().sync();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
finally
{
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
}
}

My "inboundHandler" does get called when the user connects.


Java Code:



@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{
System.out.println("CLIENT CONNECTED"); // THIS PRINTS, REACHES THIS POINT
ArcPacket packet = new ArcPacket();
packet.setArc("PUBLIC_KEY");
packet.setField("KEY", Crypto.bytesToHex(server.getRsaKeys().getPublic().getEncoded()));
ctx.writeAndFlush(packet);
}

This is my encoder, which does not seem to get called at all...


Java Code:



public class ArcEncoder extends MessageToByteEncoder<ArcPacket>
{
@Override
protected void encode(ChannelHandlerContext ctx, ArcPacket msg, ByteBuf out) throws Exception
{
System.out.println("ENCODE"); // NEVER GETS HERE
String message = ArcPacketFactory.encode(msg);
byte[] data = message.getBytes("UTF-8");
out.writeBytes(data);
System.out.println("WROTE");
}

@Override
public boolean acceptOutboundMessage(Object msg) throws Exception
{
System.out.println("ACCEPT OUTBOUND MESSAGE"); // NEVER GETS HERE
return msg instanceof ArcPacket;
}
}

So,

The code that calls ctx.writeAndFlush(packet); is run, but it doesn't seem to invoke the encoder at any point. Am I missing something obvious? Perhaps I'm adding the encoder incorrectly? Though it looks right when I compare it to other examples I've seen.


Thanks for any help.



Array question


Hey guys,


So this is not a question about HOW to make arrays, but more how to do the following instruction:


Create an array of 10 cell phones. All these cell phones must be initialized with

proper values; that is: brand, price & serial number. You must use the copy

constructor to create some of these objects


How would I go about to do this? I know I can create an array of object from my class like this



Java Code:



Cellphone[] cellphoneArr = new Cellphone[10];

but then would I have to initialize 5 of them and then use the copy constructor to copy the 5 others? Or is there any faster way to do this? For instance create 5 then use a loop to copy the first 5 into the 5 left?

xml files in struts2


I have some questions about where to put xml files in Struts2.

To begin with the two basic files struts and web xml.


-web.xml goes into webapp/WEB-INF and there is no problem with that one;


-struts.xml is recommended to be at webapp/WEB-INF/classes (so it will end up at the WAR).


But in many occasions the struts.xml is at src/main/resources.

I can make my struts only work when the xml-file is at classes!


My first question is how to make the struts to pickup the struts.xml at src/main/resources (in eclipse)?



how to convert bytes(or String) to 3gp file??


hello.


i'm coding an App. which records the voice(voice recorder) , converts it to array of bytes then Encodes it to base64 .


so i decode the base64 file to normal String or bytes.


now i need to convert normal String(or bytes) variable to a voice file.


summary :


1_record a voice


2_convert to arrays of byte


3_encoded to base64


4_decode the arrays of byte


5_convert it to a playable sound file


here is my code :



PHP Code:



protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/recordfile.3gpp";

myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);

startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});

stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
stop(v);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});

stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
}

public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}

text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);

Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
String encoded;
File file ;
public void stop(View view) throws IOException{

try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
// file = new File(Environment.getExternalStorageDirectory() + "/recordfile.3gpp");


FileInputStream in=new FileInputStream(file=new File(outputFile+"/recordfile.3gp"));
byte fileContent[] = new byte[(int)file.length()];

in.read(fileContent,0,fileContent.length);

encoded = Base64.encodeToString(fileContent,0);
// Utilities.log("~~~~~~~~ Encoded: ", encoded);


stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");

Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}

public void play(View view) {
try{
myPlayer = new MediaPlayer();

FileOutputStream out=new FileOutputStream(outputFile+"/decoded.3gp");
byte[] decoded = Base64.decode(encoded, 0);

out.write(decoded);
out.close();
myPlayer.setDataSource(outputFile+"/decoded.3gp");
myPlayer.prepare();
myPlayer.start();

playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");

Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

the output: records the voice but not playing. and it makes a file recordfile.3gp on SDcard which it play from sdcard corectly....

the output should be :


records the voice and playes it. make two files :recordfile.3gp and decoded.3gp


dosen't make the secode file??!!!



Sunday, April 12, 2015

Help with program


Hey guys I am trying to practice some OOP and I keep on getting this error stating "cannot find symbol"



Java Code:



public class Triangle{
public static void main(String[] args){
TriangleFeatures A = new TriangleFeatures(2.0);
//base.getBase(2.0);
System.out.print("The base of Triangle A is: " + base.getBase() + ".");

}
}


Java Code:



class TriangleFeatures{
private double base;

TriangleFeatures(){
base = 0;
}

TriangleFeatures(double newBase){
this.base = newBase;
}

public double getBase(){
return base;
}

public void setBase(double x){
this.base = base;
}



}

can someone help me? I receive the error when I try to print out the base of the triangle. (base.getBase())



Saturday, April 11, 2015

Parameter help?


I am creating a program to simulate a store. I have several methods listed below that imitate a customer arriving to the store, and a customer departing the store. I have a simulate method that simulates the entire store day. In my simulate() method under in the departure part, I cannot figure out how to call the number of the cashier for the parameter. I call the customerDeparts() method line 111, 112 and need two parameters, num of cashier, and currentTime. Any ideas on how to call the value of the cashier? Thanks.



Java Code:



/********************************************
* Customer to cashier
* @param number of cashier
********************************************/
private void customerToCashier (int num){

//Move first customer to cashier
if(inLine.size() > 0){
cashiers[num] = inLine.remove(0);
}

//Update customers served
customersServed ++;

//Update total wait time
waitTime += currentTime - cashiers[num].getArrivalTime();

//Future time for departure
double futureTime = currentTime + futureEventTime(serviceTime);

//Create new departure event + add to priority queue
GVevent next = new GVevent(GVevent.DEPARTURE, futureTime, num);
myEvents.add(next);

}

/********************************************
* Customer Arrives
* @param time of customer getting in line
********************************************/
public void customerArrives (double t){

//Update current time
currentTime = t;

//Create new customer, add to line
Customer c = new Customer(t);
inLine.add(c);

//Check for if longest line
if(inLine.size() > longestLine){
longestLine = inLine.size();
longestTime = currentTime;
}

//Move first customer in line to available cashier
int i = cashierAvailable();
if(i >= 0){
customerToCashier(i);
}

//Generate future time
double n = futureEventTime(arrivalTime);

//Check time to make sure not after closing, add to queue
if(n < CLOSE){
GVevent next = new GVevent(GVevent.ARRIVAL, t);
myEvents.add(next);
}
}

/********************************************
* Customer Departs
* @param num of cashier available
* @param time
********************************************/
public void customerDeparts (int num, double t){

//Update current time
currentTime = t;

//Retrieve customer from cashier[num]
customerToCashier(num);

//Check to see if cashier gets new customer
if(inLine.size() > 0){
cashiers[num] = inLine.remove(0);
}else{
cashiers[num] = null;
}

}

/********************************************
* Simulation of store
********************************************/
public void simulate(){

//Reset Parameter
currentTime = OPEN;
customersServed = 0;
myEvents = new PriorityQueue <GVevent> ();

//First Arrival
GVevent a = new GVevent(GVevent.ARRIVAL, currentTime);
myEvents.add(a);

//Continue as long as there are events
while(!myEvents.isEmpty()){

//Get next event, update time
a = myEvents.poll();
currentTime = a.getTime();

//Customer arrives
if(a.isArrival()){
customerArrives(currentTime);
}

//Customer Departs
if(a.isDeparture()){
customerDeparts(, currentTime);
}
}

//Print Results
calcResults();
}


Friday, April 10, 2015

File not found IO


Hi,


I have an issue trying to read a file. Iam getting a file not found ex, but the file seems to be there.

This is my project



This the code that is loading the file.



Java Code:



public GATEApplication(String appPath) {
try {
loadGATEApplication(appPath);
corpus = Factory.newCorpus("mainCorpus");
application.setCorpus(corpus);
} catch (GateException e) {
e.printStackTrace();
}
}

/**
* Loads the .gapp file to GATE
*
* @param path the .gapp file path
*/
private void loadGATEApplication(String path) {
try {
Gate.init(); // must run first before any GATE API calls can be made.
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource(path).getFile());
System.out.println(file.getPath()); // the path is correct
application = (CorpusController) PersistenceManager
.loadObjectFromFile(file); // exception thrown here
} catch (GateException | IOException e) {
e.printStackTrace();
}
}

I test the constructor like this:

Java Code:



public static void main(String[] args) {
GATEApplication g = new GATEApplication("GATE applications/film_paum.gapp");
//File file = new File("ML_Model/GATE applications");
//for(String fileNames : file.list()) System.out.println(fileNames);

the stack trace


Java Code:



java.io.FileNotFoundException: C:\Users\Overlord\workspace\Sentiment%20Analysis%20ML%20App\bin\GATE%20applications\film_paum.gapp (The system cannot find the path specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at sun.net.http://ift.tt/QSp0th(Unknown Source)
at sun.net.http://ift.tt/1iey6X5(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at gate.util.persistence.PersistenceManager.isXmlApplicationFile(PersistenceManager.java:1013)
at gate.util.persistence.PersistenceManager.loadObjectFromUrl(PersistenceManager.java:857)
at gate.util.persistence.PersistenceManager.loadObjectFromFile(PersistenceManager.java:831)
at gate_resources.GATEApplication.loadGATEApplication(GATEApplication.java:87)
at gate_resources.GATEApplication.<init>(GATEApplication.java:67)
at gate_resources.Test.main(Test.java:8)
Exception in thread "main" java.lang.NullPointerException
at gate_resources.GATEApplication.<init>(GATEApplication.java:69)
at gate_resources.Test.main(Test.java:8)

but the path on the exception is correct and the file is there. I don't see why this is happening.

please help -spring batch


Hi all,


i'm new in spring batch,where to start.i had gone through lot of tutorials

Spring Batch Example ? CSV File To MySQL Databasehttp://ift.tt/1MRULYN etc

but every where there show maven to get jar files for spring and batch,

1)how can i resolve the same.

2)is spring batch is working with webapplication,can't we created the same for standalone,read a file process the same and insert to database.

3)where to get the respective jar files.

4)how to use this headache maven in netbeans ,do in my office the proxy blocing is cause any error in jar download.

5)please give a good tutorila that will help in start spring batch standalone first.


i know this is a common forum ,but i posted question in spring also but no replies .


any one please help.


thanks in advance.



please help -spring batch


Hi all,


i'm new in spring batch,where to start.i had gone through lot of tutorials

Spring Batch Example ? CSV File To MySQL Databasehttp://ift.tt/1MRULYN etc

but every where there show maven to get jar files for spring and batch,

1)how can i resolve the same.

2)is spring batch is working with webapplication,can't we created the same for standalone,read a file process the same and insert to database.

3)where to get the respective jar files.

4)how to use this headache maven in netbeans ,do in my office the proxy blocing is cause any error in jar download.

5)please give a good tutorila that will help in start spring batch standalone first.


i know this is a common forum ,but i posted question in spring also but no replies .


any one please help.


thanks in advance.



Thursday, April 9, 2015

Help with packages


I've written a java application with several classes all in the same .java file. It works just fine. Now, I've broken it up so that each class has its own .java file. Still works fine. My next step is to put those classes into a package, but I'm not about to get the program to run.


The .java source files are all in /home/user/src


I've set the CLASSPATH to /home/usr/src


All of the source files have "package com.myfirm.program" on the first line.


I compiled the application with:

javac -d . File1.java File2.java File3.java (etc...)


the compiler created the directory:

/home/user/src/com/myfirm/program


and put all of the .class files in there.


So how do I get the program to run?


if I run from /home/usr/src

java File1

I get:

Exception in thread "main" java.lang.NoClassDefFoundError: File1 (wrong name: com/myfirm/program/Program)


Any help would be appreciated.