Example usage for java.nio.file Files copy

List of usage examples for java.nio.file Files copy

Introduction

In this page you can find the example usage for java.nio.file Files copy.

Prototype

public static long copy(InputStream in, Path target, CopyOption... options) throws IOException 

Source Link

Document

Copies all bytes from an input stream to a file.

Usage

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Copy a File or a Directory inside the AUT workspace. Existing target
 * files / Directories are overwritten without warnings.
 *
 * @param relSourcePath/*  w  ww .ja  v a  2 s .  co  m*/
 *            the workspace relative path of the source file or directory to
 *            copy
 * @param relTargetPath
 *            the workspace relative path of the target file or directory
 */
public void copyInWorkspace(String relSourcePath, String relTargetPath) {

    LOGGER.info("kopiere. " + relSourcePath + " nach " + relTargetPath);

    File workspaceDir;
    try {
        workspaceDir = new File(getWorkspacePath());
    } catch (IOException e1) {
        String msg = "cannot find workspacePath";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }
    File source = new File(workspaceDir, relSourcePath);
    File target = new File(workspaceDir, relTargetPath);
    Path sourcePath = Paths.get(source.getAbsolutePath());
    Path targetPath = Paths.get(target.getAbsolutePath());

    if (!source.exists()) {
        String msg = "cannot copy '" + source + "': File does not exist";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }
    if (!source.canRead()) {
        String msg = "cannot copy '" + source + "': File cannot be read";
        LOGGER.error(msg);
        throw new StopTestException(msg);
    }

    if (source.isDirectory()) {
        try {
            copyFolder(sourcePath, targetPath);
        } catch (IOException e) {
            String msg = "cannot copy directory '" + source + "' to '" + target + "'";
            LOGGER.error(msg, e);
            throw new StopTestException(msg, e);
        }
    } else {
        try {
            Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            String msg = "cannot copy directory '" + source + "' to '" + target + "'";
            LOGGER.error(msg, e);
            throw new StopTestException(msg, e);
        }
    }

}

From source file:eu.itesla_project.online.db.OnlineDbMVStore.java

@Override
public void exportStates(String workflowId, Path file) {
    if (workflowStatesFolderExists(workflowId)) {
        LOGGER.info("Exporting states for workflow {}", workflowId);
        Path workflowStatesFolder = getWorkflowStatesFolder(workflowId);
        Path csvFile = Paths.get(workflowStatesFolder.toString(), SERIALIZED_STATES_FILENAME);
        if (!csvFile.toFile().exists()) {
            LOGGER.info("Serializing network data of workflow {}", workflowId);
            try (FileWriter fileWriter = new FileWriter(csvFile.toFile());
                    CsvListWriter csvWriter = new CsvListWriter(fileWriter,
                            new CsvPreference.Builder('"', ';', "\r\n").build())) {
                boolean printHeaders = true;
                for (Integer stateId : listStoredStates(workflowId)) {
                    Network network = getState(workflowId, stateId);
                    if (network != null) {
                        Map<HistoDbAttributeId, Object> networkValues = IIDM2DB
                                .extractCimValues(network, new IIDM2DB.Config(network.getId(), true, true))
                                .getSingleValueMap();
                        if (printHeaders) {
                            List<String> headers = new ArrayList<>(networkValues.size());
                            for (HistoDbAttributeId attrId : networkValues.keySet()) {
                                headers.add(attrId.toString());
                            }/*w  w  w .jav a 2  s  .  c om*/
                            ArrayList<String> headersList = new ArrayList<>();
                            headersList.add("workflow");
                            headersList.add("state");
                            headersList.addAll(Arrays.asList(headers.toArray(new String[] {})));
                            csvWriter.writeHeader(headersList.toArray(new String[] {}));
                            printHeaders = false;
                        }
                        ArrayList<Object> valuesList = new ArrayList<>();
                        valuesList.add(workflowId);
                        valuesList.add(stateId);
                        valuesList.addAll(Arrays.asList(networkValues.values().toArray()));
                        csvWriter.write(valuesList.toArray());
                    }
                }
            } catch (IOException e) {
                LOGGER.error("Error serializing network data for workflow {}", workflowId);
            }
        }
        try {
            Files.copy(csvFile, file, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    } else
        LOGGER.error("No stored states for workflow {}", workflowId);
}

From source file:client.welcome2.java

private void SupplierAddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SupplierAddButtonActionPerformed
    int f = 0;//from w  w w. j  ava 2s. c  om
    int h = 0;
    sn = SupplierContracdIDText.getText();
    int ans;
    try {
        String sql = "Insert into suppliers (supplier_id,supplier_name,supplier_address,supplier_phone,supplier_email,supplier_contract_id) values(?,?,?,?,?,?)";

        pst = conn.prepareStatement(sql);
        pst.setString(1, SupplierIDText.getText());
        pst.setString(2, SupplierNameText.getText());
        pst.setString(3, SupplierAddressText.getText());
        pst.setString(4, SupplierPhoneText.getText());
        pst.setString(5, SupplierEmailText.getText());
        pst.setString(6, SupplierContracdIDText.getText());

        if (SupplierUploadText.getText().isEmpty()) {
            ans = JOptionPane.showConfirmDialog(null,
                    "Are You Sure You Want To Add a Supplier Without a Contract?", "Warning!",
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (ans == 0)
                pst.execute();
            if (ans == 1) {
            }
        }

        else {

            Path dest = Paths.get("src/SupplierContracts/" + sn + ".pdf");
            Path source = Paths.get(filename_supplier);
            Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);
            pst.execute();
        }

        JOptionPane.showMessageDialog(null, "Supplier Has Been Added");
    } catch (Exception e) {
        h = 1;

        if (SupplierIDText.getText().isEmpty())
            SupplierIDText.setBackground(Color.red);
        else
            SupplierIDText.setBackground(Color.white);

        if (SupplierNameText.getText().isEmpty())
            SupplierNameText.setBackground(Color.red);
        else
            SupplierNameText.setBackground(Color.white);

        if (SupplierAddressText.getText().isEmpty())
            SupplierAddressText.setBackground(Color.red);
        else
            SupplierAddressText.setBackground(Color.white);

        if (SupplierPhoneText.getText().isEmpty())
            SupplierPhoneText.setBackground(Color.red);
        else
            SupplierPhoneText.setBackground(Color.white);

        if (SupplierEmailText.getText().isEmpty())
            SupplierEmailText.setBackground(Color.red);
        else
            SupplierEmailText.setBackground(Color.white);

        if (SupplierContracdIDText.getText().isEmpty())
            SupplierContracdIDText.setBackground(Color.red);
        else
            SupplierContracdIDText.setBackground(Color.white);

        if (f != 2) {
            JOptionPane.showMessageDialog(null, "The Marked Fields Are Empty\n Please Fill All Fields",
                    "Attention!", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(null, e);
        }
    }
    if (f == 0 && h == 0) {
        SupplierIDText.setText("");
        SupplierNameText.setText("");
        SupplierAddressText.setText("");
        SupplierPhoneText.setText("");
        SupplierEmailText.setText("");
        SupplierContracdIDText.setText("");
        SupplierUploadText.setText("");
    }
}

From source file:gov.osti.services.Metadata.java

/**
 * Store a File to a specific directory location. All files associated with
 * a CODEID are stored in the same folder.
 *
 * @param in the InputStream containing the file content
 * @param codeId the CODE ID associated with this file content
 * @param fileName the base file name of the file
 * @param basePath the base path destination for the file content
 * @return the absolute filesystem path to the file
 * @throws IOException on IO errors/*  ww  w.  j a v a2s.  c  o m*/
 */
private static String writeFile(InputStream in, Long codeId, String fileName, String basePath)
        throws IOException {
    // store this file in a designated base path
    java.nio.file.Path destination = Paths.get(basePath, String.valueOf(codeId), fileName);
    // make intervening folders if needed
    Files.createDirectories(destination.getParent());
    // save it (CLOBBER existing, if one there)
    Files.copy(in, destination, StandardCopyOption.REPLACE_EXISTING);

    return destination.toString();
}

From source file:client.welcome2.java

private void SupplierUpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SupplierUpdateButtonActionPerformed

    fn = SupplierContractIDText1.getText();

    try {//  w w  w .  j  a v  a 2 s .com

        String sn = SupplierNameText1.getText();
        String sa = SupplierAddressText1.getText();
        String sp = SupplierPhoneText1.getText();
        String se = SupplierEmailText1.getText();
        String sc = SupplierContractIDText1.getText();

        String sql = "update suppliers set supplier_name='" + sn + "',supplier_address='" + sa
                + "',supplier_phone='" + sp + "',supplier_email='" + se + "',supplier_contract_id='" + sc
                + "' where supplier_id='" + tableClick + "'";
        pst = conn.prepareStatement(sql);
        pst.execute();
        JOptionPane.showMessageDialog(null, "Supplier Details Updated");
        update_Supplier_table();
    }

    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }

    try {

        if (!SupplierUploadText1.getText().isEmpty()) {
            Path dest = Paths
                    .get("C:/Users/Felix/Documents/NetBeansProjects/Yatzig/src/Contracts/" + fn + ".pdf");
            Path source = Paths.get(supplier_filename_update);
            Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING);

            SupplierNameText1.setText(" ");
            SupplierAddressText1.setText(" ");
            SupplierPhoneText1.setText(" ");
            SupplierEmailText1.setText(" ");
            SupplierContractIDText1.setText(" ");
            SupplierUploadText1.setText(" ");

        }

    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

From source file:edu.harvard.iq.dataverse.ingest.IngestServiceBean.java

public static void main(String[] args) {

    String file = args[0];//from   w w w  .j a v a 2 s  .  c o  m
    String type = args[1];

    if (file == null || type == null || "".equals(file) || "".equals(type)) {
        System.err.println("Usage: java edu.harvard.iq.dataverse.ingest.IngestServiceBean <file> <type>.");
        System.exit(1);
    }

    BufferedInputStream fileInputStream = null;

    try {
        fileInputStream = new BufferedInputStream(new FileInputStream(new File(file)));
    } catch (FileNotFoundException notfoundEx) {
        fileInputStream = null;
    }

    if (fileInputStream == null) {
        System.err.println("Could not open file " + file + ".");
        System.exit(1);
    }

    TabularDataFileReader ingestPlugin = getTabDataReaderByMimeType(type);

    if (ingestPlugin == null) {
        System.err.println("Could not locate an ingest plugin for type " + type + ".");
        System.exit(1);
    }

    TabularDataIngest tabDataIngest = null;

    try {
        tabDataIngest = ingestPlugin.read(fileInputStream, null);
    } catch (IOException ingestEx) {
        System.err.println("Caught an exception trying to ingest file " + file + ".");
        System.exit(1);
    }

    try {
        if (tabDataIngest != null) {
            File tabFile = tabDataIngest.getTabDelimitedFile();

            if (tabDataIngest.getDataTable() != null && tabFile != null && tabFile.exists()) {

                String tabFilename = FileUtil.replaceExtension(file, "tab");

                Files.copy(Paths.get(tabFile.getAbsolutePath()), Paths.get(tabFilename),
                        StandardCopyOption.REPLACE_EXISTING);

                DataTable dataTable = tabDataIngest.getDataTable();

                System.out.println("NVARS: " + dataTable.getVarQuantity());
                System.out.println("NOBS: " + dataTable.getCaseQuantity());
                System.out.println("UNF: " + dataTable.getUnf());

                for (int i = 0; i < dataTable.getVarQuantity(); i++) {
                    String vartype = "";

                    if (dataTable.getDataVariables().get(i).isIntervalContinuous()) {
                        vartype = "numeric-continuous";
                    } else {
                        if (dataTable.getDataVariables().get(i).isTypeNumeric()) {
                            vartype = "numeric-discrete";
                        } else {
                            vartype = "character";
                        }
                    }

                    System.out.print("VAR" + i + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getName() + " ");
                    System.out.print(vartype + " ");
                    System.out.print(dataTable.getDataVariables().get(i).getUnf());
                    System.out.println();

                }

            } else {
                System.err.println("Ingest failed to produce tab file or data table for file " + file + ".");
                System.exit(1);
            }
        } else {
            System.err.println("Ingest resulted in a null tabDataIngest object for file " + file + ".");
            System.exit(1);
        }
    } catch (IOException ex) {
        System.err.println("Caught an exception trying to save ingested data for file " + file + ".");
        System.exit(1);
    }

}

From source file:stainingestimation.StainingEstimation.java

/**
 * Saves the channel images of processed TMAspots. The user has to choose a
 * folder in which the images are stored. This does nothing if
 * color-deconvolution has not been performed, yet.
 *
 * @param whichImage The channel to be saves (SHOW_CHANNEL1_IMAGE,
 * SHOW_CHANNEL2_IMAGE or SHOW_CHANNEL3_IMAGE).
 *//*  w  ww. j av  a  2s.c om*/
public void saveChannelImages(int whichImage) {
    if (!processedTMAspots.isEmpty()) {
        // Let the user chose a folder
        File file = FileChooser.chooseSavingFolder(this, manager.getCurrentDir());

        if (file != null) {
            manager.setCurrentDir(file.getPath());
            for (TMAspot ts : processedTMAspots) {
                try {
                    Files.copy((new File(getImagename(ts, whichImage))).toPath(),
                            (new File(file.getPath() + File.separator + ts.getName() + "_"
                                    + Misc.FilePathStringtoFilename(getImagename(ts, whichImage)))).toPath(),
                            StandardCopyOption.REPLACE_EXISTING);
                } catch (Exception ex) {
                    if (tmarker.DEBUG > 0) {
                        Logger.getLogger(StainingEstimation.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
    }
}

From source file:rems.Global.java

public static void exprtToHTMLTblr(ResultSet dtst, String fileNm, String rptTitle, String[] colsToGrp,
        String[] colsToCnt, String[] colsToSum, String[] colsToAvrg, String[] colsToFrmt, boolean isfirst,
        boolean islast, boolean shdAppnd) {
    try {//from w ww .j av  a 2s . c  om
        System.out.println(fileNm);
        DecimalFormat myFormatter = new DecimalFormat("###,##0.00");
        DecimalFormat myFormatter2 = new DecimalFormat("###,##0");
        dtst.last();
        int totlRows = dtst.getRow();
        dtst.beforeFirst();
        ResultSetMetaData dtstmd = dtst.getMetaData();
        int colCnt = dtstmd.getColumnCount();
        long totlLen = 0;
        for (int d = 0; d < colCnt; d++) {
            totlLen += dtstmd.getColumnName(d + 1).length();
        }
        long[] colcntVals = new long[colCnt];
        double[] colsumVals = new double[colCnt];
        double[] colavrgVals = new double[colCnt];
        String cption = "";
        if (isfirst) {
            cption = "<caption align=\"top\">" + rptTitle + "</caption>";
            Global.strSB.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]><html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en-US\" xml:lang=\"en\"><head><meta http-equiv=\"Content-Type\" "
                    + "content=\"text/html; charset=utf-8\">" + System.getProperty("line.separator") + "<title>"
                    + rptTitle + "</title>" + System.getProperty("line.separator")
                    + "<link rel=\"stylesheet\" href=\"../amcharts/rpt.css\" type=\"text/css\"></head><body>");

            Files.copy(
                    new File(Global.getOrgImgsDrctry() + "/" + String.valueOf(Global.UsrsOrg_ID) + ".png")
                            .toPath(),
                    new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                            + String.valueOf(Global.UsrsOrg_ID) + ".png").toPath(),
                    StandardCopyOption.REPLACE_EXISTING);

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/images/" + String.valueOf(Global.UsrsOrg_ID) + ".png");
            }
            //Org Name
            String orgNm = Global.getOrgName(Global.UsrsOrg_ID);
            String pstl = Global.getOrgPstlAddrs(Global.UsrsOrg_ID);
            //Contacts Nos
            String cntcts = Global.getOrgContactNos(Global.UsrsOrg_ID);
            //Email Address
            String email = Global.getOrgEmailAddrs(Global.UsrsOrg_ID);

            Global.strSB
                    .append("<p><img src=\"../images/" + String.valueOf(Global.UsrsOrg_ID) + ".png\">" + orgNm
                            + "<br/>" + pstl + "<br/>" + cntcts + "<br/>" + email + "<br/>" + "</p>")
                    .append(System.getProperty("line.separator"));
        }

        Global.strSB.append("<table style=\"margin-top:5px;\">" + cption + "<thead>")
                .append(System.getProperty("line.separator"));

        int wdth = 0;
        String finalStr = " ";
        for (int d = 0; d < colCnt; d++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(d + 1).length();
            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
            if (colLen >= 3) {
                if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                    algn = "right";
                    finalStr = StringUtils.leftPad(dtstmd.getColumnName(d + 1).trim(), colLen, ' ');
                } else {
                    finalStr = dtstmd.getColumnName(d + 1).trim() + " ";
                }
                Global.strSB
                        .append("<th align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + finalStr.replace(" ", "&nbsp;") + "</th>")
                        .append(System.getProperty("line.separator"));
            }
        }

        Global.strSB.append("</thead><tbody>").append(System.getProperty("line.separator"));

        String[][] prevRowVal = new String[totlRows][colCnt];
        dtst.beforeFirst();
        System.out.println(Global.strSB.toString());
        for (int a = 0; a < totlRows; a++) {
            dtst.next();
            Global.strSB.append("<tr>").append(System.getProperty("line.separator"));
            for (int d = 0; d < colCnt; d++) {
                String algn = "left";
                double nwval = 0;
                boolean mstgrp = Global.mustColBeGrpd(String.valueOf(d), colsToGrp);
                if (Global.mustColBeCntd(String.valueOf(d), colsToCnt) == true) {
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colcntVals[d] += 1;
                        }
                    } else {
                        colcntVals[d] += 1;
                    }
                } else if (Global.mustColBeSumd(String.valueOf(d), colsToSum) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if ((prevRowVal[a - 1][d].equals(dtst.getString(d + 1)))) {

                        } else {
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colsumVals[d] += nwval;
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(d), colsToAvrg) == true) {
                    nwval = Double.parseDouble(dtst.getString(d + 1));
                    if ((a > 0) && (mstgrp == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {

                        } else {
                            colcntVals[d] += 1;
                            colsumVals[d] += nwval;
                        }
                    } else {
                        colcntVals[d] += 1;
                        colsumVals[d] += nwval;
                    }
                }

                int colLen = dtstmd.getColumnName(d + 1).length();
                if (colLen >= 3) {
                    if ((a > 0) && (Global.mustColBeGrpd(String.valueOf(d), colsToGrp) == true)) {
                        if (prevRowVal[a - 1][d].equals(dtst.getString(d + 1))) {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            Global.strSB
                                    .append("<td align=\"" + algn + "\"  width=\"" + wdth + "%\">"
                                            + " ".replace(" ", "&nbsp;") + "</td>")
                                    .append(System.getProperty("line.separator"));
                        } else {
                            wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                            String frsh = " ";
                            if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                                algn = "right";
                                double num = Double.parseDouble(dtst.getString(d + 1).trim());
                                if (!dtst.getString(d + 1).equals("")) {
                                    frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                                } else {
                                    frsh = dtst.getString(d + 1) + " ";
                                }
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                            Global.strSB.append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                    + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                            .replace(" ", "&nbsp;")
                                    + "</td>").append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                        }
                    } else {
                        wdth = (int) Math.round(((double) colLen / (double) totlLen) * 100);
                        String frsh = " ";
                        if (Global.mustColBeFrmtd(String.valueOf(d), colsToFrmt) == true) {
                            algn = "right";
                            double num = Double.parseDouble(dtst.getString(d + 1).trim());
                            if (!dtst.getString(d + 1).equals("")) {
                                frsh = myFormatter.format(num);//.Trim().PadRight(60, ' ')
                            } else {
                                frsh = dtst.getString(d + 1) + " ";
                            }
                        } else {
                            frsh = dtst.getString(d + 1) + " ";
                        }
                        Global.strSB
                                .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                        + Global.breakTxtDownHTML(frsh, dtstmd.getColumnName(d + 1).length())
                                                .replace(" ", "&nbsp;")
                                        + "</td>")
                                .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
                    }
                }
            }
            Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        }
        //Populate Counts/Sums/Averages
        Global.strSB.append("<tr>").append(System.getProperty("line.separator"));

        for (int f = 0; f < colCnt; f++) {
            String algn = "left";
            int colLen = dtstmd.getColumnName(f + 1).length();
            finalStr = " ";
            if (colLen >= 3) {
                if (Global.mustColBeCntd(String.valueOf(f), colsToCnt) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Count = " + myFormatter2.format(colcntVals[f]));
                    } else {
                        finalStr = ("Count = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeSumd(String.valueOf(f), colsToSum) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Sum = " + myFormatter.format(colsumVals[f]));
                    } else {
                        finalStr = ("Sum = " + String.valueOf(colcntVals[f]));
                    }
                } else if (Global.mustColBeAvrgd(String.valueOf(f), colsToAvrg) == true) {
                    if (Global.mustColBeFrmtd(String.valueOf(f), colsToFrmt) == true) {
                        algn = "right";
                        finalStr = ("Average = " + myFormatter.format(colsumVals[f] / colcntVals[f]));
                    } else {
                        finalStr = ("Average = " + String.valueOf(colsumVals[f] / colcntVals[f]));
                    }
                } else {
                    finalStr = " ";
                }
                Global.strSB
                        .append("<td align=\"" + algn + "\" width=\"" + wdth + "%\">"
                                + Global.breakTxtDownHTML(finalStr, dtstmd.getColumnName(f + 1).length())
                                        .replace(" ", "&nbsp;")
                                + "</td>")
                        .append(System.getProperty("line.separator"));//.replace(" ", "&nbsp;")
            }
        }
        Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
        Global.strSB.append("</tbody></table>").append(System.getProperty("line.separator"));
        if (islast) {
            Global.strSB.append("</body></html>");

            File file = new File(fileNm);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(Global.strSB.toString());
            bw.close();

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/samples/" + String.valueOf(Global.runID) + ".html");
            }
        }
    } catch (Exception ex) {
        System.out.println(ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n");
        Global.errorLog += ex.getMessage() + "\r\n\r\n" + Arrays.toString(ex.getStackTrace()) + "\r\n\r\n";
        Global.writeToLog();
    }
}

From source file:rems.Global.java

public static void exprtToHTMLDet(ResultSet recsdtst, ResultSet grpsdtst, String fileNm, String rptTitle,
        boolean isfirst, boolean islast, boolean shdAppnd, String orntnUsd, String imgCols) {
    try {/*from w w  w.j a v a2 s . co m*/
        imgCols = "," + StringUtils.strip(imgCols, ",") + ",";
        String cption = "";
        if (isfirst) {
            cption = "<caption align=\"top\">" + rptTitle + "</caption>";
            Global.strSB.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" "
                    + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"[]><html xmlns=\"http://www.w3.org/1999/xhtml\" dir=\"ltr\" lang=\"en-US\" xml:lang=\"en\"><head><meta http-equiv=\"Content-Type\" "
                    + "content=\"text/html; charset=utf-8\">" + System.getProperty("line.separator") + "<title>"
                    + rptTitle + "</title>" + System.getProperty("line.separator")
                    + "<link rel=\"stylesheet\" href=\"../amcharts/rpt.css\" type=\"text/css\"></head><body>");

            Files.copy(
                    new File(Global.getOrgImgsDrctry() + "/" + String.valueOf(Global.UsrsOrg_ID) + ".png")
                            .toPath(),
                    new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                            + String.valueOf(Global.UsrsOrg_ID) + ".png").toPath(),
                    StandardCopyOption.REPLACE_EXISTING);

            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/images/" + String.valueOf(Global.UsrsOrg_ID) + ".png");
            }
            //Org Name
            String orgNm = Global.getOrgName(Global.UsrsOrg_ID);
            String pstl = Global.getOrgPstlAddrs(Global.UsrsOrg_ID);
            //Contacts Nos
            String cntcts = Global.getOrgContactNos(Global.UsrsOrg_ID);
            //Email Address
            String email = Global.getOrgEmailAddrs(Global.UsrsOrg_ID);
            Global.strSB
                    .append("<p><img src=\"../images/" + String.valueOf(Global.UsrsOrg_ID) + ".png\">" + orgNm
                            + "<br/>" + pstl + "<br/>" + cntcts + "<br/>" + email + "<br/>" + "</p>")
                    .append(System.getProperty("line.separator"));
        }

        int fullPgWdthVal = 800;
        if (orntnUsd.equals("Portrait")) {
            fullPgWdthVal = 700;
        }

        int wdth = 0;
        String finalStr = " ";
        String algn = "left";
        String[] rptGrpVals = { "Group Title", "Group Page Width Type", "Group Min-Height", "Show Group Border",
                "Group Display Type", "No of Vertical Divs In Group", "Comma Separated Col Nos",
                "Data Label Max Width%", "Comma Separated Hdr Nms", "Column Delimiter", "Row Delimiter" };

        String grpTitle = "";
        String grpPgWdth = "";
        int grpMinHght = 0;
        String shwBrdr = "Show";
        String grpDsplyTyp = "Details";
        int grpColDvsns = 4;//Use 1 for Images others 2 or 4
        String colnums = "";
        String lblmaxwdthprcnt = "35";
        String tblrHdrs = "";
        String clmDlmtrs = "";
        String rwDlmtrs = "";

        int divwdth = 0;

        /* 1. For each detail group create a div and fieldset with legend & border based on group settings
         * 2a. if detail display then create required no of td in tr1 of a table, create new tr if no of columns is not exhausted
         *      i.e if no of vertical divs=4 no rows=math.ceil(no cols*0.5)/
         *      else no rows=no cols
         *      for each col display label and data if vrtcl divs is 2 or 4 else display only data
         * 2b. if tabular create table with headers according to defined headers
         *      split data according to rows and cols and display them in this table
         * 2. Get all column nos within the group and create their labels and data using settings
         * 3. if col nos is image then use full defined page width else create no of defined columns count
         * 4. if 
         * 
         */
        grpsdtst.last();
        recsdtst.last();
        int grpdtcnt = grpsdtst.getRow();
        int rowsdtcnt = recsdtst.getRow();
        grpsdtst.beforeFirst();
        recsdtst.beforeFirst();
        ResultSetMetaData recsdtstmd = recsdtst.getMetaData();
        ResultSetMetaData grpsdtstmd = grpsdtst.getMetaData();

        for (int a = 0; a < rowsdtcnt; a++) {
            recsdtst.next();
            Global.strSB.append("<table style=\"margin-top:5px;min-width:" + String.valueOf(fullPgWdthVal + 50)
                    + "px;\">" + cption + "<tbody>").append(System.getProperty("line.separator"));
            Global.strSB.append("<tr><td>").append(System.getProperty("line.separator"));
            for (int d = 0; d < grpdtcnt; d++) {
                grpsdtst.next();
                wdth = 35;
                grpTitle = grpsdtst.getString(1);
                grpPgWdth = grpsdtst.getString(2);
                grpMinHght = Integer.parseInt(grpsdtst.getString(3));
                shwBrdr = grpsdtst.getString(4);
                grpDsplyTyp = grpsdtst.getString(5);
                grpColDvsns = Integer.parseInt(grpsdtst.getString(6));//Use 1 for Images others 2 or 4
                colnums = grpsdtst.getString(7);
                lblmaxwdthprcnt = grpsdtst.getString(8);
                tblrHdrs = grpsdtst.getString(9);
                clmDlmtrs = grpsdtst.getString(10);
                rwDlmtrs = grpsdtst.getString(11);
                wdth = Integer.parseInt(lblmaxwdthprcnt);

                if (grpPgWdth.equals("Half Page Width")) {
                    divwdth = (int) (fullPgWdthVal / 2);
                } else {
                    divwdth = (int) (fullPgWdthVal / 1);
                }

                Global.strSB.append("<div style=\"float:left;min-width:" + String.valueOf(divwdth - 50)
                        + "px;padding:10px;\">").append(System.getProperty("line.separator"));//min-height:" + (grpMinHght + 20).ToString() + "px;
                if (shwBrdr.equals("Show")) {
                    Global.strSB
                            .append("<fieldset style=\"min-width:" + String.valueOf(divwdth - 80) + "px;\">")
                            .append(System.getProperty("line.separator"));//min-height:" + (grpMinHght).ToString() + "px;
                    Global.strSB.append("<legend>" + grpTitle + "</legend>")
                            .append(System.getProperty("line.separator"));
                }
                String w = "\\,";
                String[] colNumbers = colnums.split(w);
                int noofRws = 1;
                wdth = ((divwdth - 90) * wdth) / 100;
                if (grpDsplyTyp.equals("DETAIL")) {
                    if (grpColDvsns == 4) {
                        noofRws = (int) Math.ceil((double) colNumbers.length / (double) 2);
                    } else {
                        noofRws = colNumbers.length;
                    }
                    Global.strSB
                            .append("<table style=\"min-width:" + String.valueOf(divwdth - 90)
                                    + "px;margin-top:5px;border:none;\" border=\"0\"><tbody>")
                            .append(System.getProperty("line.separator"));
                    if (grpColDvsns == 4) {
                        for (int h = 0; h < colNumbers.length; h++) {
                            if ((h % 2) == 0) {
                                Global.strSB.append("<tr>").append(System.getProperty("line.separator"));
                            }
                            int clnm = -1;
                            clnm = Integer.parseInt(colNumbers[h]);
                            if (clnm >= 0) {
                                String frsh = "";
                                Global.strSB.append(
                                        "<td style=\"border-bottom:none;border-left:none;font-weight:bolder;\" align=\""
                                                + algn + "\" width=\"" + wdth + "px\">")
                                        .append(System.getProperty("line.separator"));
                                frsh = recsdtstmd.getColumnName(clnm + 1).trim() + ": ";
                                Global.strSB.append(
                                        Global.breakTxtDownHTML(frsh, (wdth / 7)).replace(" ", "&nbsp;"));
                                Global.strSB.append("</td>").append(System.getProperty("line.separator"));

                                Global.strSB
                                        .append("<td style=\"border-bottom:none;border-left:none;\" align=\""
                                                + algn + "\" width=\"" + (divwdth - 90 - wdth) + "px\">")
                                        .append(System.getProperty("line.separator"));
                                if (imgCols.contains("," + clnm + ",")) {
                                    frsh = recsdtst.getString(clnm + 1).trim();
                                    File file = new File(Global.dataBasDir + frsh);
                                    // if file doesnt exists, then create it
                                    if (!file.exists()) {
                                        String extnsn = FilenameUtils.getExtension(Global.dataBasDir + frsh);

                                        Files.copy(new File(Global.dataBasDir + frsh).toPath(),
                                                new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn).toPath(),
                                                StandardCopyOption.REPLACE_EXISTING);

                                        Global.strSB
                                                .append("<p><img src=\"../images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn
                                                        + "\" style=\"width:auto;height::" + grpMinHght
                                                        + "px;\">" + "</p>")
                                                .append(System.getProperty("line.separator"));
                                    }
                                } else {
                                    frsh = recsdtst.getString(clnm + 1).trim() + " ";
                                    Global.strSB
                                            .append(Global.breakTxtDownHTML(frsh, ((divwdth - 90 - wdth) / 7))
                                                    .replace(" ", "&nbsp;"));
                                }
                                Global.strSB.append("</td>").append(System.getProperty("line.separator"));
                            }

                            if ((h % 2) == 1) {
                                Global.strSB.append("</tr>").append(System.getProperty("line.separator"));
                            }

                        }

                    } else if (grpColDvsns == 2) {
                        for (int h = 0; h < colNumbers.length; h++) {
                            Global.strSB.append("<tr>").append(System.getProperty("line.separator"));
                            int clnm = -1;
                            clnm = Integer.parseInt(colNumbers[h]);
                            if (clnm >= 0) {
                                String frsh = "";
                                Global.strSB.append(
                                        "<td style=\"border-bottom:none;border-left:none;font-weight:bold;\" align=\""
                                                + algn + "\" width=\"" + wdth + "px\">")
                                        .append(System.getProperty("line.separator"));
                                frsh = recsdtstmd.getColumnName(clnm + 1).trim() + ": ";
                                Global.strSB.append(
                                        Global.breakTxtDownHTML(frsh, ((wdth) / 7)).replace(" ", "&nbsp;"));
                                Global.strSB.append("</td>").append(System.getProperty("line.separator"));

                                Global.strSB
                                        .append("<td style=\"border-bottom:none;border-left:none;\" align=\""
                                                + algn + "\" width=\"" + (divwdth - 90 - wdth) + "px\">")
                                        .append(System.getProperty("line.separator"));
                                if (imgCols.contains("," + clnm + ",")) {
                                    frsh = recsdtst.getString(clnm + 1).trim();
                                    File file = new File(Global.dataBasDir + frsh);
                                    // if file doesnt exists, then create it
                                    if (!file.exists()) {
                                        String extnsn = FilenameUtils.getExtension(Global.dataBasDir + frsh);

                                        Files.copy(new File(Global.dataBasDir + frsh).toPath(),
                                                new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn).toPath(),
                                                StandardCopyOption.REPLACE_EXISTING);

                                        Global.strSB
                                                .append("<p><img src=\"../images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn
                                                        + "\" style=\"width:auto;height:" + grpMinHght
                                                        + "px;\">" + "</p>")
                                                .append(System.getProperty("line.separator"));
                                    }
                                } else {
                                    frsh = recsdtst.getString(clnm + 1).trim() + " ";
                                    Global.strSB
                                            .append(Global.breakTxtDownHTML(frsh, ((divwdth - 90 - wdth) / 7))
                                                    .replace(" ", "&nbsp;"));
                                }
                                Global.strSB.append("</td>");
                            }
                            Global.strSB.append("</tr>");
                        }
                    } else if (grpColDvsns == 1) {
                        for (int h = 0; h < colNumbers.length; h++) {
                            Global.strSB.append("<tr>");
                            int clnm = -1;
                            clnm = Integer.parseInt(colNumbers[h]);
                            if (clnm >= 0) {
                                String frsh = "";
                                Global.strSB
                                        .append("<td style=\"border-bottom:none;border-left:none;\" align=\""
                                                + algn + "\" width=\"" + (divwdth - 90) + "px\">")
                                        .append(System.getProperty("line.separator"));
                                if (imgCols.contains("," + clnm + ",")) {
                                    frsh = recsdtst.getString(clnm + 1).trim();
                                    File file = new File(Global.dataBasDir + frsh);
                                    // if file doesnt exists, then create it
                                    if (!file.exists()) {
                                        String extnsn = FilenameUtils.getExtension(Global.dataBasDir + frsh);

                                        Files.copy(new File(Global.dataBasDir + frsh).toPath(),
                                                new File(Global.getRptDrctry() + "/amcharts_2100/images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn).toPath(),
                                                StandardCopyOption.REPLACE_EXISTING);

                                        Global.strSB
                                                .append("<p><img src=\"../images/"
                                                        + String.valueOf(Global.runID) + "_" + String.valueOf(a)
                                                        + String.valueOf(clnm) + extnsn
                                                        + "\" style=\"width:auto;height:" + grpMinHght
                                                        + "px;\">" + "</p>")
                                                .append(System.getProperty("line.separator"));
                                    }
                                } else {
                                    frsh = recsdtst.getString(clnm + 1).trim() + " ";
                                    Global.strSB.append(Global.breakTxtDownHTML(frsh, ((divwdth - 90) / 7))
                                            .replace(" ", "&nbsp;"));
                                }
                                Global.strSB.append("</td>");
                            }
                            Global.strSB.append("</tr>");

                        }
                    }

                    Global.strSB.append("</tbody></table>");

                } else {
                }
                if (shwBrdr.equals("Show")) {
                    Global.strSB.append("</fieldset>");
                }

                Global.strSB.append("</div>");
            }
            Global.strSB.append("</td></tr>");
            Global.strSB.append("</tbody></table><br/><br/>").append(System.getProperty("line.separator"));
        }

        if (islast) {
            Global.strSB.append("</body></html>");

            File file = new File(fileNm);
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(Global.strSB.toString());
            bw.close();
            if (Global.callngAppType.equals("DESKTOP")) {
                Global.upldImgsFTP(9, Global.getRptDrctry(),
                        "/amcharts_2100/samples/" + String.valueOf(Global.runID) + ".html");
            }
        }
    } catch (IOException ex) {
    } catch (SQLException ex) {
    } catch (NumberFormatException ex) {
    }
}