Returning String Array - java

I am having trouble with returning string array on a client and server environment. The result I getting is nothing when I compiled the client application.
server application
public String[] getFlight() throws Exception {
AvailableFlights todayFlight = new AvailableFlights();
List<Flight> flights_today = todayFlight.getFlightDetail();
List<String> flights = new ArrayList<String>();
try {
flights_today = this.unmarshal(new File("Flights.xml"));
for (Flight flight : flights_today) {
String flightDetail = flight.getJourney()
+ " " + flight.getAirline()
+ " "+ String.valueOf(flight.getConnections())
+ " "+ String.valueOf(flight.getCost())
+ " "+ flight.getDestination()
+ " "+ flight.getOrigin()
+ " "+ String.valueOf(flight.getSeats());
flights.add(flightDetail);
System.out.println(flightDetail);
}
} catch (Exception e) {
}
return (String[]) flights.toArray();
}
client java application
import org.me.kettravel.*;
public class JavaApplication5 {
public static void main(String[] args) {
try {
System.out.println(getFlight());
} catch (Throwable ex) {
}
}
private static java.util.List<java.lang.String> getFlight() throws Exception_Exception {
org.me.kettravel.ReadFlightService service = new org.me.kettravel.ReadFlightService();
org.me.kettravel.ReadFlight port = service.getReadFlightPort();
return port.getFlight();
}
Additionally I have tried a small experiment with "hello" like below on the server app and it worked fine, so I know that the web service is working fine but I just can't seem to pass/return the flights String array to the client app.
String i = "hello";
return i;
PS: When I try to run the server app with public static void main (String[] args) { constructor and without return, the app printed out the arraylist perfectly from unmarshalling xml convert it to arraylist and do system.out.print.
I would be grateful if anyone could shed some light as I am really stuck on this. Thanks.
04/01/2012 (19:16) - Adjustment has been made suggested by Genzer, the client app still not getting any response from server app.
04/01/2012 (23:24) - Adjustment has been made suggested by Bohemian can be seen below, the client app is now getting an error checking javax.xml.ws.soap.SOAPFaultException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
public static void main(String[] args) {
try {
Object obj = getFlight();
System.out.println(obj);
} catch (Throwable ex) {
System.out.println(ex);
}
}
06/01/2013 (16:20) - I have just addressed my mistake as the XML file was empty from tests to tests, however it is now have data in the xml file. I have just created a test class to see if readFlight returns anything to a class that it's in a same project/source package. Result is a success... really running out of ideas =/ as I have tested the web service by sending a simple hello string over to client app and worked no problem.
test class
public class test {
public static void main(String[] args) {
readFlight rF = new readFlight();
try {
System.out.println(rF.getFlight());
} catch (Throwable ex) {
System.out.println(ex);
}
}
}
Output from the test class: [London to Amsterdam KLM 1 200.0 Amsterdam London 100, London to Kuala Lumper Malaysia Airline 1 750.0 Kuala Lumper London 100, London to Manchester British Airway 1 50.0 Manchester London 56]
10/01/2013 (18:13) - PROBLEM SOLVED. You have to give full directory to the unmarshall file. Example: C:/Users/User/Documents/NetBeansProjects/WebService/booking.xml

The problem is that you have two different variables named flights. You populate one and return the other.

You could remove public static String[] flights and modify the method like this:
public List<String> getFlight() throws Exception {
Flight nextFlight = new Flight();
AvailableFlights todayFlight = new AvailableFlights();
List<Flight> flights_today = todayFlight.getFlightDetail();
// Since you you List for Flight, why not here
List<String> flights = new ArrayList<String>();
try {
flights_today = readFlight.unmarshal(new File("Flights.xml"));
for (Flight flight : flights_today) {
String flightDetail = flight.getJourney()
+ " " + flight.getAirline()
+ " "+ String.valueOf(flight.getConnections())
+ " "+ String.valueOf(flight.getCost())
+ " "+ flight.getDestination()
+ " "+ flight.getOrigin()
+ " "+ String.valueOf(flight.getSeats());
flights.add(flightDetail);
}
} catch (Exception e) {
}
return flights;
}

You have committed a "no no", which may be hiding the problem:
catch (Exception e) {
}
You should never (well, rarely) catch Exception. Especially when your catch block is empty.
There could be an unchecked exception, like NullPointerException, being thrown within your loop, but you wouldn't know.
Try removing the catch and leaving only soecific Exceptions (if any) that are declared to be thrown.
If one of the method is declared as throwing Exception, then at the very least, you should do this:
catch (Exception e) {
System.out.println(e);
}

Related

Problems with loading a map with bukkit

I am trying to load a map with the bukkit API, and ran into a problem.
The map does not load. The file gets created and get cappied as well, but when i do /memory in game, it shows all the loaded worlds, and this does not show up. And when i try to teleport to the world by doing p.teleport(world.getSpawnLocation()); it just throws a java.lang.NullPointerException: null execption.
my code:
public static void loadMap(String l) throws IOException {
try {
File folderName = new File(plugin.getDataFolder() + "/maps/Dungeon");
File desti = new File(l + "_world");
if(!desti.exists()) {
desti.mkdir();
}
FileUtils.copyDirectory(folderName, desti);
World world = Bukkit.getServer().createWorld(new WorldCreator(l + "_world"));
System.out.println("[DDEBUG]" + world);
} catch (Exception e) {
System.out.println(e);
}
}
Any ideas on how to fix this ?
that means the player is null, so it throws this error
btw. if you use try and catch blok, so remove throws IOException

Testing methods using JUnit

I am new to JUnit and I have to test a method using JUnit api. One method internall calls another. My test case goes inside the method but while catchign the exception it fails.
Method under test is
public void checkANDCondition( Map<String, Message> messagesMap ) throws EISClientException
{
List<String> codes = getMessageCodes();
if(isAllReturnedMessagesContainCodes(codes, messagesMap))
{
StringBuffer buff = new StringBuffer("All of the specified message codes matched returned errors.");
for(String code: codes )
{
Message message = messagesMap.get(code);
buff.append(message.getMessageCode() + ": " + message.getMessageType() + ": " + message.getMessageText() + " ");
}
throw new EISClientException(buff.toString());
}
}
public boolean isAllReturnedMessagesContainCodes(List<String> codes, Map<String, Message> messagesMap)
{
if(codes!=null)
{
for(String code: codes)
{
if(!messagesMap.containsKey(code))
{
return false;
}
}
}
return true;
}
What I have done so far is
#Test
public void testPostProcess() throws Exception {
clientResponse = mock(ClientResponse.class);
MessageToExceptionPostProcessFilter postProcessFilter = new MessageToExceptionPostProcessFilter();
RetrieveBillingServiceResponse serviceResponse = new RetrieveBillingServiceResponse();caughtException = false;
try {
postProcessFilter.setCondition(ConditionOperator.AND);
List<String> messagesCodes = new ArrayList<String>();
messagesCodes.add("200");
messagesCodes.add("400");
Message message = new Message();
message.setMessageCode("200");
message.setMessageType(MessageTypeEnum.MESSAGE_TYPE_INFO);
message.setMessageText("Service completed successfully");
serviceResponse.setMessages(Arrays.asList(message));
postProcessFilter.setMessageCodes(messagesCodes);
serviceResponse = postProcessFilter.postProcess(serviceResponse, clientResponse);
assertNotNull(serviceResponse.getMessages());
} catch (EISClientException ex) {
caughtException = true;
assertEquals("All of the specified message codes matched returned errors.", ex.getMessage());
}
assertTrue(caughtException);
}
How can I make it pass?
Thanks
#Test(expected = EISCLientException.class)
public void testPostProcess() throws Exception {
...
serviceResponse.getMessages();
fail("Shouldn't reach this point");
}
That way you don't need to catch, with expected if it does not get throw a EISClientException it will fail.
edit: There are two times I can think of where you wouldn't want to use this.
1) You are mocking exceptions that are thrown mock(exception.class);
this i believe then throws some Mockito excpetion and it will not match the expected exception.
2) You are wrapping caught exceptions in your code, and throwing a generic exception. Example of code:
try {
} catch (FileParseException e){
throw new (ProjectFailingException(e, "file is bad");
}
if you have multiple catches and are wrapping them as ProjectFailingExceptions then you may want to catch in the test like this...
#Test ( expected = FileParseException.class)
public void testProcess() {
try {
...
} catch (ProjectFailingException e){
throw e.getCause();
}
Then the proper exception is thrown and you can make sure that process isn't throwing an exception from a a different catch.

unreported exception Exception; must be caught or declared to be thrown

There's two classes:
The main one (Corina.java) and the one that I am having issues with (Functions.java). Without complicating things too much, Corina.java calls a method in Functions.java, the method checks if a boolean is true or false and asks for authentication based on that, the code is very impartial at the moment, though I am using a phidgets RFID reader and copied a portion of one of their examples. but I get the following error in JCreator:
--------------------Configuration: Corina - JDK version 1.7.0_45 <Default> - <Default>--------------------
C:\Users\alexis.JKLSEMICOLON\Documents\JCreator LE\MyProjects\Corina\src\Functions.java:23: error: unreported exception Exception; must be caught or declared to be thrown
authenticateContinue();
^
First class code:
public class Corina {
public static void main(String[] args) {
Functions funtion = new Functions();
funtion.authenticateStart();
}
}
Second class code:
import com.phidgets.*;
import com.phidgets.event.*;
public class Functions {
public void authenticateStart() {
boolean authStatus = false;
System.out.println("The authentication status is currently: " + authStatus + ".");
if (authStatus) {
System.out.println("The applications is unlocked. Please wait.");
// applicationStart();
} else {
System.out.println("Please authenticate now by swiping one of the RFID tags allowed to unlock the program.");
authenticateContinue();
}
}
public void authenticateContinue() throws Exception {
RFIDPhidget rfid;
System.out.println(Phidget.getLibraryVersion());
rfid = new RFIDPhidget();
rfid.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae) {
try {
((RFIDPhidget) ae.getSource()).setAntennaOn(true);
((RFIDPhidget) ae.getSource()).setLEDOn(true);
} catch (PhidgetException ex) {
}
System.out.println("attachment of " + ae);
}
});
rfid.addDetachListener(new DetachListener() {
public void detached(DetachEvent ae) {
System.out.println("detachment of " + ae);
}
});
rfid.addErrorListener(new ErrorListener() {
public void error(ErrorEvent ee) {
System.out.println("error event for " + ee);
}
});
rfid.addTagGainListener(new TagGainListener() {
public void tagGained(TagGainEvent oe) {
System.out.println(oe);
}
});
rfid.addTagLossListener(new TagLossListener() {
public void tagLost(TagLossEvent oe) {
System.out.println(oe);
}
});
rfid.addOutputChangeListener(new OutputChangeListener() {
public void outputChanged(OutputChangeEvent oe) {
System.out.println(oe);
}
});
rfid.openAny();
System.out.println("waiting for RFID attachment...");
rfid.waitForAttachment(1000);
System.out.println("Serial: " + rfid.getSerialNumber());
System.out.println("Outputs: " + rfid.getOutputCount());
System.out.println("Outputting events. Input to stop.");
System.in.read();
System.out.print("closing...");
rfid.close();
rfid = null;
System.out.println(" ok");
if (false) {
System.out.println("wait for finalization...");
System.gc();
}
}
}
any help would be appreciated. Ideally, I would like to just have the tag saved to a string, so if you would be knowledgeable on that, by all means.
Your problem is that authenticateStart calls authenticateContinue(), but you've flagged authenticateContinue as able to throw an Exception. That means that authenticateStart needs to be able to deal with that exception when it's thrown. You have a couple of options.
Put the call to authenticateContinue inside a try block, and deal with the exception in a catch block beneath it.
Change authenticateContinue so that it doesn't throw a checked exception.
Flag authenticateStart as able to throw an Exception. This will push the problem up into main, where you're calling authenticateStart.
No matter what you do, you'll have to deal with that exception somehow. The whole point of Java exception handling is that you can't just leave checked exceptions unhandled - you have to deal with them somehow.

SVN Commit Log Issue

I am currently working on a project about calculations.I have done the main part of my project,Also integrated SVN Commit function to my code (using .ini file to read the specific address etc. )
I can easily Commit the files, what I am trying is I want to implement the real-time log to my console. Is there any way to implement the log to the console ? Not the general log but the commit log which should be real time.
I am using eclipse for mac, I've heard about SVNKit but I am really poor about SVN.
Thanks in advance for any information
--- EDIT ---
This is the code for reading the svn commands from .ini file
public static String iniSVNOkut(String deger, String getObje, String fetchObje){
Ini uzantilariAlIni = null;
try
{
String uzantiAyarlari = "Uzantilar.ini";
try
{
uzantilariAlIni = new Ini(new FileReader(uzantiAyarlari));
}
catch (InvalidFileFormatException e)
{
System.err.print("Hata InvalidFileFormat : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch(FileNotFoundException e)
{
System.err.print("Hata FileNotFoundException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
catch (IOException e)
{
System.err.print("Hata IOException : " + e.getMessage() + "\n" );
e.printStackTrace();
}
return deger = uzantilariAlIni.get(getObje).fetch(fetchObje);
}
finally
{
}
}
This is what .ini includes
[svnAdresi]
svnAdresiniAl = svn co http://svn.svnkit.com/repos/svnkit/trunk/ /Users/sample/Documents/workspace/SatirHesaplaGUI/svnTestMAC
This is how I call it
String svnAdresi;
svnAdresi = IniFonksiyon.iniSVNOkut(svnAdresi, "svnAdresi", "svnAdresiniAl");
Runtime cmdCalistir = Runtime.getRuntime();
try
{
Process islem = cmdCalistir.exec(svnAdresi);
}
catch (Exception e)
{
e.printStackTrace();
}
If I understand your question correctly, you want to read the Subversion commit log into your console application.
The easiest way is to use SVNKit.
Here's how I did it.
private static List<SVNLogEntry> logEntryList;
/*
* Gets the Subversion log records for the directory
*/
LogHandler handler = new LogHandler();
String[] paths = { directory };
try {
repository.log(paths, latestRevision, 1L, false, true, handler);
} catch (SVNException svne) {
if (svne.getMessage().contains("not found")) {
logEntryList = new ArrayList<SVNLogEntry>();
} else {
CobolSupportLog.logError(
"Error while fetching the repository history: "
+ svne.getMessage(), svne);
return false;
}
}
logEntryList = handler.getLogEntries();
directory - string pointing to a particular directory or module
latestRevision - largest revision number from Subversion. Placing the latestRevision second in the log method invocation returns the log records in most recent order.
If you want the log records in sequential order, from 1 to latestRevision, then the 1L would be placed second, and the latestRevision would be placed third.
repository - Subversion repository that you've already authenticated.
Here's LogHandler.
public class LogHandler implements ISVNLogEntryHandler {
protected static final int REVISION_LIMIT = 5;
protected List<SVNLogEntry> logEntryList;
public LogHandler() {
logEntryList = new ArrayList<SVNLogEntry>();
}
public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
logEntryList.add(logEntry);
}
public List<SVNLogEntry> getLogEntries() {
if (logEntryList.size() <= REVISION_LIMIT) {
return logEntryList;
} else {
return logEntryList.subList(0, REVISION_LIMIT);
}
}
}

Provisioning Api using Java

Hello I tried one application which is used to store First 100 users in my domain to the table using JPA.But its returning Server Error. Pealse Help me.
This is the code i tried..
public class AppsProvisioning {
public String m[]=new String[1000];
public int a;
final EntityManager em = EMFService.get().createEntityManager();
//public static void main(String[] args)
public void calluser() throws AppsForYourDomainException, ServiceException,
{
try {
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials("admin#xxxx.edu.in","xxxxxxxx");
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/domain/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(int i=0; i<entries.size(); i++) {
UserEntry entry = entries.get(i);
m[i]=entry.getTitle().getPlainText();
table greeting1 = new table(m[i]);
em.persist(greeting1);
System.out.println("\t" + entry.getTitle().getPlainText());
}
a=entries.size();
System.out.println("\nTotal Entries: "+entries.size());
}
catch(AuthenticationException e) {
e.printStackTrace();
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(ServiceException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
finally
{
em.close();
}
}
}
I think error in em.close()
Error is:Server Error
The server encountered an error and could not complete your request.
Regards
Sharun
Replace "domain" in the feed url (https://www.google.com/a/feeds/domain/user/2.0/) with your domain "xxxx.edu.in".
As an alternative, use AppsForYourDomainClient.retrieveAllUsers() as explained in the reference guide http://code.google.com/googleapps/domain/gdata_provisioning_api_v2.0_reference_java.html

Categories