Example usage for java.io FileWriter append

List of usage examples for java.io FileWriter append

Introduction

In this page you can find the example usage for java.io FileWriter append.

Prototype

@Override
    public Writer append(CharSequence csq) throws IOException 

Source Link

Usage

From source file:UserInterface.AdministrativeRole.RequestAnalysis.java

private void ExportBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportBtnActionPerformed
    // TODO add your handling code here:
    try {//  w  w w  . j  a  v a2 s . co  m
        if (enterprise.getOrganizationDirectory().getOrganizationList().size() > 0) {
            Organization organization = null;
            //System.out.println(enterprise.getOrganizationDirectory().getOrganizationList().size());
            for (Organization org : enterprise.getOrganizationDirectory().getOrganizationList()) {
                if (org instanceof ProcurementOrganization) {
                    organization = org;
                    //System.out.println(organization);
                    break;
                }
            }
            FileWriter writer = new FileWriter(System.getProperty("user.dir") + "\\test.csv");
            //in = new FileInputStream(new File (System.getProperty("user.dir")+"\\Sound.wav"));
            writer.append("Request ID");
            writer.append(',');
            writer.append("Requester");
            writer.append(',');
            writer.append("Requester Organization");
            writer.append(',');
            writer.append("Machine Name");
            writer.append(',');
            writer.append("Machine Status");
            writer.append(',');
            writer.append("Requested Date");
            writer.append(',');
            writer.append("Total Price");
            writer.append(',');
            writer.append("Requester Message");
            writer.append(',');

            writer.append('\n');
            if (organization.getWorkQueue().getWorkRequestList().size() > 0) {
                for (WorkRequest request : organization.getWorkQueue().getWorkRequestList()) {
                    writer.append(String.valueOf(request.getWorkRequestId()));
                    writer.append(',');
                    writer.append(request.getSender().getUsername());
                    writer.append(',');
                    writer.append(request.getOrg().getName());
                    writer.append(',');
                    writer.append(request.getMachine().getMachineName());
                    writer.append(',');
                    writer.append(request.getMachine().getSensorData().getSensorVlaue());
                    writer.append(',');
                    writer.append(request.getRequestDate().toString());
                    writer.append(',');
                    writer.append(String.valueOf(request.getTotalPrice()));
                    writer.append(',');
                    writer.append(request.getMessage());
                    writer.append(',');
                    writer.append('\n');

                }
            }

            writer.flush();
            writer.close();
            JOptionPane.showMessageDialog(this, "Record Exported Successfully", "Export",
                    JOptionPane.INFORMATION_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, "No Organization Present");
        }
    } catch (Exception e) {
        System.out.println("inside");
        System.out.println(e.getMessage());

    }
}

From source file:it.txt.access.capability.demo.soap.server.service.impl.CapabilityServiceHelper.java

public void performRequestOperation(ServiceRequestInfoModel infoModel) throws CapabilityServiceException {
    File requestFile;//from  w  ww  .j a v a 2s  .c  o  m
    //Recover request operation.
    String operation = infoModel.getOperation();
    //Recover request resource.
    String resourceID = infoModel.getResourceID();
    //Recover the file specified by the resource.
    //Before perfor the operation, check if the request is valid
    checkRequestOperation(infoModel);
    try {
        requestFile = new File(new URI(resourceID));
    } catch (Exception ex) {
        //The Resource is not an URi;
        LOGGER.log(Level.INFO, ex.getMessage(), ex);
        requestFile = new File(resourceID);
    }
    LOGGER.log(Level.INFO, "The Resource ID Path: {0}", requestFile.getAbsolutePath());
    //Check the operation type
    if (operation.equalsIgnoreCase(ClientServerUtils.OPERATION_UPDATE)) {
        if (!requestFile.exists()) {
            //can not perform update operation.
            throw new CapabilityServiceException(RESPONSE_OPERATION_RESOURCE_NOT_EXIST);
        }
    } else if (operation.equalsIgnoreCase(ClientServerUtils.OPERATION_READ)) {
        if (!requestFile.exists()) {
            //can not perform read operation.
            throw new CapabilityServiceException(RESPONSE_OPERATION_RESOURCE_NOT_EXIST);
        }
    } else if (operation.equalsIgnoreCase(ClientServerUtils.OPERATION_DELETE)) {
        if (!requestFile.exists()) {
            //can not perform delete operation.
            throw new CapabilityServiceException(RESPONSE_OPERATION_RESOURCE_NOT_EXIST);
        } else {
            //can not perform delete operation over directory.
            if (requestFile.isDirectory()) {
                throw new CapabilityServiceException(RESPONSE_OPERATION_DELETE_NOT_PERFORMED);
            } else if (requestFile.isFile()) {
                if (!requestFile.delete()) {
                    //can not perform delete operation.
                    throw new CapabilityServiceException(RESPONSE_OPERATION_DELETE_NOT_PERFORMED);
                }
            } else {
                //The resourceID is not a file.
                throw new CapabilityServiceException(RESPONSE_OPERATION_DELETE_NOT_PERFORMED);
            }
        }
    } else if (operation.equalsIgnoreCase(ClientServerUtils.OPERATION_CREATE)) {
        if (requestFile.exists()) {
            //can not perform create operation.
            throw new CapabilityServiceException(RESPONSE_OPERATION_CREATE_ALREADY_EXIST);
        } else {
            try {
                //write something to the created file
                FileWriter fileWriter = new FileWriter(requestFile.toURI().getPath());
                fileWriter.append(OPERATION_CREATE_FILE_CONTENT);
                fileWriter.close();
            } catch (IOException ex) {
                String response = "";
                response += ClientServerUtils.RESPONSE_INTERNAL_ERROR;
                response += " ";
                response += RESPONSE_OPERATION_CREATE_NOT_PERFORMED;
                throw new CapabilityServiceException(response, ex);
            }
        }
    } else {
        //due the checkRequestValidity this case should not been performed.
        throw new CapabilityServiceException(ClientServerUtils.RESPONSE_REQUEST_OPERATION_NOT_PERFORMED);
    }
}

From source file:dk.netarkivet.archive.arcrepositoryadmin.ReplicaCacheDatabaseTester.java

License:asdf

private File makeTemporaryEmptyFilelistFile() throws Exception {
    File res = new File(TestInfo.TEST_DIR, "filelist_empty.out");
    FileWriter fw = new FileWriter(res);

    StringBuilder fileContent = new StringBuilder("");

    fw.append(fileContent.toString());
    fw.flush();/*from   w  ww  .  j a v a2s . co  m*/
    fw.close();

    return res;
}

From source file:org.openmrs.module.birt.report.renderer.BirtDocTemplateRenderer.java

public void prepareDatasets(ReportData reportData, BirtReport report) {

    Iterator<Entry<String, DataSet>> iter = reportData.getDataSets().entrySet().iterator();

    List<String> fileNames = null;
    while (iter.hasNext()) {
        Map.Entry<String, DataSet> mEntry = (Map.Entry<String, DataSet>) iter.next();

        DataSet dataset = (DataSet) mEntry.getValue();

        List<DataSetColumn> columns = dataset.getMetaData().getColumns();

        try {//  w  w  w  .  j a v  a 2s .c  o  m
            String fileName = mEntry.getKey() + ".csv";
            FileWriter w = new FileWriter(report.getOutputDirectory() + fileName);
            fileNames = new ArrayList<String>();
            fileNames.add(fileName);

            // header row
            w.append(getBeforeRowDelimiter());
            for (DataSetColumn column : columns) {
                w.append(getBeforeColumnDelimiter());
                w.append(escape(column.getName()));
                w.append(getAfterColumnDelimiter());
            }
            w.append(getAfterRowDelimiter());

            // data rows
            for (DataSetRow row : dataset) {
                w.append(getBeforeRowDelimiter());
                for (DataSetColumn column : columns) {
                    Object colValue = row.getColumnValue(column);
                    w.append(getBeforeColumnDelimiter());
                    if (colValue != null) {
                        if (colValue instanceof Cohort) {
                            w.append(escape(Integer.toString(((Cohort) colValue).size())));
                        } else if (colValue instanceof IndicatorResult) {
                            w.append(((IndicatorResult) colValue).getValue().toString());
                        } else {
                            // this check is because a logic EmptyResult .toString() -> null
                            String temp = escape(colValue.toString());
                            if (temp != null)
                                w.append(temp);
                        }
                    }
                    w.append(getAfterColumnDelimiter());
                }
                w.append(getAfterRowDelimiter());
            }

            w.close();
        } catch (IOException e) {
            throw new RenderingException("Error: " + e, e);
        }
    }

    report.setCsvFileNames(fileNames);
}

From source file:org.openmrs.module.birt.report.renderer.BirtPdfTemplateRenderer.java

public void prepareDatasets(ReportData reportData, BirtReport report) {

    Iterator<Entry<String, DataSet>> iter = reportData.getDataSets().entrySet().iterator();

    List<String> fileNames = null;
    while (iter.hasNext()) {
        Map.Entry<String, DataSet> mEntry = (Map.Entry<String, DataSet>) iter.next();

        DataSet dataset = (DataSet) mEntry.getValue();

        List<DataSetColumn> columns = dataset.getMetaData().getColumns();

        try {/*  w ww . j  a  v  a  2  s. c om*/
            String fileName = mEntry.getKey() + ".csv";
            FileWriter w = new FileWriter(report.getOutputDirectory() + fileName);
            fileNames = new ArrayList<String>();
            fileNames.add(fileName);

            // header row
            w.append(getBeforeRowDelimiter());
            for (DataSetColumn column : columns) {
                w.append(getBeforeColumnDelimiter());
                w.append(escape(column.getName()));
                w.append(getAfterColumnDelimiter());
            }
            w.append(getAfterRowDelimiter());

            // data rows
            for (DataSetRow row : dataset) {
                w.append(getBeforeRowDelimiter());
                for (DataSetColumn column : columns) {
                    Object colValue = row.getColumnValue(column);
                    w.append(getBeforeColumnDelimiter());
                    if (colValue != null) {
                        if (colValue instanceof Cohort) {
                            w.append(escape(Integer.toString(((Cohort) colValue).size())));
                        } else if (colValue instanceof IndicatorResult) {
                            w.append(((IndicatorResult) colValue).getValue().toString());
                        } else {
                            // this check is because a logic EmptyResult .toString() -> null
                            String temp = escape(colValue.toString());
                            if (temp != null)
                                w.append(temp);
                        }
                    }
                    w.append(getAfterColumnDelimiter());
                }
                w.append(getAfterRowDelimiter());
            }

            w.close();
        } catch (IOException e) {
            throw new RenderingException("Error: " + e, e);
        }
    }
    report.setCsvFileNames(fileNames);
}

From source file:wsattacker.plugin.dos.dosExtension.result.ResultGenerator.java

private void saveMetadata(File metadata) throws IOException {
    // Save Metadata to file
    FileWriter writer = new FileWriter(metadata);

    // Attack Name + Target
    writer.append("+++++++++++++++++++++++++++\n");
    writer.append("Attack Summary\n");
    writer.append("+++++++++++++++++++++++++++\n");
    writer.append("attack Name: " + attackModel.getAttackName());
    writer.append("\n\n");
    writer.append("Attack Description:\n");
    writer.append("-------------------\n");
    writer.append(attackModel.getAttackDescription());
    writer.append("\n\n");
    writer.append("Attack Countermeasures:\n");
    writer.append("-----------------------\n");
    writer.append(attackModel.getAttackCountermeasures());
    writer.append("\n\n");
    writer.append("+++++++++++++++++++++++++++\n");
    writer.append("Attack Metadata:");
    writer.append("\n\n");
    writer.append("" + "Attack start: " + attackModel.getStartDate() + "\n" + "Attack stop: "
            + attackModel.getStopDate() + "\n" + "Parallel threads: " + attackModel.getNumberThreads() + "\n"
            + "Requests per thread: " + attackModel.getNumberRequestsPerThread() + "\n"
            + "Request repeat interval: " + (attackModel.getSecondsBetweenRequests()) + " ms\n"
            + "Server recovery time: " + (attackModel.getSecondsServerLoadRecovery() / 1000) + " sec\n"
            + "Send testprobes: " + attackModel.getCounterProbesSend() + "\n" + "Testprobe repeat interval: "
            + (attackModel.getSecondsBetweenProbes()) + " ms\n" + "Size testprobe request: "
            + attackModel.getRequestSizeTestProbe() + " Bytes\n" + "Size untampered request: "
            + attackModel.getRequestSizeUntampered() + " Bytes\n" + "Size tampered request: "
            + attackModel.getRequestSizeTampered() + " Bytes\n" + "Size untampered padded request: "
            + attackModel.getRequestSizePaddedUntampered() + " Bytes\n" + "Size tampered padded request: "
            + attackModel.getRequestSizePaddedTampered() + " Bytes\n"
            + "Median response time untampered requests: " + attackModel.getMedianUntampered() + " ms\n"
            + "Median response time tampered requests: " + attackModel.getMedianTampered() + " ms\n"
            + "Auto finialize attack switch: " + attackModel.isAutoFinalizeSwitch() + "\n"
            + "Auto finialize attack duration: " + attackModel.getAutoFinalizeSeconds() + " seconds\n" + "\n");
    writer.append("Custom Attack parameters: \n");
    writer.append(attackModel.getCustomAttackParameters());
    writer.append("\n\n");
    writer.append("+++++++++++++++++++++++++++\n");
    writer.append("Attack Success Metric - see help file for more info:");
    writer.append("\n\n");
    writer.append("Attack roundtrip time ratio: " + attackModel.getAttackRoundtripTimeRatio() + " Points - "
            + attackModel.getAttackRoundtripTimeRatioDescription("text"));
    writer.append("\n\n");
    writer.append("Request size ratio: " + attackModel.getAttackRatioRequestsize() + " Points - "
            + attackModel.getAttackRatioRequestsizeDescription("text"));
    writer.append("\n\n");

    writer.append("testprobe roundtrip time after attack (length " + attackModel.getAttackLongevitySeconds()
            + " sec): " + attackModel.getTestProbeAttackRoundtripTime() + " seconds - "
            + attackModel.getTestProbeAttackRoundtripTimeDescription("text"));
    writer.append("\n\n");
    writer.append("+++++++++++++++++++++++++++\n");
    writer.append("Requests:");
    writer.append("\n\n");
    writer.append("target Endpoint: " + attackModel.getWsdlUrl());
    writer.append("\n\n");
    writer.append("Testprobe Request:\n");
    writer.append("------------------\n");
    Iterator<String> iterator = attackModel.getOriginalRequestHeaderFields().keySet().iterator();
    while (iterator.hasNext()) {
        String key = iterator.next();
        String value = attackModel.getOriginalRequestHeaderFields().get(key).toString();
        writer.append(key).append(": ").append(value).append("\n");
    }/*  w  w  w  .  j  ava2  s  .  c  o  m*/
    writer.append("\n");
    writer.append(attackModel.getWsdlRequestOriginal().getRequestContent());
    writer.append("\n\n");
    writer.append("Untampered Request:\n");
    writer.append("-------------------\n");
    writer.append(attackModel.getUntamperedRequestObject().getHeaderString("\n"));
    writer.append("\n");
    writer.append(attackModel.getUntamperedRequestObject().getXmlMessage());
    writer.append("\n\n");
    writer.append("Tampered Request:\n");
    writer.append("-----------------\n");
    writer.append(attackModel.getTamperedRequestObject().getHeaderString("\n"));
    writer.append("\n");
    writer.append(attackModel.getTamperedRequestObject().getXmlMessage());

    writer.flush();
    writer.close();
}

From source file:tml.conceptmap.TerminologicalConceptMap.java

public void writeToXML(String filename) throws Exception {
    FileWriter writer = new FileWriter(filename);
    writer.append("<?xml version=\"1.0\"?>\n");
    writer.append("<conceptmap>\n");
    for (TerminologicalConcept concept : this.vertexSet()) {
        writer.append("  <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(concept.getTerm()));
        writer.append("\"/>\n");
    }//from   w w  w .  ja  v  a  2  s.co m
    for (TerminologicalRelationship<TerminologicalConcept> relationship : this.edgeSet()) {
        writer.append("  <relationship label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getLinkingWord()));
        writer.append("\">\n");
        writer.append("    <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getSource().getTerm()));
        writer.append("\"/>\n");
        writer.append("    <concept label=\"");
        writer.append(StringEscapeUtils.escapeXml(relationship.getTarget().getTerm()));
        writer.append("\"/>\n");
        writer.append("  </relationship>\n");
    }
    writer.append("</conceptmap>\n");
    writer.close();
}

From source file:File.WriteNewTrack.java

/**
 * Metda processRequest je obslun metda, ktor sa vol po vyvolan danho servletu na strane pouvatea. 
 * Pri?om sa servlet vykonva na strane servera.
 * @param request - objekt poiadavky, ktor sa prena zo strany klienta na stranu servera
 * @param response - objekt odozvy servera, ktor sa prena zo strany servera na stranu klienta
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 *//*www .j a  va 2  s  . c om*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    String trackName = session.getAttribute("trackName").toString();
    String trackDescr = session.getAttribute("trackDescr").toString();
    String trackActivity = session.getAttribute("trackActivity").toString();
    String access = session.getAttribute("access").toString();

    session.setAttribute("trackNameExist", "False");
    //        if (system.startsWith("Windows")) {
    //            String tempPath = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
    //            //String tempPath = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                //tempFile.delete();
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        } else {
    //            String tempPath = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/" + session.getAttribute("username") + "/Temp" + "/";
    //            File tempFile = new File(tempPath);
    //            if (tempFile.exists()) {
    //                System.out.println("Mam temp a vymazujem!");
    //                FileUtils.deleteDirectory(tempFile);
    //                FileLogger.getInstance().createNewLog("Warning: Found old temp folder which belongs to " + session.getAttribute("username") + " !!! Successfuly delete the old temp.");
    //            }
    //        }

    if (system.startsWith("Windows")) {
        //pathToFile = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\";
        //pathToMultimedia = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\Temp" + "\\Multimedia\\";
        pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                + session.getAttribute("username") + "\\Temp" + "\\";
        pathToMultimedia = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                + session.getAttribute("username") + "\\Temp" + "\\Multimedia\\";
    } else {
        pathToFile = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                + session.getAttribute("username") + "/Temp" + "/";
        pathToMultimedia = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                + session.getAttribute("username") + "/Temp" + "/Multimedia/";
    }

    File tempF = new File(pathToFile + "Temp.txt");
    if (tempF.exists()) {
        FileUtils.forceDelete(tempF);
        FileLogger.getInstance()
                .createNewLog("Warning: Found tamp file Temp.txt in WriteNewTrack which belongs to user "
                        + session.getAttribute("username") + " while writing new track " + trackName + " !!!");
    }

    File multF = new File(pathToMultimedia);
    MultimediaSearcher searcher = new MultimediaSearcher();
    searcher.setSearchFolder(pathToMultimedia);
    String[] files = searcher.startSearchWithoutTrack();
    if (files.length >= 1) {
        session.setAttribute("isMultimedia", "True");
    }

    new File(pathToFile).mkdirs();
    File file = new File(pathToFile, "Temp.txt"); // Write to destination file. Pouyivaj filename!
    boolean create = file.createNewFile();
    //System.out.println("Vytvoril: " + create);

    if (file.exists()) {
        String latLngStr = request.getParameter("textBox");

        FileWriter writer = new FileWriter(file, true);
        BufferedWriter buf = new BufferedWriter(writer);

        writer.append(latLngStr);

        buf.close();
        writer.close();
    }
    if (session.getAttribute("isMultimedia") != null) {
        request.getRequestDispatcher("SynchronizeDrawTrack.jsp").forward(request, response);
    } else {
        try {

            String pathToTemp;
            String pathToTempFile;
            String pathToMultimediaFiles;

            String filename = trackName + ".gpx";
            if (system.startsWith("Windows")) {
                //pathToFile = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + trackName + "\\";
                //pathToTemp = "D:\\GitHub\\GPSWebApp\\web\\Logged\\uploaded_from_server\\" + session.getAttribute("username") + "\\" + "Temp" + "\\";
                //pathToTempFile = pathToFile + "Temp.txt";
                pathToFile = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                        + session.getAttribute("username") + "\\" + trackName + "\\";
                pathToTemp = "E:\\SCHOOL\\TUKE\\DIPLOMOVKA\\PRAKTICKA CAST\\GITHUB\\GPSWebApp\\web\\Logged\\uploaded_from_server\\"
                        + session.getAttribute("username") + "\\" + "Temp" + "\\";
                pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "\\";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            } else {
                pathToFile = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                        + session.getAttribute("username") + "/" + trackName + "/";
                pathToTemp = "/usr/local/tomcat/webapps/ROOT/Logged/uploaded_from_server/"
                        + session.getAttribute("username") + "/" + "Temp" + "/";
                pathToTempFile = pathToFile + "Temp.txt";
                pathToMultimediaFiles = pathToFile + "Multimedia" + "/";
                //                    File fTemp = new File(pathToMultimediaFiles);
                //                    if(!fTemp.exists()){
                //                        fTemp.mkdirs();
                //                    }
            }

            File oldFile = new File(pathToTemp);
            File newFile = new File(pathToFile);
            oldFile.renameTo(newFile);

            GPXParser parser = new GPXParser(pathToFile, filename, session.getAttribute("username").toString(),
                    trackName);
            parser.readFromTrackPoints(pathToTempFile, trackName, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created GPXParser in STEP 3 for track " + trackName + " .");
            parser.searchForMultimediaFilesWithoutCorrection(pathToMultimediaFiles);

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly founded multimedia files in STEP 3 for track " + trackName + " .");
            parser.parseFromTrackPoints(trackActivity, trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly parsed GPX file in STEP 3 for track " + trackName + " .");
            parser.createGPXFile(trackDescr);
            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly generated GPX file in STEP 3 for track " + trackName + " .");

            DBTrackCreator tCreator = new DBTrackCreator();
            DBLoginFinder finder = new DBLoginFinder();

            tCreator.createNewTrack(trackName, trackDescr, trackActivity, pathToFile,
                    finder.getUserId(session.getAttribute("username").toString()),
                    parser.getStartAndEndDate().get(0).toString(),
                    parser.getStartAndEndDate().get(1).toString(), access, parser.getStartAddress(),
                    parser.getEndAddress(), parser.getTrackLengthKm(), parser.getTrackMinElevation(),
                    parser.getTrackMaxElevation(), parser.getTrackHeightDiff(), parser.getTrackDuration(),
                    "Drawed");

            TLVLoader loader = new TLVLoader();
            loader.readTLVFile(pathToFile, trackName);
            PDFTrackGenerator generator = new PDFTrackGenerator(loader, pathToFile, trackName);
            generator.generateTrackPDFA4(2, null, 640, 640, 1, parser.getStartAndEndDate().get(0).toString(),
                    parser.getStartAndEndDate().get(1).toString(), trackActivity,
                    session.getAttribute("username").toString());

            FileLogger.getInstance().createNewLog("For user " + session.getAttribute("username")
                    + "was successfuly created new track in STEP 3 for track " + trackName + " .");

            if (loader.getTrackPoints().get(0).getInternetElevation() == 0 && loader.getTrackPoints()
                    .get(loader.getTrackPoints().size() - 1).getInternetElevation() == 0) {
                session.setAttribute("Limit", "True");
            }

        } catch (Exception ex) {
            System.out.println("Error: Unable to create .tlv file!");
            FileLogger.getInstance().createNewLog("ERROR: Unable to create user's "
                    + request.getSession().getAttribute("username") + " track " + trackName + " in STEP 3 !!!");
            //vloyit oznacenie chyby parsera!!!
            ex.printStackTrace();
        }
        request.getRequestDispatcher("ShowTracks.jsp").forward(request, response);
    }

}

From source file:com.apkcategorychecker.writer.WriterCSV.java

private void removeBlankLines(String _csvPath) {
    try {/*from  w ww  .  j av  a2 s  . c om*/
        FileReader fr = new FileReader(_csvPath);
        BufferedReader br = new BufferedReader(fr);
        FileWriter fw = new FileWriter(_csvPath + ".temp");
        String line;

        while ((line = br.readLine()) != null) {
            //line = line.trim(); // remove leading and trailing whitespace
            if (line.length() != 0) // don't write out blank lines
            {
                fw.write(line, 0, line.length());
                fw.append("\r");
            }
        }
        fr.close();
        fw.close();
        File old = new File(_csvPath);
        old.delete();
        File clean = new File(_csvPath + ".temp");
        clean.renameTo(old);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.whizzosoftware.hobson.scheduler.ical.ICalTaskProviderTest.java

@Test
public void testEditEvent() throws Exception {
    File file = File.createTempFile("hob", ".ics");
    try {//from  www. j  a  v a  2s  .  co m
        String ical = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Action','properties':{'message':'foo'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        String ical2 = "BEGIN:VCALENDAR\n" + "PRODID:-//Whizzo Software//Hobson 1.0//EN\n" + "VERSION:2.0\n"
                + "BEGIN:VEVENT\n" + "UID:15dee4fe-a841-4cf6-8d7f-76c3ad5492b1\n" + "DTSTART:20130714T170000Z\n"
                + "DTEND:20130714T170000Z\n" + "SUMMARY:My Edited Task\n"
                + "COMMENT:[{'pluginId':'com.whizzosoftware.hobson.server-api','actionId':'log','name':'My Edited Action','properties':{'message':'foobar'}}]\n"
                + "END:VEVENT\n" + "END:VCALENDAR";

        // write out ICS to temp file
        FileWriter fw = new FileWriter(file);
        fw.append(ical);
        fw.close();

        ICalTaskProvider p = new ICalTaskProvider("pluginId", null, null,
                TimeZone.getTimeZone("America/Denver"));
        p.setScheduleExecutor(new MockScheduledTaskExecutor());
        p.setScheduleFile(file);
        p.start();

        // make sure the task was created
        assertEquals(1, p.getTasks().size());

        // create task JSON
        JSONObject json = new JSONObject();
        json.put("name", "My Edited Task");
        JSONArray conds = new JSONArray();
        json.put("conditions", conds);
        JSONObject cond = new JSONObject();
        conds.put(cond);
        cond.put("start", "20130714T170000Z");
        JSONArray actions = new JSONArray();
        json.put("actions", actions);
        JSONObject action = new JSONObject();
        actions.put(action);
        action.put("pluginId", "com.whizzosoftware.hobson.server-api");
        action.put("actionId", "log");
        action.put("name", "My Edited Action");
        JSONObject props = new JSONObject();
        action.put("properties", props);
        props.put("message", "foobar");

        // update the task
        p.updateTask("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", json);

        assertTrue(file.exists());

        // read back file
        Calendar cal = new CalendarBuilder().build(new FileInputStream(file));
        assertEquals(1, cal.getComponents().size());
        VEvent c = (VEvent) cal.getComponents().get(0);
        assertEquals("My Edited Task", c.getProperty("SUMMARY").getValue());
        assertEquals("15dee4fe-a841-4cf6-8d7f-76c3ad5492b1", c.getProperty("UID").getValue());
        assertEquals("20130714T170000Z", c.getProperty("DTSTART").getValue());
        JSONArray aj = new JSONArray(new JSONTokener(c.getProperty("COMMENT").getValue()));
        assertEquals(1, aj.length());
        JSONObject cj = aj.getJSONObject(0);
        assertEquals("com.whizzosoftware.hobson.server-api", cj.getString("pluginId"));
        assertEquals("My Edited Action", cj.getString("name"));
        assertEquals("log", cj.getString("actionId"));
        assertTrue(cj.has("properties"));
        JSONObject pj = cj.getJSONObject("properties");
        assertEquals("foobar", pj.getString("message"));
    } finally {
        file.delete();
    }
}