I am working on a Processing program within Eclipse and I am having issues initializing the Client object. I have properly imported both core.jar and net.jar from the Processing package into my class from these locations:
C:\Program Files\eclipse\processing-2.0.2\core\library
C:\Program Files\eclipse\processing-2.0.2\modes\java\libraries\net\library\net.jar
public class Client extends PApplet {
private static final long serialVersionUID = 0L;
// Declare a client
Client client;
public void setup() {
size(400, 200);
// create the client
client = new Client(this, "127.0.0.1", 8888);
}
}
The line Eclipse is complaining about (client = new Client(this, "127.0.0.1", 8888) shows an error: the constructor Client(Client, String, int) is undefined.
Per the Client API, there is a constructor that takes those arguments: http://processing.org/reference/libraries/net/Client.html.
I have also tried client = new Client(this, 8888); and Eclipse is still complaining about an error. Can anyone help guide me on how to resolve this? Thanks.
Your class is called Client so the new Client in your code is trying to create an instance of your class. What you actually want is an instance of processing.net.Client. It would be best to use a different name for you class:
import processing.net.Client;
public class MyApplet extends PApplet {
private static final long serialVersionUID = 0L;
// Declare a client
Client client;
public void setup() {
size(400, 200);
// create the client
client = new Client(this, "127.0.0.1", 8888);
}
}
I have changed the class name to MyApplet.
Related
I am using jersey rest api (JAX-RS) of 2.25.1 version. I tried to use LoggingFeature class at server side and as well as client side.
Client side code:
public static void getOperation() {
ClientConfig config = new ClientConfig();
config.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY_CLIENT, LoggingFeature.Verbosity.PAYLOAD_ANY);
config.register(new LoggingFeature(logger, LoggingFeature.Verbosity.PAYLOAD_ANY));
Client client = ClientBuilder.newClient(config);
client.register(ClientEmpReqFilter.class);
client.register(ClientEmpResFilter.class);
WebTarget target = client.target("http://localhost:8080").path("restappln/rest/entity");
String str = target.request(MediaType.APPLICATION_JSON).get(String.class);
System.out.println(str);
}
and Server-side code is :
#ApplicationPath("/rest")
public class MyApplication extends ResourceConfig {
public MyApplication() {
packages("<package name>");
register(LoggingFeature.class);
}
}
I am not able to get logging. I am passing instance of java.util.Logger to the contructor of client config.
config.register(new LoggingFeature(logger, LoggingFeature.Verbosity.PAYLOAD_ANY));
How do I actually run this client/server project on ActionScript 3? I'm using flashbuilder. I'm not sure if I'm even doing the right thing, i made a new as mobile project and put in the code for my client which is this:
public class client extends Sprite
{
private var socket:Socket;
private var IP:String = "127.0.0.1";
public function client()
{
super();
socket = new Socket();
socket.addEventListener(Event.CONNECT, onConnected);
socket.connect(IP, 5555);
}
protected function onConnected(event:Event):void
{
socket.writeUTFBytes("communication between Sockets (Client socket and server socket)");
socket.flush();
}
}
and then I made a new class within the package that has the client class (as above) in it and put in this as the server class:
public class NewSocketServerTest extends Sprite
{
private var serverSocket:ServerSocket = new ServerSocket();
private var clientSocket:Socket;
private var txt:TextField;
public function NewSocketServerTest()
{
createUI();
serverSocket.bind(5555);
serverSocket.addEventListener(ServerSocketConnectEvent.CONNECT, onConnected);
serverSocket.listen();
}
protected function onConnected(event:ServerSocketConnectEvent):void
{
txt.appendText("This is a demonstration of \n" );
clientSocket = event.socket;
clientSocket.addEventListener(ProgressEvent.SOCKET_DATA, onDataHandler);
}
protected function onDataHandler(event:ProgressEvent):void
{
var str:String = clientSocket.readUTFBytes(clientSocket.bytesAvailable);
txt.appendText(str);
}
private function createUI():void
{
txt = new TextField();
txt.width=400;
txt.height=400;
txt.appendText("Hello! \n");
addChild(txt);
}
}
When I try run this in an emulator it's just a white screen and I'm not sure what I'm doing wrong.
Try specifying the serverSocket hostname.
serverSocket.bind(5555,"127.0.0.1");
Here is a code snippet of my RemoteServiceServlet. The function getSubject(), obtains the session from the HttpServletRequest, which refers to the getThreadLocalRequest. I am making a junit test to test this server, however the getThreadLocalRequest is not populated and returns null.
public class Server extends XsrfProtectedServiceServlet implements RemoteInterface {
private static final long serialVersionUID = 2230123191888380541L;
public Server() throws IOException
{
credentials = new PropertiesCredentials(Server.class.getResourceAsStream("AwsCredentials.properties.email"));
database = new Database();
}
public Subject getSubject()
{
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession(false);
Subject subject = (Subject)session.getAttribute("subject");
return subject;
}
}
This is my junit test
#Test
public void testserver()
{
Server s = new Server();
s.getSubject();
}
s.getSubject fails because the session is not populated. How can I mock Server so that I can populate a session.
You'll need to use a mocking framework to create behaviour around the object under test. I use PowerMock with EasyMock (http://code.google.com/p/powermock/).
What I suggest you do first, though, is refactor the code out of the constructor. As written, this code is very complicated to test, because the getResourceAsStream method is a static method of the underlying Class type. And since it's not used in the method under test (nor is the database reference), I question the need to use the constructor to get the resource bundle.
To test your getSubject() method, essentially what you need to do is create an instance of your class that is a partial mock, where the getThreadLocalRequest is the only method to be mocked:
#RunWith( PowerMockRunner.class )
#PrepareForTest( Server.class )
public class ServerTest {
#Test
public void testGetSubjectReturnsSubjectFromHttpSession() {
// assuming the constructor is cleaned up, create a Server instance...
Server server = PowerMock.createPartialMockAndInvokeDefaultConstructor( Server.class, "getThreadLocalRequest" );
// create a mock object that represents the Http request
HttpServletRequest mockRequest = PowerMock.createMock(HttpServletRequest.class);
EasyMock.expect( server.getThreadLocalRequest() ).andReturns( mockRequest);
// create a mock for the Http Session
HttpSession mockSession = PowerMock.createMock( HttpSession.class );
EasyMock.expect( mockRequest.getSession( EasyMock.anyBoolean() ) ).andReturns( mockSession );
EasyMock.expect( mockSession.getAttribute( EasyMock.isA( String.class ) ).andReturns( mockSubject );
// put the mocks into playback mode
PowerMock.replayAll();
// exercise the method
Subject subject = server.getSubject();
// verify that the mocks were called as you expect them to be...
PowerMock.verifyAll();
// and here you put other assertions that relate to the data returned...
Assert.assertNotNull( subject );
}
}
I am running a basic GWT application in IntelliJ, below is my code
public class test implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
final Button button = new Button("Click me");
final Label label = new Label();
button.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
if (label.getText().equals("")) {
testService.App.getInstance().getMessage("h", new AsyncCallback<Inter>() {
public void onFailure(Throwable caught) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void onSuccess(Inter result) {
label.setText(result.getToken());
}
});
} else {
label.setText("");
}
}
});
Impl Class
public class testServiceImpl extends RemoteServiceServlet implements testService {
// Implementation of sample interface method
public Inter getMessage(String msg) {
RdbHelper rdbHelper = new RdbHelper();
return rdbHelper.getMsg();
}
}
RdbHelper Class
public class RdbHelper {
public Inter getMsg(){
Inter inter = new Inter();
return inter;
}
}
Inter Class
public class Inter implements Serializable{
private String token ;
public String getToken() {
token = "Hello";
return token;
}
public void setToken(String token) {
this.token = token;
}
}
I should see msg "Hello" but i am getting this error .
ERROR: Errors in 'file:/C:/work/Grails/TestFinal/src/com/test/client/test.java'.
ERROR: Unable to find type 'com.test.client.test'.
ERROR: Line 28: No source code is available for type com.test.shared.Inter; did you forget to inherit a required module?.
ERROR: Hint: Previous compiler errors may have made this type unavailable.
ERROR: Hint: Check the inheritance chain from your module; it may not be inheriting a required module or a module may not be adding its source path entries properly.
ERROR: Failed to load module 'test' from user agent 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.75 Safari/535.7' at 127.0.0.1:51070.
Note: I am trying the same thing in Eclipse and its working fine, but this is the Issue i am facing in IntelliJ
Did you remember to put
<source path="shared"/>
in your Module.gwt.xml file.
You need to do this to compile the code in shared package to javascript code. If not it only compiles the code in the client package and thereby the code in the shared folder is not available on client side.
I am looking to read xls file using the gwt RPC and when I am using the code which excecuted fine in normal file it is unable to load the file and giving me null pointer exception.
Following is the code
{
{
import com.arosys.readExcel.ReadXLSX;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.Preview.client.GWTReadXL;
import java.io.InputStream;
import com.arosys.customexception.FileNotFoundException;
import com.arosys.logger.LoggerFactory;
import java.util.Iterator;
import org.apache.log4j.Logger;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author Amandeep
*/
public class GWTReadXLImpl extends RemoteServiceServlet implements GWTReadXL
{
private String fileName;
private String[] Header=null;
private String[] RowData=null;
private int sheetindex;
private String sheetname;
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private static Logger logger=null;
public void loadXlsxFile() throws Exception
{
logger.info("inside loadxlsxfile:::"+fileName);
InputStream resourceAsStream =ClassLoader.getSystemClassLoader().getSystemResourceAsStream("c:\\test2.xlsx");
logger.info("resourceAsStream-"+resourceAsStream);
if(resourceAsStream==null)
throw new FileNotFoundException("unable to locate give file");
else
{
try
{
workbook = new XSSFWorkbook(resourceAsStream);
sheet = workbook.getSheetAt(sheetindex);
}
catch (Exception ex)
{
logger.error(ex.getMessage());
}
}
}// end loadxlsxFile
public String getNumberOfColumns() throws Exception
{
int NO_OF_Column=0; XSSFCell cell = null;
loadXlsxFile();
Iterator rowIter = sheet.rowIterator();
XSSFRow firstRow = (XSSFRow) rowIter.next();
Iterator cellIter = firstRow.cellIterator();
while(cellIter.hasNext())
{
cell = (XSSFCell) cellIter.next();
NO_OF_Column++;
}
return NO_OF_Column+"";
}
}
}
I am calling it in client program by this code:
final AsyncCallback<String> callback1 = new AsyncCallback<String>() {
public void onSuccess(String result) {
RootPanel.get().add(new Label("In success"));
if(result==null)
{
RootPanel.get().add(new Label("result is null"));
}
RootPanel.get().add(new Label("result is"+result));
}
public void onFailure(Throwable caught) {
RootPanel.get().add(new Label("In Failure"+caught));
}
};
try{
getService().getNumberOfColumns(callback1);
}catch(Exception e){}
}
Pls tell me how can I resolve this issue as the code runs fine when run through the normal java file.
Why are using using the system classloader, rather than the normal one?
But, If you still want to use then look at this..
As you are using like a web application. In that case, you need to use the ClassLoader which is obtained as follows:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
This one has access to the all classpath paths tied to the webapplication in question and you're not anymore dependent on which parent classloader (a webapp has more than one!) has loaded your class.
Then, on this classloader, you need to just call getResourceAsStream() to get a classpath resource as stream, not the getSystemResourceAsStream() which is dependent on how the webapplication is started. You don't want to be dependent on that as well since you have no control over it at external hosting:
InputStream input = classLoader.getResourceAsStream("filename.extension");
The location of file should in your CLASSPATH.