List of usage examples for java.io BufferedWriter flush
public void flush() throws IOException
From source file:com.seer.datacruncher.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l//w ww.ja va 2 s . c o m : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "com.seer.datacruncher.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:com.waitwha.nessus.server.Server.java
/** * Downloads a report by the given uuid and saves it to the path given. * //from w w w. j a va 2 s. co m * @param uuid String UUID of the Nessus report/scan results to download. * @param path String path to save the document (XML). * @throws SAXException * @throws ParserConfigurationException */ public NessusClientData downloadReport(String uuid, String path) throws ParserConfigurationException, SAXException { String c = "/file/report/download"; if (this.url.endsWith("/")) c = c.substring(1); NessusClientData scan = null; /* * Get a client, setup the POST, and execute. */ HttpPost post = new HttpPost(String.format("%s%s", this.url, c)); post.addHeader("User-Agent", DEFAULT_USER_AGENT); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("seq", r() + "")); nvps.add(new BasicNameValuePair("report", uuid)); post.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); HttpClient client = this.getClient(); try { log.finest(String.format("[%s] Executing POST.", post.getURI())); HttpResponse resp = client.execute(post); try { HttpEntity entity = resp.getEntity(); if (resp.getStatusLine().getStatusCode() == 200) { InputStream in = entity.getContent(); log.finest(String.format("[%s] Received HTTP code %d: %dbytes (%s)", post.getURI(), resp.getStatusLine().getStatusCode(), entity.getContentLength(), entity.getContentType().getValue())); File file = new File(path); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.flush(); } writer.close(); scan = NessusClientData.parse(file); EntityUtils.consumeQuietly(entity); } else { log.warning(String.format("[%s] Received HTTP code %d. Could not download report.", post.getURI(), resp.getStatusLine().getStatusCode())); } } catch (IOException e) { log.warning(String.format("[%s] Could not download report: %s", post.getURI(), e.getMessage())); } } catch (IOException e) { log.warning(String.format("[%s] Could not download report: %s", post.getURI(), e.getMessage())); } return scan; }
From source file:it.openprj.jValidator.services.ServiceScheduledJob.java
@Override protected synchronized void executeInternal(JobExecutionContext arg0) throws JobExecutionException { long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); JobsEntity jobEntity = jobsDao.find(jobId); if (!jobEntity.isWorking()) { if (jobsDao.setWorkStatus(jobId, true)) { try { long eventTriggerId = arg0.getJobDetail().getJobDataMap().getString("eventTriggerId") == null ? -1l/* ww w.ja v a2 s. co m*/ : Long.parseLong(arg0.getJobDetail().getJobDataMap().getString("eventTriggerId")); if (eventTriggerId > 0) { EventTriggerEntity entity = eventTriggerDao.findEventTriggerById(eventTriggerId); String className = entity.getName(); try { String sourceCode = entity.getCode(); EventTrigger eventTrigger; String response; eventTrigger = (EventTrigger) CommonUtils.getClassInstance(className, "it.openprj.jValidator.eventtrigger.EventTrigger", EventTrigger.class, sourceCode); assert eventTrigger != null; response = eventTrigger.trigger(); log.info("Response From EventTrigger(" + className + ") :" + response); } catch (Exception e) { e.printStackTrace(); log.error("EventTrigger(" + className + ") :" + e.getMessage(), e); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + e.getMessage()); } catch (NoClassDefFoundError err) { log.error("EventTrigger(" + className + ") :" + err.getMessage(), err); logDao.setErrorLogMessage("EventTrigger(" + className + ") :" + err.getMessage()); } return; } int day = arg0.getJobDetail().getJobDataMap().getString("day") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("day")); int month = arg0.getJobDetail().getJobDataMap().getString("month") == null ? -1 : Integer.parseInt(arg0.getJobDetail().getJobDataMap().getString("month")); if ((day > 0 && day != Calendar.getInstance().get(Calendar.DAY_OF_MONTH)) || (month > 0 && month != (Calendar.getInstance().get(Calendar.MONTH) + 1))) { return; } StandardFileSystemManager fsManager = new StandardFileSystemManager(); boolean isDataStream = true; try { fsManager.init(); long schemaId = arg0.getJobDetail().getJobDataMap().getLong("schemaId"); long schedulerId = arg0.getJobDetail().getJobDataMap().getLong("schedulerId"); //long jobId = arg0.getJobDetail().getJobDataMap().getLong("jobId"); long connectionId = arg0.getJobDetail().getJobDataMap().getLong("connectionId"); String datastream = ""; int idSchemaType = schemasDao.find(schemaId).getIdSchemaType(); TasksEntity taskEntity = tasksDao.find(schedulerId); //JobsEntity jobEntity = jobsDao.find(jobId); if (taskEntity.getIsOneShoot()) { jobEntity.setIsActive(0); jobsDao.update(jobEntity); } if (idSchemaType == SchemaType.GENERATION) { StreamGenerationUtils sgu = new StreamGenerationUtils(); datastream = sgu.getStream(schemaId); log.debug("Content stream: " + schemaId); if (datastream.trim().length() > 0) { log.debug("Datastream to validate: " + datastream); DatastreamsInput datastreamsInput = new DatastreamsInput(); String result = datastreamsInput.datastreamsInput(datastream, schemaId, null); log.debug("Validation result: " + result); } else { isDataStream = false; log.debug("No datastream create"); } } if (connectionId != 0) { int serviceId = Integer .parseInt(arg0.getJobDetail().getJobDataMap().getString("serviceId")); String hostName = arg0.getJobDetail().getJobDataMap().getString("ftpServerIp"); String port = arg0.getJobDetail().getJobDataMap().getString("port"); String userName = arg0.getJobDetail().getJobDataMap().getString("userName"); String password = arg0.getJobDetail().getJobDataMap().getString("password"); String inputDirectory = arg0.getJobDetail().getJobDataMap().getString("inputDirectory"); String fileName = arg0.getJobDetail().getJobDataMap().getString("fileName"); ConnectionsEntity conn; conn = connectionsDao.find(connectionId); if (inputDirectory == null || inputDirectory.trim().length() == 0) { inputDirectory = fileName; } else if (!(conn.getIdConnType() == GenericType.uploadTypeConn && serviceId == Servers.HTTP.getDbCode())) { inputDirectory = inputDirectory + "/" + fileName; } log.info("(jobId:" + jobEntity.getName() + ") - Trying to Server polling at server [" + hostName + ":" + port + "] with user[" + userName + "]."); String url = ""; if (serviceId == Servers.SAMBA.getDbCode()) { if (!fsManager.hasProvider("smb")) { fsManager.addProvider("smb", new SmbFileProvider()); } url = "smb://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.HTTP.getDbCode()) { if (!fsManager.hasProvider("http")) { fsManager.addProvider("http", new HttpFileProvider()); } url = "http://" + hostName + ":" + port + "/" + inputDirectory; } else if (serviceId == Servers.FTP.getDbCode()) { if (!fsManager.hasProvider("ftp")) { fsManager.addProvider("ftp", new FtpFileProvider()); } url = "ftp://" + userName + ":" + password + "@" + hostName + ":" + port + "/" + inputDirectory; } log.info("url:" + url); final FileObject fileObject = fsManager.resolveFile(url); if (conn.getIdConnType() == GenericType.DownloadTypeConn) { if (conn.getFileDateTime() != null && conn.getFileDateTime().getTime() == fileObject .getContent().getLastModifiedTime()) { log.info("There is no New or Updated '" + fileName + "' file on server to validate. Returning ..."); return; } else { log.info("There is New or Updated '" + fileName + "' file on server to validate. Validating ..."); ConnectionsEntity connection = connectionsDao.find(connectionId); connection.setFileDateTime( new Date(fileObject.getContent().getLastModifiedTime())); ApplicationContext ctx = AppContext.getApplicationContext(); ConnectionsDao connDao = (ctx.getBean(ConnectionsDao.class)); if (connDao != null) { connDao.update(connection); } Map<String, byte[]> resultMap = new HashMap<String, byte[]>(); byte data[] = new byte[(int) fileObject.getContent().getSize()]; fileObject.getContent().getInputStream().read(data); resultMap.put(fileObject.getName().getBaseName(), data); Set<String> keySet = resultMap.keySet(); Iterator<String> itr = keySet.iterator(); while (itr.hasNext()) { String strFileName = itr.next(); String result = ""; try { Long longSchemaId = schemaId; SchemaEntity schemaEntity = schemasDao.find(longSchemaId); if (schemaEntity == null) { result = "No schema found in database with Id [" + longSchemaId + "]"; log.error(result); logDao.setErrorLogMessage(result); } else { if (strFileName.endsWith(FileExtensionType.ZIP.getAbbreviation())) { // Case 1: When user upload a Zip file - All ZIP entries should be validate one by one ZipInputStream inStream = null; try { inStream = new ZipInputStream( new ByteArrayInputStream(resultMap.get(fileName))); ZipEntry entry; while (!(isStreamClose(inStream)) && (entry = inStream.getNextEntry()) != null) { if (!entry.isDirectory()) { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput .setUploadedFileName(entry.getName()); byte[] byteInput = IOUtils.toByteArray(inStream); result += datastreamsInput.datastreamsInput( new String(byteInput), longSchemaId, byteInput); } inStream.closeEntry(); } log.debug(result); } catch (IOException ex) { result = "Error occured during fetch records from ZIP file."; log.error(result); logDao.setErrorLogMessage(result); } finally { if (inStream != null) inStream.close(); } } else { DatastreamsInput datastreamsInput = new DatastreamsInput(); datastreamsInput.setUploadedFileName(strFileName); result = datastreamsInput.datastreamsInput( new String(resultMap.get(strFileName)), longSchemaId, resultMap.get(strFileName)); log.debug(result); } } } catch (Exception ex) { ex.printStackTrace(); result = "Exception occured during process the message for xml file " + strFileName + " Error - " + ex.getMessage(); log.error(result); logDao.setErrorLogMessage(result); } } } } else if (isDataStream && (conn.getIdConnType() == GenericType.uploadTypeConn)) { File uploadFile = File.createTempFile(fileName, ".tmp"); try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadFile)); bw.write(datastream); bw.flush(); bw.close(); } catch (IOException ioex) { log.error("Datastream file can't be created"); logDao.setErrorLogMessage("Datastream file can't be created"); return; } if (serviceId == Servers.HTTP.getDbCode()) { try { HttpClient httpclient = new HttpClient(); PostMethod method = new PostMethod(url); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); Part[] parts = new Part[] { new FilePart("file", uploadFile.getName(), uploadFile) }; method.setRequestEntity( new MultipartRequestEntity(parts, method.getParams())); method.setDoAuthentication(true); int statusCode = httpclient.executeMethod(method); String responseBody = new String(method.getResponseBody()); if (statusCode != HttpStatus.SC_OK) { throw new HttpException(method.getStatusLine().toString()); } else { System.out.println(responseBody); } method.releaseConnection(); } catch (Exception ex) { log.error("Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file at HTTP Server: " + ex.getMessage()); } } else { try { FileObject localFileObject = fsManager .resolveFile(uploadFile.getAbsolutePath()); fileObject.copyFrom(localFileObject, Selectors.SELECT_SELF); System.out.println("File uploaded at : " + new Date()); if (uploadFile.exists()) { uploadFile.delete(); } } catch (Exception ex) { log.error( "Exception occurred during uploading of file: " + ex.getMessage()); logDao.setErrorLogMessage( "Exception occurred during uploading of file: " + ex.getMessage()); } } } } } catch (Exception ex) { log.error("Error " + ": " + ex.getMessage()); } finally { fsManager.close(); } } finally { jobsDao.setWorkStatus(jobId, false); } } else { log.error("Can not set " + jobEntity.getName() + "working."); } } else { log.debug("Job " + jobEntity.getName() + " is working."); } }
From source file:org.runnerup.export.RunKeeperSynchronizer.java
@Override public Status upload(SQLiteDatabase db, final long mID) { Status s;//from w ww .j a v a 2 s . co m if ((s = connect()) != Status.OK) { return s; } /** * Get the fitnessActivities end-point */ HttpURLConnection conn = null; Exception ex; try { URL newurl = new URL(REST_URL + fitnessActivitiesUrl); Log.e(Constants.LOG, "url: " + newurl.toString()); conn = (HttpURLConnection) newurl.openConnection(); conn.setDoOutput(true); conn.setRequestMethod(RequestMethod.POST.name()); conn.addRequestProperty("Authorization", "Bearer " + access_token); conn.addRequestProperty("Content-type", "application/vnd.com.runkeeper.NewFitnessActivity+json"); RunKeeper rk = new RunKeeper(db); BufferedWriter w = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream())); rk.export(mID, w); w.flush(); int responseCode = conn.getResponseCode(); String amsg = conn.getResponseMessage(); conn.disconnect(); conn = null; if (responseCode >= HttpStatus.SC_OK && responseCode < HttpStatus.SC_MULTIPLE_CHOICES) { s = Status.OK; s.activityId = mID; return s; } ex = new Exception(amsg); } catch (Exception e) { ex = e; } if (ex != null) { Log.e(getName(), "Failed to upload: " + ex.getMessage()); } if (conn != null) { conn.disconnect(); } s = Synchronizer.Status.ERROR; s.ex = ex; s.activityId = mID; return s; }
From source file:fr.mcc.ginco.rest.services.ExportRestService.java
private File writeExportFile(Thesaurus targetThesaurus, boolean alphabetical) { File temp;/*from w w w . jav a 2 s .c o m*/ BufferedWriter out = null; try { temp = File.createTempFile("pattern", ".suffix"); temp.deleteOnExit(); out = new BufferedWriter(new FileWriter(temp)); if (alphabetical) { out.write(LabelUtil.getResourceLabel("export-alphabetical").concat(" ")); } else { out.write(LabelUtil.getResourceLabel("export-hierarchical").concat(" ")); } out.write(targetThesaurus.getTitle()); out.newLine(); out.newLine(); out.flush(); List<FormattedLine> result; if (alphabetical) { result = exportService.getAlphabeticalText(targetThesaurus); } else { result = exportService.getHierarchicalText(targetThesaurus); } for (FormattedLine results : result) { for (int i = 0; i < results.getTabs(); i++) { out.write(TABULATION_DELIMITER); } out.write(StringEscapeUtils.unescapeHtml4(results.getText().replace("'", "'")) .replaceAll("<br>", "")); out.newLine(); out.flush(); } out.close(); } catch (IOException e) { throw new BusinessException("Cannot create temp file!", "cannot-create-file", e); } return temp; }
From source file:com.sec.ose.osi.sdk.protexsdk.discovery.report.spdx.SPDXReportGenerator.java
public int generator(String projectName, String targetFilePath, UIResponseObserver observer) { log.debug("generate SPDX Document : " + projectName); try {//www. java 2 s . com String pMessage = " > Load SPDX Document from Server.\n"; if (observer != null) { observer.pushMessageWithHeader(pMessage); } // 1. select project String projectId = ProjectAPIWrapper.getProjectID(projectName); // 2. setup report configuration (below are full config that we can setup) SpdxReportConfiguration spdxReportConfiguration = new SpdxReportConfiguration(); /** Spec. 2 SPDX DOCUMENT INFORMATION **/ // Unused // spdxReportConfiguration.setDocumentComment(""); /** Spec. 3 CREATION INFORMATION **/ spdxReportConfiguration.setOrganization(LoginSessionEnt.getInstance().getOrganization()); spdxReportConfiguration.setOrganizationEmail("Unknown"); try { User userInfo = ProtexSDKAPIManager.getUserAPI() .getUserByEmail(LoginSessionEnt.getInstance().getUserID()); spdxReportConfiguration.setCreatedBy(userInfo.getFirstName() + " " + userInfo.getLastName()); } catch (SdkFault e1) { e1.printStackTrace(); spdxReportConfiguration.setCreatedBy("Unknown"); } spdxReportConfiguration.setCreatedByEMail(LoginSessionEnt.getInstance().getUserID()); /** Spec. 4 PACKAGE INFORMATION **/ spdxReportConfiguration.setPackageName(projectName); spdxReportConfiguration.setPackageVersion(""); spdxReportConfiguration.setPackageFileName(""); spdxReportConfiguration.setPackageLicenseDeclarationType(SpdxLicenseDeclarationType.NO_ASSERTION); spdxReportConfiguration.setAllLicenseInfoFromFilesType(SpdxAllLicenseInfoFromFileType.NO_ASSERTION); spdxReportConfiguration.setPackageLicenseConclusionType(SpdxPackageLicenseConclusionType.NO_ASSERTION); // Unused spdxReportConfiguration.setLicenseComment(""); // Spec 4. Comments On License (not available, protex error??) spdxReportConfiguration.setPackageDownloadUrl(""); // Spec 4. Package Download Location spdxReportConfiguration.setPackageSourceInformation(""); // Spec 4. Source Information // (not available, protex error??) spdxReportConfiguration.setCopyright(""); // Spec 4. Copyright Text spdxReportConfiguration.setPackageDescription(""); // Spec 4. Package Detailed Description /** Spec. 7 REVIEW INFORMATION **/ /** DEFAULT SETTING **/ spdxReportConfiguration.setFileLicenseConclusionType(SpdxFileLicenseConclusionType.NO_ASSERTION); // COMPONENT_IDENTIFIED_LICENSES | NO_ASSERTION System.out.println(LoginSessionEnt.getInstance().getProtexServerUrl()); spdxReportConfiguration.setProtexUrl(LoginSessionEnt.getInstance().getProtexServerUrl()); /** I don't know what it is **/ // Unused spdxReportConfiguration.setReportComment(""); // 3. setup report format SpdxReportFormat reportFormat = SpdxReportFormat.RDF; // HTML | RDF | RDF_AND_XLS_WRAPPED_IN_ZIP | XLS // 4. generate SPDX report Report report = ProtexSDKAPIManager.getReportAPI().generateSpdxReport(projectId, spdxReportConfiguration, reportFormat); // file write pMessage = " > Save SPDX Document.\n"; if (observer != null) { observer.pushMessageWithHeader(pMessage); } BufferedReader SPDXReportReader = null; BufferedWriter SPDXReportWriter = null; if (report != null && report.getFileContent() != null) { try { SPDXReportReader = new BufferedReader( new InputStreamReader(report.getFileContent().getInputStream(), "UTF-8")); SPDXReportWriter = new BufferedWriter(new FileWriter(targetFilePath)); String tmpStr = null; while ((tmpStr = SPDXReportReader.readLine()) != null) { SPDXReportWriter.write(tmpStr + "\n"); } SPDXReportWriter.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { SPDXReportReader.close(); SPDXReportWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } return 0; } catch (SdkFault e) { e.printStackTrace(); } return 1; }
From source file:cn.org.once.cstack.service.impl.ScriptingServiceImpl.java
public void execute(String scriptContent, String login, String password) throws ServiceException { logger.info(scriptContent);// ww w . j av a2s.c o m File tmpFile = null; FileWriter fileWriter = null; BufferedWriter writer = null; ProcessBuilder processBuilder = null; try { tmpFile = File.createTempFile(login, ".cmdFile"); fileWriter = new FileWriter(tmpFile); writer = new BufferedWriter(fileWriter); String commandConnect = CONNECT_CMD.replace("#USER", login).replace("#PASSWORD", password) .replace("#HOST", host); logger.debug(commandConnect); writer.append(commandConnect); writer.newLine(); writer.append(scriptContent); writer.newLine(); writer.append(DISCONNECT_CMD); writer.flush(); logger.debug(writer.toString()); File fileCLI = new File(pathCLI); if (!fileCLI.exists()) { System.out.println("Error ! "); StringBuilder msgError = new StringBuilder(512); msgError.append( "\nPlease run manually (1) : mkdir -p " + pathCLI.substring(0, pathCLI.lastIndexOf("/"))); msgError.append( "\nPlease run manually (2) : wget https://github.com/Treeptik/cloudunit/releases/download/1.0/CloudUnitCLI.jar -O " + pathCLI); throw new ServiceException(msgError.toString()); } processBuilder = new ProcessBuilder("java", "-jar", pathCLI, "--cmdfile", tmpFile.getAbsolutePath()); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = ""; try { while ((line = reader.readLine()) != null) { logger.info(line); if (line.contains("not found")) throw new ServiceException("Syntax error : " + line); if (line.contains("Invalid or corrupt jarfile")) throw new ServiceException("Invalid or corrupt jarfile"); } } finally { reader.close(); } } catch (IOException e) { StringBuilder msgError = new StringBuilder(512); msgError.append("login=").append(login); msgError.append(", password=").append(password); msgError.append(", scriptContent=").append(scriptContent); logger.error(msgError.toString(), e); } finally { try { fileWriter.close(); } catch (Exception ignore) { } try { writer.close(); } catch (Exception ignore) { } } }
From source file:tagtime.beeminder.BeeminderGraph.java
public void writeToBeeFile(String id, long timestamp, double hours, String comment) { if (id == null) { throw new IllegalArgumentException("id cannot be null!"); }/* w w w .j a v a 2s . c om*/ BufferedWriter fileWriter; try { fileWriter = new BufferedWriter(new FileWriter( Main.getDataDirectory().getPath() + "/" + tagTimeInstance.username + "_" + graphName + ".bee")); } catch (IOException e) { e.printStackTrace(); return; } try { fileWriter.append(id + " " + timestamp + " " + hourFormatter.format(hours) + " " + comment); fileWriter.flush(); } catch (IOException e) { e.printStackTrace(); } try { fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.orange.mmp.bind.JSONClientBinding.java
/** * Sends the request to WebService and return an object built from * JSON response./*from w ww. java 2 s. co m*/ * @return A binding object in a JSONObject, JSONArray or String */ public Object getResponse(InputStream postData) throws BindingException { StringWriter responseContent = new StringWriter(); BufferedReader reader = null; BufferedWriter writer = null; //Get response try { this.getHttpConnection().init(this.buildURL(), this.timeout); if (postData != null) this.getHttpConnection().sendData(postData); InputStream httpIn = this.getHttpConnection().getData(); if (httpIn != null) { writer = new BufferedWriter(responseContent); reader = new BufferedReader(new InputStreamReader(httpIn, Constants.DEFAULT_ENCODING)); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.newLine(); writer.flush(); } } else return null; } catch (UnsupportedEncodingException uee) { throw new BindingException("Unsupported encoding from " + this.epr + " : " + uee.getMessage()); } catch (IOException ioe) { throw new BindingException("Failed to get response : " + ioe.getMessage()); } catch (MMPNetException mne) { throw new BindingException("Failed to get response : " + mne.getMessage()); } finally { try { if (reader != null) reader.close(); if (writer != null) writer.close(); this.releaseConnection(); } catch (MMPNetException mne) { //Nop, logs in AOP } catch (IOException ioe) { //Nop, logs in AOP } } //Parse response if (responseContent == null) throw new BindingException("Failed to parse response : empty result"); String jsonString = responseContent.toString(); if (jsonString.length() == 0) throw new BindingException("Failed to parse response : empty result"); try { JSONTokener tokener = new JSONTokener(jsonString); return tokener.nextValue(); } catch (JSONException je) { throw new BindingException("Failed to parse response : " + je.getMessage()); } }
From source file:app.utils.ACache.java
public void put(String key, String value) { File file = mCache.newFile(key); BufferedWriter out = null; try {/* www . j av a 2 s. co m*/ out = new BufferedWriter(new FileWriter(file), 1024); out.write(value); } catch (IOException e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } mCache.put(file); } }