List of usage examples for java.io IOException getStackTrace
public StackTraceElement[] getStackTrace()
From source file:cli.Main.java
private static void sendMessage(Manager m, String messageText, List<TextSecureAttachment> textSecureAttachments, List<TextSecureAddress> recipients) { final TextSecureDataMessage.Builder messageBuilder = TextSecureDataMessage.newBuilder() .withBody(messageText);//from www. j a v a2s. c o m if (textSecureAttachments != null) { messageBuilder.withAttachments(textSecureAttachments); } TextSecureDataMessage message = messageBuilder.build(); try { m.sendMessage(recipients, message); } catch (IOException e) { System.err.println("Failed to send message: " + e.getMessage()); } catch (EncapsulatedExceptions e) { System.err.println("Failed to send (some) messages:"); for (NetworkFailureException n : e.getNetworkExceptions()) { System.err.println("Network failure for \"" + n.getE164number() + "\": " + n.getMessage()); } for (UnregisteredUserException n : e.getUnregisteredUserExceptions()) { System.err.println("Unregistered user \"" + n.getE164Number() + "\": " + n.getMessage()); } for (UntrustedIdentityException n : e.getUntrustedIdentityExceptions()) { System.err.println("Untrusted Identity for \"" + n.getE164Number() + "\": " + n.getMessage()); } } catch (AssertionError e) { System.err.println("Failed to send message (Assertion): " + e.getMessage()); System.err.println(e.getStackTrace()); System.err.println( "If you use an Oracle JRE please check if you have unlimited strength crypto enabled, see README"); System.exit(1); } }
From source file:org.apache.hadoop.hdfs.server.datanode.CachingBlockSender.java
/** * Converts an IOExcpetion (not subclasses) to SocketException. * This is typically done to indicate to upper layers that the error * was a socket error rather than often more serious exceptions like * disk errors./* w w w. j a va 2 s . c om*/ */ private static IOException ioeToSocketException(IOException ioe) { if (ioe.getClass().equals(IOException.class)) { // "se" could be a new class in stead of SocketException. final IOException se = new SocketException("Original Exception : " + ioe); se.initCause(ioe); /* * Change the stacktrace so that original trace is not truncated * when printed. */ se.setStackTrace(ioe.getStackTrace()); return se; } // otherwise just return the same exception. return ioe; }
From source file:com.sysunite.nifi.XmlSplitTest.java
@Test public void testOnTrigger() { try {/*from w w w. j a va2 s . co m*/ //import a xml file and simulate it as a flowfile earlier used with some attributes. String file = "slagboom.xml"; byte[] contents = FileUtils .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile())); InputStream in = new ByteArrayInputStream(contents); InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in)); ProcessSession processSession = testRunner.getProcessSessionFactory().createSession(); FlowFile f = processSession.create(); f = processSession.importFrom(cont, f); f = processSession.putAttribute(f, "RandomId", "123"); // Add properites // Add properites //testRunner.setProperty("FunctionalPhysicalObject-id", "/FunctionalPhysicalObject/@id"); //testRunner.setProperty("BeginOfLife-id", "/FunctionalPhysicalObject/BeginOfLife/@value"); testRunner.setProperty("HasAsSubject", "/FunctionalPhysicalObject/HasAsSubject"); //testRunner.setProperty("IsMaterializedBy", "/FunctionalPhysicalObject/IsMaterializedBy"); // Add the content to the runner testRunner.enqueue(f); // Run the enqueued content, it also takes an int = number of contents queued testRunner.run(); // //get contents for original relationship // List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("original"); // assertTrue("1 match", results.size() == 1); // MockFlowFile result = results.get(0); // String resultValue = new String(testRunner.getContentAsByteArray(result)); // System.out.println(resultValue); // List<MockFlowFile> results3 = testRunner.getFlowFilesForRelationship("FunctionalPhysicalObject-id"); // MockFlowFile result3 = results3.get(0); // result3.assertAttributeExists("FunctionalPhysicalObject-id"); // String xmlValue3 = result3.getAttribute("FunctionalPhysicalObject-id"); // System.out.println("-----------"); // System.out.println(xmlValue3); // // //get contents for a specific dynamic relationship // List<MockFlowFile> results = testRunner.getFlowFilesForRelationship("BeginOfLife"); // MockFlowFile result = results.get(0); // result.assertAttributeExists("BeginOfLife"); // String xmlValue = result.getAttribute("BeginOfLife"); // System.out.println("-----------"); // System.out.println(xmlValue); // // // List<MockFlowFile> results2 = testRunner.getFlowFilesForRelationship("IsMaterializedBy"); // MockFlowFile result2 = results2.get(0); // result2.assertAttributeExists("IsMaterializedBy"); // String xmlValue2 = result2.getAttribute("IsMaterializedBy"); // System.out.println("-----------"); // System.out.println(xmlValue2); List<MockFlowFile> results2 = testRunner.getFlowFilesForRelationship("HasAsSubject"); for (MockFlowFile mockf : results2) { //MockFlowFile result2 = results2.get(0); //f.assertAttributeExists("HasAsSubject"); String xmlValue2 = f.getAttribute("RandomId"); System.out.println("-----------"); System.out.println(xmlValue2); String resultValue = new String(testRunner.getContentAsByteArray(mockf)); System.out.println(resultValue); } } catch (IOException e) { System.out.println("FOUT!!"); System.out.println(e.getStackTrace()); } }
From source file:com.sysunite.weaver.nifi.CreateValuePropertyTest.java
@Test public void testOnTrigger() { /********* TEST OUTPUTS ********/ /*******/* w w w . j av a2 s .com*/ * * * /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/bin/java -ea -Xmx1G -Djava.net.preferIPv4Stack=true -Didea.launcher.port=7535 "-Didea.launcher.bin.path=/Applications/IntelliJ IDEA 14.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA 14.app/Contents/lib/idea_rt.jar:/Applications/IntelliJ IDEA 14.app/Contents/plugins/junit/lib/junit-rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/ant-javafx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/dt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/javafx-mx.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/jconsole.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/packager.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/sa-jdi.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/lib/tools.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/charsets.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/deploy.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/javaws.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jce.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jfr.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jfxswt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/jsse.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/management-agent.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/plugin.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/resources.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/rt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/cldrdata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/dnsns.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/jaccess.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/jfxrt.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/localedata.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/nashorn.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunec.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunjce_provider.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/sunpkcs11.jar:/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home/jre/lib/ext/zipfs.jar:/Users/jonathansmit/Documents/nifiproj/weaver-createvalueproperty/nifi-weaver-createvalueproperty-processors/target/test-classes:/Users/jonathansmit/Documents/nifiproj/weaver-createvalueproperty/nifi-weaver-createvalueproperty-processors/target/classes:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-api/0.6.0/nifi-api-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-processor-utils/0.6.0/nifi-processor-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-utils/0.6.0/nifi-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-security-utils/0.6.0/nifi-security-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/commons/commons-lang3/3.4/commons-lang3-3.4.jar:/Users/jonathansmit/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-mock/0.6.0/nifi-mock-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-expression-language/0.6.0/nifi-expression-language-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/antlr/antlr-runtime/3.5.2/antlr-runtime-3.5.2.jar:/Users/jonathansmit/.m2/repository/org/apache/nifi/nifi-data-provenance-utils/0.6.0/nifi-data-provenance-utils-0.6.0.jar:/Users/jonathansmit/.m2/repository/org/slf4j/slf4j-simple/1.7.12/slf4j-simple-1.7.12.jar:/Users/jonathansmit/.m2/repository/org/slf4j/slf4j-api/1.7.12/slf4j-api-1.7.12.jar:/Users/jonathansmit/.m2/repository/junit/junit/4.11/junit-4.11.jar:/Users/jonathansmit/.m2/repository/org/hamcrest/hamcrest-core/1.3/hamcrest-core-1.3.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-xml/0.17.2/jcabi-xml-0.17.2.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-log/0.17/jcabi-log-0.17.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-aspects/0.22/jcabi-aspects-0.22.jar:/Users/jonathansmit/.m2/repository/org/aspectj/aspectjrt/1.8.4/aspectjrt-1.8.4.jar:/Users/jonathansmit/.m2/repository/javax/validation/validation-api/1.1.0.Final/validation-api-1.1.0.Final.jar:/Users/jonathansmit/.m2/repository/com/jcabi/jcabi-immutable/1.4/jcabi-immutable-1.4.jar:/Users/jonathansmit/.m2/repository/com/weaverplatform/sdk-java/1.0/sdk-java-1.0.jar:/Users/jonathansmit/.m2/repository/org/apache/httpcomponents/httpclient/4.4.1/httpclient-4.4.1.jar:/Users/jonathansmit/.m2/repository/org/apache/httpcomponents/httpcore/4.4.1/httpcore-4.4.1.jar:/Users/jonathansmit/.m2/repository/commons-logging/commons-logging/1.2/commons-logging-1.2.jar:/Users/jonathansmit/.m2/repository/commons-codec/commons-codec/1.10/commons-codec-1.10.jar:/Users/jonathansmit/.m2/repository/com/google/code/gson/gson/2.6.2/gson-2.6.2.jar:/Users/jonathansmit/.m2/repository/org/mockito/mockito-core/1.10.19/mockito-core-1.10.19.jar:/Users/jonathansmit/.m2/repository/org/objenesis/objenesis/2.1/objenesis-2.1.jar:/Users/jonathansmit/.m2/repository/org/codehaus/groovy/groovy-all/2.4.5/groovy-all-2.4.5.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 com.sysunite.weaver.nifi.CreateValuePropertyTest,testOnTrigger contact! RootNode: FunctionalPhysicalObject RootNode (xpath): /FunctionalPhysicalObject RootNode-Attribute: id RootNode-Attribute (xpath): /FunctionalPhysicalObject/@id RootNode-Attribute (value): 816ee370-4274-e211-a3a8-b8ac6f902f00 ChildNode: BeginOfLife ChildNode (xpath): /FunctionalPhysicalObject/BeginOfLife ChildNode-Attribute: value Child-Attribute (xpath): /FunctionalPhysicalObject/BeginOfLife/@value Child-Attribute (value): 2013-12-21 Error, bad response ..linkEntity (local): done! ..linkEntity (remote): done! Error, bad response ..linkEntity (local): done! Error, bad response ..linkEntity (remote): done! aantal gevonden: 1 * * Aan de kant van weaver worden speciale acties niet uitgevoerd voor * EntityType.VALUE_PROPERTY, OBJECT_PROPERTY, COLLECTION, OBJECT; * * * * */ try { String file = "slagboom.xml"; byte[] contents = FileUtils .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile())); InputStream in = new ByteArrayInputStream(contents); InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in)); // Generate a test runner to mock a processor in a flow TestRunner runner = TestRunners.newTestRunner(new CreateValueProperty()); // Add properites runner.setProperty(CreateValueProperty.PROP_NODE, "FunctionalPhysicalObject"); runner.setProperty(CreateValueProperty.PROP_NODE_ATTRIBUTE, "id"); runner.setProperty(CreateValueProperty.PROP_CHILDNODE, "BeginOfLife"); runner.setProperty(CreateValueProperty.PROP_CHILDNODE_ATTRIBUTE, "value"); // Add the content to the runner runner.enqueue(cont); // Run the enqueued content, it also takes an int = number of contents queued runner.run(); // All results were processed with out failure //runner.assertQueueEmpty(); // If you need to read or do aditional tests on results you can access the content List<MockFlowFile> results = runner.getFlowFilesForRelationship(CreateValueProperty.MY_RELATIONSHIP); //assertTrue("1 match", results.size() == 1); System.out.println("aantal gevonden: " + results.size()); MockFlowFile result = results.get(0); String resultValue = new String(runner.getContentAsByteArray(result)); //check weaver String checkValue = weaver.get("816ee370-4274-e211-a3a8-b8ac6f902f00").toString(); assertEquals(checkValue, resultValue); //System.out.println("Match: " + IOUtils.toString(runner.getContentAsByteArray(result))); } catch (IOException e) { System.out.println("FOUT!!"); System.out.println(e.getStackTrace()); } catch (NullPointerException e) { System.out.println("weaver connection error (weaver-get)"); } }
From source file:org.openhab.binding.panasonictv.internal.PanasonicTVBinding.java
/** * This methods sends the command to the TV * /*from w ww . j a v a2s . c o m*/ * @return HTTP response code from the TV (should be 200) */ private int sendCommand(PanasonicTVBindingConfig config) { String command = config.getCommand().toUpperCase(); final String soaprequest_skeleton = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<s:Body><u:X_SendKey xmlns:u=\"urn:panasonic-com:service:p00NetworkControl:1\">" + "<X_KeyEvent>NRC_%s</X_KeyEvent></u:X_SendKey></s:Body></s:Envelope>\r"; String soaprequest = ""; if (config.getCommand().toUpperCase().startsWith("HDMI")) { soaprequest = String.format(soaprequest_skeleton, command); } else { soaprequest = String.format(soaprequest_skeleton, command + "-ONOFF"); } String tvIp = registeredTVs.get(config.getTv()); if ((tvIp == null) || tvIp.isEmpty()) { return 0; } try { Socket client = new Socket(tvIp, tvPort); BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(client.getOutputStream(), "UTF8")); String header = "POST /nrc/control_0/ HTTP/1.1\r\n"; header = header + "Host: " + tvIp + ":" + tvPort + "\r\n"; header = header + "SOAPACTION: \"urn:panasonic-com:service:p00NetworkControl:1#X_SendKey\"\r\n"; header = header + "Content-Type: text/xml; charset=\"utf-8\"\r\n"; header = header + "Content-Length: " + soaprequest.length() + "\r\n"; header = header + "\r\n"; String request = header + soaprequest; logger.debug("Request send to TV with IP " + tvIp + ": " + request); wr.write(header); wr.write(soaprequest); wr.flush(); InputStream inFromServer = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inFromServer)); String response = reader.readLine(); client.close(); logger.debug("TV Response from " + tvIp + ": " + response); return Integer.parseInt(response.split(" ")[1]); } catch (IOException e) { logger.error("Exception during communication to the TV: " + e.getStackTrace()); } catch (Exception e) { logger.error("Exception in binding during execution of command: " + e.getStackTrace()); } return 0; }
From source file:org.pouzinsociety.transport.im.logger.LoggerBuddy.java
public void processPacket(Packet packet) { StringBuffer buf = new StringBuffer(); boolean network_packet = false; // Debug Info for Log File buf.append("PacketId: " + packet.getPacketID() + "\n"); buf.append("Src: " + packet.getFrom() + ", dest: " + packet.getTo() + "\n"); Message msg = (Message) packet;//w ww .j av a 2s . c o m buf.append("Body:" + msg.getBody() + "\n"); Collection<String> props = msg.getPropertyNames(); byte[] buffer = null; for (Iterator<String> keys = props.iterator(); keys.hasNext();) { String key = keys.next(); if (key.equals("PDU")) { buf.append("PDU:\n" + toHexString((byte[]) msg.getProperty(key)) + "\n"); buffer = (byte[]) msg.getProperty(key); network_packet = true; } else { buf.append("Key(" + key + "): " + msg.getProperty(key) + "\n"); } } if (network_packet == true) { long timestamp = System.currentTimeMillis(); if (dumpFileStream != null) { try { writeRecordHeader(dumpFileStream, timestamp, buffer.length); dumpFileStream.write(buffer); } catch (IOException ioe) { log.error("Error: Writing record to dump file"); log.error(ioe.getStackTrace()); } } } log.info("\n\nPacket:\n" + buf.toString() + "\n\n"); }
From source file:org.egov.restapi.web.rest.CreateBillController.java
/** * API to create works contractor bill./*from w w w . ja va2 s .com*/ * * @param egBillregister * @param request * @return successMessage and billnumber - server response in JSON format */ @RequestMapping(value = "/egf/bill", method = POST, consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) public String createContractorBill(@RequestBody final String requestJson, final HttpServletResponse response) { if (LOG.isDebugEnabled()) LOG.debug("Rest API creating bill with the data: " + requestJson); String responseJson; EgBillregister egBillregister; EgBillregister savedBillregister; ApplicationThreadLocals.setUserId(2L); BillRegister billRegister = null; final JsonObject jsonObject = new JsonObject(); try { billRegister = (BillRegister) getObjectFromJSONRequest(requestJson, BillRegister.class); } catch (final IOException e) { LOG.error(e.getStackTrace()); final List<RestErrors> errorList = new ArrayList<>(0); final RestErrors re = new RestErrors(); re.setErrorCode(e.getMessage()); re.setErrorMessage(e.getMessage()); errorList.add(re); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return JsonConvertor.convert(errorList); } try { final List<RestErrors> errors = billService.validateBillRegister(billRegister); if (!errors.isEmpty()) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return JsonConvertor.convert(errors); } else { egBillregister = new EgBillregister(); billService.createProjectCode(billRegister); billService.populateBillRegister(egBillregister, billRegister); savedBillregister = billService.createBill(egBillregister); responseJson = savedBillregister.getBillnumber(); } } catch (final ValidationException e) { LOG.error(e.getStackTrace()); final List<RestErrors> errorList = new ArrayList<>(0); final List<ValidationError> errors = e.getErrors(); for (final ValidationError ve : errors) { final RestErrors re = new RestErrors(); re.setErrorCode(ve.getKey()); re.setErrorMessage(ve.getMessage()); errorList.add(re); } response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return JsonConvertor.convert(errorList); } catch (final Exception e) { LOG.error(e.getStackTrace()); final List<RestErrors> errorList = new ArrayList<>(0); final RestErrors re = new RestErrors(); re.setErrorCode(e.getMessage()); re.setErrorMessage(e.getMessage()); errorList.add(re); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return JsonConvertor.convert(errorList); } jsonObject.addProperty("successMessage", "Works Bill created Successfully"); jsonObject.addProperty("billNumber", responseJson); response.setStatus(HttpServletResponse.SC_CREATED); return jsonObject.toString(); }
From source file:com.springsource.hq.plugin.tcserver.plugin.serverconfig.environment.UnixFileReadingEnvironmentFactory.java
/** * Scan the setenv.sh file one time, gathering a symbol table built out of "variable=value" lines. Then look for two * important values: JAVA_HOME and JVM_OPTS. */// w w w . ja v a 2 s. c o m public Environment create(ConfigResponse config) throws PluginException { try { Environment environment = new Environment(); if (new File(Metric.decode(config.getValue("installpath")) + "/bin/setenv.sh").exists()) { String envFile = Metric.decode(config.getValue("installpath")) + "/bin/setenv.sh"; Map<String, String[]> symbolTable = extractPropertyMapping(envFile); Set<String> jvmOptsValues = new LinkedHashSet<String>(); expandValue(symbolTable, "JVM_OPTS", jvmOptsValues); JvmOptions combJvmOptions = jvmOptionsConverter.convert(new ArrayList<String>(jvmOptsValues)); environment.setJvmOptions(combJvmOptions); Set<String> javaHome = new LinkedHashSet<String>(); expandValue(symbolTable, "JAVA_HOME", javaHome); environment.setJavaHome(collectionToSpaceDelimitedString(javaHome)); } return environment; } catch (IOException e2) { for (StackTraceElement elem : e2.getStackTrace()) { log.info(elem.toString()); } throw new PluginException( "Unable to read existing tc Runtime configuration. Cause: " + e2.getMessage()); } catch (Exception e) { log.error("Received " + e.getMessage()); e.printStackTrace(); throw new PluginException( "Unable to read existing tc Runtime configuration. Cause: " + e.getMessage()); } }
From source file:com.catalyst.sonar.score.batch.util.FileInstaller.java
/** * This method copies a directory from a URL to a destination File. The URL * is equal to {@code getClass().getResource(getSourcePath())} and the * destination File is equal to {@code new File(getDestinationPath())}. * //from w ww . ja va 2s . c om * @return true if copy is successful, false otherwise. */ public boolean copyResourcesRecursively() { logger.debug("copyResourcesRecursively()"); URL originUrl = getClass().getResource(sourcePath); File destination = new File(destinationPath); boolean success = false; try { final URLConnection urlConnection = originUrl.openConnection(); logger.debug("{}", originUrl); if (urlConnection instanceof JarURLConnection) { success = FileInstaller.copyJarResourcesRecursively(destination, (JarURLConnection) urlConnection); logger.debug("returning " + success); return success; } else { success = FileInstaller.copyFilesRecusively(new File(originUrl.getPath()), destination); logger.debug("returning " + success); return success; } } catch (final IOException e) { logger.debug(e.getStackTrace().toString()); } logger.debug("returning " + success); return success; }
From source file:com.networkmanagerapp.JSONBackgroundDownloaderService.java
/** * Delegate method to run the specified intent in another thread. * @param arg0 The intent to run in the background *///from ww w.j a v a 2s .com @Override protected void onHandleIntent(Intent arg0) { mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); showNotification(); String filename = arg0.getStringExtra("FILENAME"); String jsonFile = arg0.getStringExtra("JSONFILE"); try { String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference", ""); Log.d("password", password); String ip = PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"); String enc = URLEncoder.encode(ip, "UTF-8"); String scriptUrl = "http://" + enc + ":1080" + filename; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "utf-8"); // Set the timeout in milliseconds until a connection is established. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(params, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 20000; HttpConnectionParams.setSoTimeout(params, timeoutSocket); HttpHost targetHost = new HttpHost(enc, 1080, "http"); DefaultHttpClient client = new DefaultHttpClient(params); client.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("root", password)); HttpGet request = new HttpGet(scriptUrl); HttpResponse response = client.execute(targetHost, request); Log.d("JBDS", response.getStatusLine().toString()); InputStream in = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder str = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); if (str.toString().equals("Success\n")) { String xmlUrl = "http://" + enc + ":1080/json" + jsonFile; request = new HttpGet(xmlUrl); HttpResponse jsonData = client.execute(targetHost, request); in = jsonData.getEntity().getContent(); reader = new BufferedReader(new InputStreamReader(in)); str = new StringBuilder(); line = null; while ((line = reader.readLine()) != null) { str.append(line + "\n"); } in.close(); FileOutputStream fos = openFileOutput(jsonFile.substring(1), Context.MODE_PRIVATE); fos.write(str.toString().getBytes()); fos.close(); } } catch (MalformedURLException ex) { Log.e("NETWORKMANAGER_XBD_MUE", ex.getMessage()); } catch (IOException e) { try { Log.e("NETWORK_MANAGER_XBD_IOE", e.getMessage()); StackTraceElement[] st = e.getStackTrace(); for (int i = 0; i < st.length; i++) { Log.e("NETWORK_MANAGER_XBD_IOE", st[i].toString()); } } catch (NullPointerException ex) { Log.e("Network_manager_xbd_npe", ex.getLocalizedMessage()); } } finally { mNM.cancel(R.string.download_service_started); Intent bci = new Intent(NEW_DATA_AVAILABLE); sendBroadcast(bci); stopSelf(); } }