Example usage for java.io PrintWriter write

List of usage examples for java.io PrintWriter write

Introduction

In this page you can find the example usage for java.io PrintWriter write.

Prototype

public void write(String s) 

Source Link

Document

Writes a string.

Usage

From source file:org.ala.spatial.web.services.GDMWSController.java

private String generateParamfile(String[] layers, String layersPath, String useEuclidean, String speciesfile,
        String outputdir) {//www  . j  av a2 s  . com
    try {
        LayerDAO layerDao = Client.getLayerDao();
        StringBuilder envLayers = new StringBuilder();
        StringBuilder useEnvLayers = new StringBuilder();
        StringBuilder predSpline = new StringBuilder();
        for (int i = 0; i < layers.length; i++) {
            envLayers.append("EnvGrid").append(i + 1).append("=").append(layersPath).append(layers[i])
                    .append("\n");
            envLayers.append("EnvGridName").append(i + 1).append("=")
                    .append(layerDao.getLayerByName(layers[i]).getDisplayname()).append("\n");
            useEnvLayers.append("UseEnv").append(i + 1).append("=1").append("\n");
            predSpline.append("PredSpl").append(i + 1).append("=3").append("\n");
        }
        StringBuilder sbOut = new StringBuilder();
        sbOut.append("[GDMODEL]").append("\n").append("WorkspacePath=" + outputdir).append("\n")
                .append("RespDataType=RD_SitePlusSpecies").append("\n").append("PredDataType=ED_GridData")
                .append("\n").append("Quantiles=QUANTS_FromData").append("\n").append("UseEuclidean=0")
                .append("\n").append("UseSubSample=1").append("\n").append("NumSamples=10000").append("\n")
                .append("[RESPONSE]").append("\n").append("InputData=" + speciesfile).append("\n")
                .append("UseWeights=0").append("\n").append("[PREDICTORS]").append("\n") //.append("DomainGrid=/data/ala/runtime/output/gdm/test/domain").append("\n")
                .append("EuclSpl=3").append("\n").append("NumPredictors=" + layers.length).append("\n")
                .append(envLayers).append("\n").append(useEnvLayers).append("\n").append(predSpline)
                .append("\n");
        //File fDir = new File(outputdir);
        //fDir.mkdir();
        //File spFile = File.createTempFile("params_", ".csv", fDir);
        PrintWriter spWriter = new PrintWriter(
                new BufferedWriter(new FileWriter(outputdir + "gdm_params.txt")));
        spWriter.write(sbOut.toString());
        spWriter.close();
        //return spFile.getAbsolutePath();
        return outputdir + "gdm_params.txt";
    } catch (IOException ex) {
        Logger.getLogger(GDMWSController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:AnalysisModule.DataAnalysis.java

public void simulateBitmapAnalyse(List<Scenario> lstScenario) throws Exception {
    Double valor;/*from   w w  w .j  av a  2  s.  co m*/

    bitmapAnalyse(lstScenario);
    for (Scenario scenario : lstScenario) {
        for (Topology topology : scenario.lstTopology) {
            File table = new File(topology.getSaidasDir() + "Resumo.csv");
            FileWriter fw = new FileWriter(table);
            PrintWriter pw = new PrintWriter(fw);
            pw.write(";Instancia 1;Instancia 2;Instancia 3;Instancia 4\n");
            pw.write("Tipo;BITMAP;BITMAP;BITMAP;COUNTER\n");
            pw.write("Size(KB);");
            for (Instance instance : topology.getLstInstance()) {
                pw.write(String.format("%6.2f", (instance.getBitMapSize() / 8.0) / 1024.0) + ";");
            }
            pw.write("\n");
            pw.write("Treshold;0,1;0,3;0,5;-\n");
            pw.write("RMSE;");
            for (Instance instance : topology.getLstInstance()) {
                double error = 0;
                int counter = 0;
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        error += Math.pow(topology.getTrafficMatrix()[i][j] - instance.trafficMatrix[i][j], 2);
                        counter++;
                    }
                }
                error = Math.sqrt(error / counter);
                System.out.println("RMSE: " + error);
                pw.write(String.format("%10.8f", error) + ";");
            }
            pw.write("\n");
            pw.write("RMSRE;");
            for (Instance instance : topology.getLstInstance()) {
                double error = 0;
                int counter = 0;
                double T = 0;
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        if (instance.trafficMatrix[i][j] > T) {
                            error += Math.pow((topology.getTrafficMatrix()[i][j] - instance.trafficMatrix[i][j])
                                    / instance.trafficMatrix[i][j], 2);
                            counter++;
                        }
                    }
                }
                error = Math.sqrt(error / counter);
                System.out.println("RMSRE: " + error);
                pw.write(String.format("%10.8f", error) + ";");
            }
            pw.write("\n");
            pw.write("Observers;");
            for (Instance instance : topology.getLstInstance()) {
                int nbSw = 0;
                for (Switch sw : instance.networkSwitch.values()) {
                    if (sw.isObserver) {
                        nbSw++;
                    }
                }
                pw.write(nbSw + ";");
            }
            pw.write("\n");
            pw.write("RelNbSw;");
            for (Instance instance : topology.getLstInstance()) {
                int nbSw = 0;
                for (Switch sw : instance.networkSwitch.values()) {
                    if (sw.isObserver) {
                        nbSw++;
                    }
                }
                pw.write(String.format("%4.2f", 100.0 * (float) nbSw / (float) topology.getNumberOfSwitches())
                        + ";");
            }
            pw.write("\n");
            pw.close();
            fw.close();
            for (Instance instance : topology.getLstInstance()) {
                HashMap<Double, List<HashMap<Integer, Integer>>> orderMap = new HashMap<>();
                File bmpFile = new File(
                        topology.getSaidasDir() + "SimulacaoInstancia" + instance.getId() + ".csv");
                if (!bmpFile.exists()) {
                    bmpFile.createNewFile();
                }
                FileWriter fout = new FileWriter(bmpFile);
                PrintWriter oos = new PrintWriter(fout);
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    oos.print(";Router " + (i + 1));
                }
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    oos.println();
                    oos.print("Router " + (i + 1));
                    for (int j = 0; j < topology.getNumberOfSwitches(); j++) {
                        int sourceId = i;
                        int destinationId = j;
                        if (sourceId > topology.getNumberOfSwitches()
                                || destinationId > topology.getNumberOfSwitches()) {
                            System.out.println("Erro no nmero de switches");
                            throw new Exception("Erro no nmero de switches");
                        } else {
                            doPrintElement(oos, i, j, instance.trafficMatrix[i][j]);

                            //                                if (i < j) {
                            //                                    if (orderMap.containsKey(instance.trafficMatrix[i][j])) {
                            //
                            //                                        HashMap<Integer, Integer> mapNodes = new HashMap<>();
                            //                                        mapNodes.put(i + 1, j + 1);
                            //                                        orderMap.get(instance.trafficMatrix[i][j]).add(mapNodes);
                            //                                    } else {
                            //                                        LinkedList listaHashMap = new LinkedList();
                            //                                        HashMap<Integer, Integer> mapNodes = new HashMap<>();
                            //                                        mapNodes.put(i + 1, j + 1);
                            //                                        listaHashMap.add(mapNodes);
                            //                                        orderMap.put(instance.trafficMatrix[i][j], listaHashMap);
                            //                                    }
                            //                                }
                        }
                    }
                }
                oos.close();
                fout.close();

                //                    Map<Double, List<HashMap<Integer, Integer>>> map = new TreeMap<>(orderMap);
                //                    System.out.println("Instancia" + instance.getId() + " After Sorting:");
                //                    Set set2 = map.entrySet();
                //                    Iterator iterator2 = set2.iterator();
                //                    while (iterator2.hasNext()) {
                //                        Map.Entry me2 = (Map.Entry) iterator2.next();
                //                        System.out.print(me2.getKey() + ": ");
                //                        System.out.println(me2.getValue());
                //                    }
                // Plot Graf
                XYSeries matrix = new XYSeries("Matrix", false, true);
                for (int i = 0; i < topology.getNumberOfSwitches(); i++) {
                    for (int j = i + 1; j < topology.getNumberOfSwitches(); j++) {
                        matrix.add((double) topology.getTrafficMatrix()[i][j], instance.trafficMatrix[i][j]);
                    }
                }
                double maxPlot = Double.max(matrix.getMaxX(), matrix.getMaxY()) * 1.1;
                XYSeries middle = new XYSeries("Real");
                middle.add(0, 0);
                middle.add(maxPlot, maxPlot);
                XYSeries max = new XYSeries("Max");
                max.add(0, 0);
                max.add(maxPlot, maxPlot * 1.2);
                XYSeries min = new XYSeries("Min");
                min.add(0, 0);
                min.add(maxPlot, maxPlot * 0.8);

                XYSeriesCollection dataset = new XYSeriesCollection();
                dataset.addSeries(middle);
                dataset.addSeries(matrix);
                dataset.addSeries(max);
                dataset.addSeries(min);
                JFreeChart chart = ChartFactory.createXYLineChart("Matriz de Trfego", "Real", "Estimado",
                        dataset);
                chart.setBackgroundPaint(new ChartColor(255, 255, 255));

                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
                renderer.setSeriesLinesVisible(1, false);
                renderer.setSeriesShapesVisible(1, true);

                int width = 640 * 2; /* Width of the image */

                int height = 480 * 2; /* Height of the image */

                File XYChart = new File(
                        topology.getSaidasDir() + "SimulacaoInstancia" + instance.getId() + ".jpeg");
                ChartUtilities.saveChartAsJPEG(XYChart, chart, width, height);
            }
        }
    }
}

From source file:csg.files.CSGFiles.java

public void saveScheduleData(AppDataComponent schData, String filePath) throws IOException {
    ScheduleData schDataManager = (ScheduleData) schData;
    JsonArrayBuilder schArrayBuilder = Json.createArrayBuilder();
    ObservableList<ScheduleItem> schedule = schDataManager.getSchedule();

    ArrayList<ScheduleItem> holidays = new ArrayList();
    ArrayList<ScheduleItem> lectures = new ArrayList();
    ArrayList<ScheduleItem> references = new ArrayList();
    ArrayList<ScheduleItem> recitations = new ArrayList();
    ArrayList<ScheduleItem> hws = new ArrayList();

    for (int i = 0; i < schedule.size(); i++) {
        if (schedule.get(i).getType().equals("holiday")) {
            holidays.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("lecture")) {
            lectures.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("reference")) {
            references.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("recitation")) {
            recitations.add(schedule.get(i));
        } else if (schedule.get(i).getType().equals("hw")) {
            hws.add(schedule.get(i));/*from   www .j  a  v  a  2s  .  c  o m*/
        }
    }

    JsonArrayBuilder holidayArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : holidays) {
        JsonObject holidayJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_LINK, scheduleItem.getLink()).build();
        holidayArrayBuilder.add(holidayJson);
    }
    JsonArray holidayArray = holidayArrayBuilder.build();

    JsonArrayBuilder lectureArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : lectures) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink()).build();
        lectureArrayBuilder.add(lecJson);
    }
    JsonArray lectureArray = lectureArrayBuilder.build();

    JsonArrayBuilder referencesArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : references) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink()).build();
        referencesArrayBuilder.add(lecJson);
    }
    JsonArray referenceArray = referencesArrayBuilder.build();

    JsonArrayBuilder recitationArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : recitations) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).build();
        recitationArrayBuilder.add(lecJson);
    }
    JsonArray recitaitonArray = recitationArrayBuilder.build();

    JsonArrayBuilder hwArrayBuilder = Json.createArrayBuilder();
    for (ScheduleItem scheduleItem : hws) {
        JsonObject lecJson = Json.createObjectBuilder().add(JSON_MONTH, scheduleItem.getDateMon())
                .add(JSON_DAY, scheduleItem.getDateDay()).add(JSON_TITLE, scheduleItem.getTitle())
                .add(JSON_TOPIC, scheduleItem.getTopic()).add(JSON_LINK, scheduleItem.getLink())
                .add(JSON_TIME, scheduleItem.getTime()).add(JSON_CRITERIA, scheduleItem.getCriteria()).build();
        hwArrayBuilder.add(lecJson);
    }
    JsonArray hwArray = hwArrayBuilder.build();

    JsonObject dataManagerJSO = Json.createObjectBuilder().add(JSON_MONDAYMON, workspace.getMonMonthDate())
            .add(JSON_MONDAYDAY, workspace.getMonDayDate()).add(JSON_FRIDAYMONTH, workspace.getFriMonthDate())
            .add(JSON_FRIDAYDAY, workspace.getFriDayDate()).add(JSON_HOLIDAYS, holidayArray)
            .add(JSON_LECTURES, lectureArray).add(JSON_REF, referenceArray)
            .add(JSON_RECITATION, recitaitonArray).add(JSON_HW, hwArray).build();

    // AND NOW OUTPUT IT TO A JSON FILE WITH PRETTY PRINTING
    Map<String, Object> properties = new HashMap<>(1);
    properties.put(JsonGenerator.PRETTY_PRINTING, true);
    JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
    StringWriter sw = new StringWriter();
    JsonWriter jsonWriter = writerFactory.createWriter(sw);
    jsonWriter.writeObject(dataManagerJSO);
    jsonWriter.close();

    // INIT THE WRITER
    OutputStream os = new FileOutputStream(filePath);
    JsonWriter jsonFileWriter = Json.createWriter(os);
    jsonFileWriter.writeObject(dataManagerJSO);
    String prettyPrinted = sw.toString();
    PrintWriter pw = new PrintWriter(filePath);
    pw.write(prettyPrinted);
    pw.close();
}

From source file:com.sshdemo.common.report.manage.web.RepositoryAction.java

public void download() {
    PrintWriter pw = null;
    InputStream in = null;/*from w  w  w . java  2 s. c  om*/
    try {
        if (getRepositoryId() != null) {
            Repository repository = reportFac.findRepositoryById(getRepositoryId());
            String type = repository.getType();
            byte[] bytes = repository.getEntity();

            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentLength(bytes.length);

            if (type.toLowerCase().equals("pdf")) {
                response.setContentType("application/pdf");
            } else if (type.toLowerCase().equals("png")) {
                response.setContentType("image/png");
            }

            pw = response.getWriter();
            in = new ByteArrayInputStream(bytes);
            int len = 0;
            while ((len = in.read()) > -1) {
                pw.write(len);
            }
            pw.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (pw != null) {
            try {
                pw.close();
                pw = null;
            } catch (Exception e) {
            }
        }
        if (in != null) {
            try {
                in.close();
                in = null;
            } catch (Exception e) {
            }
        }
    }
}

From source file:abelymiguel.miralaprima.SetMoza.java

/**
 * Processes requests for both HTTP//from   w w  w  .  j a v  a  2  s  . com
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();
    } catch (URISyntaxException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("text/javascript;charset=UTF-8");

    String url_moza;
    url_moza = request.getParameter("url_moza");

    String country_code;
    country_code = request.getParameter("country_code");

    if (country_code == null) {
        country_code = "ALL";
    }

    JSONObject jsonObject;
    String json_str;

    jsonObject = new JSONObject(this.setMozaInDB(url_moza, country_code));
    json_str = jsonObject.toString();

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }
    try {
        _con.close();
        _stmt.close();
    } catch (SQLException ex) {
        Logger.getLogger(SetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:edu.cornell.med.icb.goby.modes.FalseDiscoveryRateMode.java

private void combineTSV(String[] inputFiles, DifferentialExpressionResults data,
        DifferentialExpressionCalculator deCalculator, ObjectList<String> columnIdList, Writer out)
        throws IOException {

    PrintWriter printer = new PrintWriter(out);
    int elementIndex = 0;
    // write the TSV header first:

    boolean first = true;
    for (String column : columnIdList) {
        if (!first) {
            printer.write('\t');
        }/* ww w.ja v a 2 s .  co  m*/
        printer.print(column);
        first = false;
    }

    for (String column : adjustedColumnIds) {
        if (!first) {
            printer.write('\t');
        }
        printer.print(column);
        first = false;

    }
    printer.println();
    // end of TSV header generation

    for (String filename : inputFiles) {
        System.out.printf("Writing combined output (processing %s)%n", filename);
        TSVReader reader = new TSVReader(new FileReader(filename), '\t');

        try {
            String firstColumn = columnIdList.get(0);
            reader.setCommentPrefix(firstColumn);

            int columnIndex = 0;
            IntSet doubleColumnIndices = new IntArraySet();

            for (String column : columnIdList) {
                for (String selectedColumn : selectedPValueColumns) {
                    if (column.equalsIgnoreCase(selectedColumn)) {

                        final String statName = column.toLowerCase();

                        if (!data.isStatisticDefined(new MutableString(statName))) {
                            data.declareStatistic(statName);
                        }
                        doubleColumnIndices.add(columnIndex);
                    }
                }
                columnIndex++;
            }

            while (reader.hasNext()) {
                first = true;
                if (!reader.isCommentLine()) {
                    reader.next();
                    final String elementId = Integer.toString(elementIndex);
                    boolean keepThisLine = doubleColumnIndices.isEmpty();
                    if (elementPermutation.containsKey(elementIndex)) {
                        final int permutedIndex = elementPermutation.get(elementIndex);
                        final DifferentialExpressionInfo differentialExpressionInfo = data.get(permutedIndex);
                        assert Integer.parseInt(differentialExpressionInfo.getElementId()
                                .toString()) == elementIndex : " element index must match with data element retrived";
                        {
                            final DoubleArrayList list = differentialExpressionInfo.statistics();

                            for (final String adjustedColumn : adjustedColumnIds) {
                                final int adjustedColumnIndex = data.getStatisticIndex(adjustedColumn);

                                final double adjustedPValue = list.get(adjustedColumnIndex);
                                keepThisLine = determineKeepThisLine(keepThisLine, adjustedPValue);
                            }
                            if (topHitNum != 0 && topHitsElementIndices.isEmpty()) {
                                // early stop: there are no q-values below the threshold and we have seen enough top hits already.
                                break;
                            }
                            if (topHitNum != 0 && topHitsElementIndices.contains(elementIndex)) {
                                // the q-value is not good enough for the threshold, but we want to include up to top hits in the results:
                                keepThisLine = true;
                                topHitsElementIndices.remove(elementIndex);
                            }
                        }
                        if (!keepThisLine) {
                            //     System.out.println("skipping elementId since the adjusted P-values do not make the q-value threshold." + elementId);
                        }
                        if (keepThisLine) {
                            int index = 0;
                            final DifferentialExpressionInfo info = differentialExpressionInfo;
                            assert info.getElementId().equals(elementId) : " elementId must match";
                            first = true;
                            for (int j = 0; j < reader.numTokens(); j++) {
                                if (doubleColumnIndices.contains(j)) {
                                    reader.getString();
                                    if (!first) {
                                        printer.write('\t');
                                    }
                                    printer.print(info.statistics().get(index));
                                    first = false;
                                    index++;
                                } else {
                                    if (!first) {
                                        printer.write('\t');
                                    }
                                    printer.print(reader.getString());
                                    first = false;
                                }
                            }
                            first = false;
                            for (final String adjustedColumn : adjustedColumnIds) {
                                final int adjustedColumnIndex = data.getStatisticIndex(adjustedColumn);
                                final DoubleArrayList list = differentialExpressionInfo.statistics();
                                if (!first) {
                                    printer.write('\t');
                                }
                                printer.print(list.get(adjustedColumnIndex));
                                first = false;
                            }
                            printer.printf("%n");
                        }
                    }
                    elementIndex++;

                } else {
                    reader.skip();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        } finally {
            reader.close();
        }
    }

    printer.flush();
}

From source file:abelymiguel.miralaprima.GetMoza.java

/**
 * Processes requests for both HTTP//  w ww. ja  va 2  s .c o m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html;charset=UTF-8");
    try {
        _con = Utils.getConnection();
        _stmt = _con.createStatement();
    } catch (URISyntaxException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }

    PrintWriter out = null;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(GetMoza.class.getName()).log(Level.SEVERE, null, ex);
    }
    response.setContentType("text/javascript;charset=UTF-8");

    String country_code;
    int limit;
    String limitStr;
    country_code = request.getParameter("country_code");
    limitStr = request.getParameter("limit");

    if (limitStr != null) {
        limit = Integer.parseInt(limitStr);
    } else {
        limit = -1;
    }

    String json_str;
    JSONArray jsonArray = new JSONArray(this.searchInDB(country_code, limit));
    json_str = jsonArray.toString();

    String jsonpCallback = request.getParameter("callback");
    if (jsonpCallback != null) {
        out.write(jsonpCallback + "(" + json_str + ")");
    } else {
        out.println(json_str);
    }

    try {
        _con.close();
        _stmt.close();
        _rs.close();
    } catch (SQLException ex) {
        Logger.getLogger(GetPrima.class.getName()).log(Level.SEVERE, null, ex);
    }
    out.close();
}

From source file:de.betterform.agent.web.filter.XSLTFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    ServletContext servletContext = filterConfig.getServletContext();

    /* TODO: clean up, styleFile is  never used */
    String stylePath = null;/*w  w w  . jav  a 2  s .  co  m*/
    try {
        stylePath = WebFactory.getRealPath(xsltPath, servletContext);
    } catch (XFormsConfigException e) {
        throw new ServletException(e);
    }
    File styleFile = new File(stylePath, xslFile);

    PrintWriter out = response.getWriter();
    CharResponseWrapper wrapper = new CharResponseWrapper((HttpServletResponse) response);
    try {
        URI uri = new File(WebFactory.getRealPath(xsltPath, servletContext)).toURI().resolve(new URI(xslFile));
        XSLTGenerator generator = WebFactory.setupTransformer(uri, servletContext);

        wrapper.setContentType("text/html");
        chain.doFilter(request, wrapper);

        StringReader sr = new StringReader(wrapper.toString());
        generator.setInput(sr);
        //            Source xmlSource = new StreamSource((Reader) sr);
        CharArrayWriter caw = new CharArrayWriter();
        generator.setOutput(caw);

        //            StreamResult result = new StreamResult(caw);
        //            transformer.transform(xmlSource, result);
        generator.generate();
        response.setContentLength(caw.toString().length());
        out.write(caw.toString());

    } catch (URISyntaxException e) {
        out.println(e.toString());
        out.write(wrapper.toString());
    } catch (XFormsException e) {
        out.println(e.toString());
        out.write(wrapper.toString());
    }
}

From source file:com.portfolio.data.attachment.FileServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // =====================================================================================
    initialize(request);//w w w .  j av a 2s .  com

    int userId = 0;
    int groupId = 0;
    String user = "";

    HttpSession session = request.getSession(true);
    if (session != null) {
        Integer val = (Integer) session.getAttribute("uid");
        if (val != null)
            userId = val;
        val = (Integer) session.getAttribute("gid");
        if (val != null)
            groupId = val;
        user = (String) session.getAttribute("user");
    }

    Credential credential = null;
    Connection c = null;
    try {
        //On initialise le dataProvider
        if (ds == null) // Case where we can't deploy context.xml
        {
            c = getConnection();
        } else {
            c = ds.getConnection();
        }
        dataProvider.setConnection(c);
        credential = new Credential(c);
    } catch (Exception e) {
        e.printStackTrace();
    }

    /// uuid: celui de la ressource

    /// /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]]

    String origin = request.getRequestURL().toString();

    /// Rcupration des paramtres
    String url = request.getPathInfo();
    String[] token = url.split("/");
    String uuid = token[1];

    String size = request.getParameter("size");
    if (size == null)
        size = "S";

    String lang = request.getParameter("lang");
    if (lang == null) {
        lang = "fr";
    }

    /// Vrification des droits d'accs
    if (!credential.hasNodeRight(userId, groupId, uuid, Credential.WRITE)) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit WRITE sur le noeud "+nodeUuid);
    }

    String data;
    String fileid = "";
    try {
        data = dataProvider.getResNode(uuid, userId, groupId);

        /// Parse les donnes
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputSource is = new InputSource(new StringReader("<node>" + data + "</node>"));
        Document doc = documentBuilder.parse(is);
        DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0");
        LSSerializer serial = impl.createLSSerializer();
        serial.getDomConfig().setParameter("xml-declaration", false);

        /// Cherche si on a dj envoy quelque chose
        XPath xPath = XPathFactory.newInstance().newXPath();
        String filterRes = "//filename[@lang=\"" + lang + "\"]";
        NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET);

        String filename = "";
        if (nodelist.getLength() > 0)
            filename = nodelist.item(0).getTextContent();

        if (!"".equals(filename)) {
            /// Already have one, per language
            String filterId = "//fileid[@lang='" + lang + "']";
            NodeList idlist = (NodeList) xPath.compile(filterId).evaluate(doc, XPathConstants.NODESET);
            if (idlist.getLength() != 0) {
                Element fileNode = (Element) idlist.item(0);
                fileid = fileNode.getTextContent();
            }
        }
    } catch (Exception e2) {
        e2.printStackTrace();
    }

    int last = fileid.lastIndexOf("/") + 1; // FIXME temp patch
    if (last < 0)
        last = 0;
    fileid = fileid.substring(last);
    /// request.getHeader("REFERRER");

    /// criture des donnes
    String urlTarget = "http://" + server + "/" + fileid;
    //      String urlTarget = "http://"+ server + "/user/" + user +"/file/" + uuid +"/"+ lang+ "/ptype/fs";

    // Unpack form, fetch binary data and send
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    /*
    ServletContext servletContext = this.getServletConfig().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);
    //*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    String json = "";
    HttpURLConnection connection = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(request);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if ("uploadfile".equals(item.getFieldName())) {
                // Send raw data
                InputStream inputData = item.getInputStream();

                /*
                URL urlConn = new URL(urlTarget);
                connection = (HttpURLConnection) urlConn.openConnection();
                connection.setDoOutput(true);
                connection.setUseCaches(false);                 /// We don't want to cache data
                connection.setInstanceFollowRedirects(false);   /// Let client follow any redirection
                String method = request.getMethod();
                connection.setRequestMethod(method);
                        
                String context = request.getContextPath();
                connection.setRequestProperty("app", context);
                //*/

                String fileName = item.getName();
                long filesize = item.getSize();
                String contentType = item.getContentType();

                //               /*
                connection = CreateConnection(urlTarget, request);
                connection.setRequestProperty("filename", uuid);
                connection.setRequestProperty("content-type", "application/octet-stream");
                connection.setRequestProperty("content-length", Long.toString(filesize));
                //*/
                connection.connect();

                OutputStream outputData = connection.getOutputStream();
                IOUtils.copy(inputData, outputData);

                /// Those 2 lines are needed, otherwise, no request sent
                int code = connection.getResponseCode();
                String msg = connection.getResponseMessage();

                InputStream objReturn = connection.getInputStream();
                StringWriter idResponse = new StringWriter();
                IOUtils.copy(objReturn, idResponse);
                fileid = idResponse.toString();

                connection.disconnect();

                /// Construct Json
                StringWriter StringOutput = new StringWriter();
                JsonWriter writer = new JsonWriter(StringOutput);
                writer.beginObject();
                writer.name("files");
                writer.beginArray();
                writer.beginObject();

                writer.name("name").value(fileName);
                writer.name("size").value(filesize);
                writer.name("type").value(contentType);
                writer.name("url").value(origin);
                writer.name("fileid").value(fileid);
                //                               writer.name("deleteUrl").value(ref);
                //                                       writer.name("deleteType").value("DELETE");
                writer.endObject();

                writer.endArray();
                writer.endObject();

                writer.close();

                json = StringOutput.toString();

                /*
                DataOutputStream datawriter = new DataOutputStream(connection.getOutputStream());
                byte[] buffer = new byte[1024];
                int dataSize;
                while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
                {
                   datawriter.write(buffer, 0, dataSize);
                }
                datawriter.flush();
                datawriter.close();
                //*/
                //               outputData.close();
                //               inputData.close();

                break;
            }
        }
    } catch (FileUploadException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    /*
    HttpURLConnection connection = CreateConnection( urlTarget, request );
            
    connection.setRequestProperty("referer", origin);
            
    /// Send post data
    ServletInputStream inputData = request.getInputStream();
    DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
            
    byte[] buffer = new byte[1024];
    int dataSize;
    while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 )
    {
       writer.write(buffer, 0, dataSize);
    }
    inputData.close();
    writer.close();
            
    /// So we can forward some Set-Cookie
    String ref = request.getHeader("referer");
            
    /// Prend le JSON du fileserver
    InputStream in = connection.getInputStream();
            
    InitAnswer(connection, response, ref);
            
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    StringBuilder builder = new StringBuilder();
    for( String line = null; (line = reader.readLine()) != null; )
       builder.append(line).append("\n");
    //*/

    /// Envoie la mise  jour au backend
    /*
    try
    {
       PostForm.updateResource(session.getId(), backend, uuid, lang, json);
    }
    catch( Exception e )
    {
       e.printStackTrace();
    }
    //*/

    connection.disconnect();
    /// Renvoie le JSON au client
    response.setContentType("application/json");
    PrintWriter respWriter = response.getWriter();
    respWriter.write(json);

    //      RetrieveAnswer(connection, response, ref);
    dataProvider.disconnect();
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

public void doPropfind(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    Unmarshaller unMarshaller = createUnmarshaller();
    Marshaller marshaller = createMarshaller();

    Propfind propfind = null;/*w ww  .  java  2  s.  com*/
    try {
        propfind = (Propfind) unMarshaller.unmarshal(req.getReader());
    } catch (JAXBException e) {
        throw new CalendarException("Unable to parse request", e);
    }
    if (LOGGER.isTraceEnabled()) {
        try {
            StringWriter writer = new StringWriter();
            marshaller.marshal(propfind, writer);
            LOGGER.trace("receive :\n{}", writer.toString());
        } catch (JAXBException e) {
            // ignore
        }
    }

    Prop reqProp = propfind.getProp();

    Multistatus multistatus = new Multistatus();
    int status = propFind(multistatus, reqProp, req.getHeader("Depth"), req.getRequestURI());
    if (status != HttpServletResponse.SC_OK) {
        resp.sendError(status);
        return;
    }

    resp.setStatus(SC_MULTI_STATUS);
    resp.setContentType("text/xml;charset=\"UTF-8\"");

    PrintWriter httpWriter = resp.getWriter();

    try {
        Writer writer;
        if (LOGGER.isTraceEnabled()) {
            writer = new StringWriter();
        } else {
            writer = httpWriter;
        }
        marshaller.marshal(multistatus, writer);
        if (LOGGER.isTraceEnabled()) {
            String string = writer.toString();
            LOGGER.trace("send :\n{}", string);
            httpWriter.write(string);
        }
    } catch (JAXBException e) {
        throw new CalendarException("Unable to format response", e);
    }
    httpWriter.close();
}