Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

In this page you can find the example usage for java.io OutputStreamWriter flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

private void connectAndSend(String xml) throws ServerException {

    HttpURLConnection conn = null;
    OutputStreamWriter wr = null;

    try {//from w  w w  .  j  av a2  s.c o m
        LOGGER.debug("{} - Url: {}", instanceName, urlstr);
        String payload = cmd + xml;
        conn = createHTTPConnection(payload);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payload);
        wr.flush();

        /*
         * Look for status != 0 by building a DOM to parse
         * <status>0</status> <message>OK</message>
         */

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGGER.error("{} - Could not get a doc builder", instanceName, e);
            return;
        }

        /*
         * Getting the value for status and message tags
         */
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NRDP return string - {}", convertStreamToString(is));
                is.reset();
            }

            Document doc = null;

            doc = dBuilder.parse(is);

            doc.getDocumentElement().normalize();
            String rootNode = doc.getDocumentElement().getNodeName();
            NodeList responselist = doc.getElementsByTagName(rootNode);
            String result = (String) ((Element) responselist.item(0)).getElementsByTagName("status").item(0)
                    .getChildNodes().item(0).getNodeValue().trim();

            LOGGER.debug("NRDP return status is: {}", result);

            if (!"0".equals(result)) {
                String message = (String) ((Element) responselist.item(0)).getElementsByTagName("message")
                        .item(0).getChildNodes().item(0).getNodeValue().trim();
                LOGGER.error("{} - nrdp returned message \"{}\" for xml: {}", instanceName, message, xml);
            }
        } catch (SAXException e) {
            LOGGER.error("{} - Could not parse response xml", instanceName, e);
        }

    } catch (IOException e) {
        LOGGER.error("{} - Network error - check nrdp server and that service is started", instanceName, e);
        throw new ServerException(e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException ignore) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.norconex.importer.Importer.java

private void parseDocument(ImporterDocument doc, List<ImporterDocument> embeddedDocs)
        throws IOException, ImporterException {

    IDocumentParserFactory factory = importerConfig.getParserFactory();
    IDocumentParser parser = factory.getParser(doc.getReference(), doc.getContentType());

    // No parser means no parsing, so we simply return
    if (parser == null) {
        return;/*from w  w w . ja va  2 s.  com*/
    }

    CachedOutputStream out = createOutputStream();
    OutputStreamWriter output = new OutputStreamWriter(out, CharEncoding.UTF_8);

    try {
        List<ImporterDocument> nestedDocs = parser.parseDocument(doc, output);
        output.flush();
        if (doc.getContentType() == null) {
            String ct = doc.getMetadata().getString(ImporterMetadata.DOC_CONTENT_TYPE);
            if (StringUtils.isNotBlank(ct)) {
                doc.setContentType(ContentType.valueOf(ct));
            }
        }
        if (StringUtils.isBlank(doc.getContentEncoding())) {
            doc.setContentEncoding(doc.getMetadata().getString(ImporterMetadata.DOC_CONTENT_ENCODING));
        }
        if (nestedDocs != null) {
            embeddedDocs.addAll(nestedDocs);
        }
    } catch (DocumentParserException e) {
        IOUtils.closeQuietly(out);
        if (importerConfig.getParseErrorsSaveDir() != null) {
            saveParseError(doc, e);
        }
        throw e;
    }

    if (out.isCacheEmpty()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Parser \"" + parser.getClass() + "\" did not produce new content for: "
                    + doc.getReference());
        }
        IOUtils.closeQuietly(out);
        doc.getContent().dispose();
        doc.setContent(streamFactory.newInputStream());
    } else {
        doc.getContent().dispose();
        CachedInputStream newInputStream = null;
        try {
            newInputStream = out.getInputStream();
        } finally {
            IOUtils.closeQuietly(out);
        }
        doc.setContent(newInputStream);
    }
}

From source file:org.bimserver.servlets.DownloadServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from   w ww.  j a  v  a 2  s  .c o m*/
        String acceptEncoding = request.getHeader("Accept-Encoding");
        boolean useGzip = false;
        if (acceptEncoding != null && acceptEncoding.contains("gzip")) {
            useGzip = true;
        }
        OutputStream outputStream = response.getOutputStream();
        boolean zip = request.getParameter("zip") != null && request.getParameter("zip").equals("on");
        if (useGzip && !zip) {
            response.setHeader("Content-Encoding", "gzip");
            outputStream = new GZIPOutputStream(response.getOutputStream());
        }
        String token = (String) request.getSession().getAttribute("token");

        if (token == null) {
            token = request.getParameter("token");
        }
        long topicId = -1;
        if (request.getParameter("topicId") != null) {
            topicId = Long.parseLong(request.getParameter("topicId"));
        }
        ServiceMap serviceMap = getBimServer().getServiceFactory().get(token, AccessMethod.INTERNAL);

        String action = request.getParameter("action");
        if (action != null) {
            if (action.equals("extendeddata")) {
                SExtendedData sExtendedData = serviceMap.getServiceInterface()
                        .getExtendedData(Long.parseLong(request.getParameter("edid")));
                SFile file = serviceMap.getServiceInterface().getFile(sExtendedData.getFileId());
                if (file.getMime() != null) {
                    response.setContentType(file.getMime());
                }
                if (file.getFilename() != null) {
                    response.setHeader("Content-Disposition",
                            "inline; filename=\"" + file.getFilename() + "\"");
                }
                outputStream.write(file.getData());
                if (outputStream instanceof GZIPOutputStream) {
                    ((GZIPOutputStream) outputStream).finish();
                }
                outputStream.flush();
                return;
            } else if (action.equals("getfile")) {
                String type = request.getParameter("type");
                if (type.equals("proto")) {
                    try {
                        String protocolBuffersFile = serviceMap.getAdminInterface()
                                .getProtocolBuffersFile(request.getParameter("name"));
                        outputStream.write(protocolBuffersFile.getBytes(Charsets.UTF_8));
                        outputStream.flush();
                    } catch (ServiceException e) {
                        LOGGER.error("", e);
                    }
                } else if (type.equals("serverlog")) {
                    try {
                        OutputStreamWriter writer = new OutputStreamWriter(outputStream);
                        writer.write(serviceMap.getAdminInterface().getServerLog());
                        writer.flush();
                    } catch (ServerException e) {
                        LOGGER.error("", e);
                    } catch (UserException e) {
                        LOGGER.error("", e);
                    }
                }
            } else if (action.equals("getBcfImage")) {
                long extendedDataId = Long.parseLong(request.getParameter("extendedDataId"));
                String topicGuid = request.getParameter("topicGuid");
                String imageGuid = request.getParameter("imageGuid");
                String name = request.getParameter("name");
                BcfFile bcfFile = BcfCache.INSTANCE.get(extendedDataId);
                if (bcfFile == null) {
                    SExtendedData extendedData = serviceMap.getServiceInterface()
                            .getExtendedData(extendedDataId);
                    long fileId = extendedData.getFileId();
                    SFile file = serviceMap.getServiceInterface().getFile(fileId);
                    try {
                        bcfFile = BcfFile.read(new ByteArrayInputStream(file.getData()),
                                new ReadOptions(false));
                        BcfCache.INSTANCE.put(extendedDataId, bcfFile);
                    } catch (BcfException e) {
                        e.printStackTrace();
                    }
                }
                TopicFolder topicFolder = bcfFile.getTopicFolder(topicGuid);
                if (topicFolder != null) {
                    byte[] data = topicFolder.getSnapshot(topicGuid + "/" + name);
                    if (data != null) {
                        response.setContentType("image/png");
                        IOUtils.write(data, outputStream);
                        if (outputStream instanceof GZIPOutputStream) {
                            ((GZIPOutputStream) outputStream).finish();
                        }
                        outputStream.flush();
                        return;
                    }
                }
            }
        } else {
            SSerializerPluginConfiguration serializer = null;
            if (request.getParameter("serializerOid") != null) {
                long serializerOid = Long.parseLong(request.getParameter("serializerOid"));
                serializer = serviceMap.getServiceInterface().getSerializerById(serializerOid);
            } else {
                serializer = serviceMap.getServiceInterface()
                        .getSerializerByName(request.getParameter("serializerName"));
            }
            if (request.getParameter("topicId") != null) {
                topicId = Long.parseLong(request.getParameter("topicId"));
            }
            if (topicId == -1) {
                response.getWriter().println("No valid topicId");
                return;
            }
            SDownloadResult checkoutResult = serviceMap.getServiceInterface().getDownloadData(topicId);
            if (checkoutResult == null) {
                LOGGER.error("Invalid topicId: " + topicId);
            } else {
                DataSource dataSource = checkoutResult.getFile().getDataSource();
                PluginConfiguration pluginConfiguration = new PluginConfiguration(
                        serviceMap.getPluginInterface().getPluginSettings(serializer.getOid()));

                final ProgressTopic progressTopic = getBimServer().getNotificationsManager()
                        .getProgressTopic(topicId);

                ProgressReporter progressReporter = new ProgressReporter() {
                    private long lastMax;
                    private long lastProgress;
                    private int stage = 3;
                    private Date start = new Date();
                    private String title = "Downloading...";

                    @Override
                    public void update(long progress, long max) {
                        if (progressTopic != null) {
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(start);
                            ds.setState(progress == max ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * progress / max));

                            progressTopic.stageProgressUpdate(ds);

                            this.lastMax = max;
                            this.lastProgress = progress;
                        }
                    }

                    @Override
                    public void setTitle(String title) {
                        if (progressTopic != null) {
                            stage++;
                            this.title = title;
                            LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                            ds.setStart(new Date());
                            ds.setState(lastProgress == lastMax ? ActionState.FINISHED : ActionState.STARTED);
                            ds.setTitle(title);
                            ds.setStage(stage);
                            ds.setProgress((int) Math.round(100.0 * lastProgress / lastMax));

                            progressTopic.stageProgressUpdate(ds);
                        }
                    }
                };

                try {
                    if (zip) {
                        if (pluginConfiguration.getString("ZipExtension") != null) {
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + "."
                                            + pluginConfiguration.getString(SerializerPlugin.ZIP_EXTENSION)
                                            + "\"");
                        } else {
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + ".zip" + "\"");
                        }
                        response.setContentType("application/zip");

                        String nameInZip = dataSource.getName() + "."
                                + pluginConfiguration.getString(SerializerPlugin.EXTENSION);
                        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
                        zipOutputStream.putNextEntry(new ZipEntry(nameInZip));

                        processDataSource(zipOutputStream, dataSource, progressReporter);
                        try {
                            zipOutputStream.finish();
                        } catch (IOException e) {
                            // Sometimes it's already closed, that's no problem
                        }
                    } else {
                        if (request.getParameter("mime") == null) {
                            response.setContentType(
                                    pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE));
                            response.setHeader("Content-Disposition",
                                    "inline; filename=\"" + dataSource.getName() + "."
                                            + pluginConfiguration.getString(SerializerPlugin.EXTENSION) + "\"");
                        } else {
                            response.setContentType(request.getParameter("mime"));
                        }
                        processDataSource(outputStream, dataSource, progressReporter);
                    }
                } catch (SerializerException s) {
                    if (s.getCause() != null && s.getCause() instanceof IOException) {

                    } else {
                        LOGGER.error("", s);
                    }

                    LongActionState ds = StoreFactory.eINSTANCE.createLongActionState();
                    ds.setStart(new Date());
                    ds.setState(ActionState.AS_ERROR);
                    ds.setTitle("Serialization Error");
                    ds.setProgress(-1);
                    ds.setStage(3);
                    ds.getErrors().add(s.getMessage());

                    progressTopic.stageProgressUpdate(ds);
                }
            }
        }
        if (outputStream instanceof GZIPOutputStream) {
            ((GZIPOutputStream) outputStream).finish();
        }
        outputStream.flush();
    } catch (NumberFormatException e) {
        LOGGER.error("", e);
        response.getWriter().println("Some number was incorrectly formatted");
    } catch (ServiceException e) {
        LOGGER.error("", e);
        response.getWriter().println(e.getUserMessage());
    } catch (EOFException e) {
    } catch (Exception e) {
        LOGGER.error("", e);
    }
}

From source file:it.infn.ct.jsaga.adaptor.tosca.job.ToscaJobControlAdaptor.java

private String submitTosca() throws IOException, ParseException, BadResource, NoSuccessException {
    StringBuilder orchestrator_result = new StringBuilder("");
    StringBuilder postData = new StringBuilder();
    postData.append("{ \"template\": \"");
    String tosca_template_content = "";
    try {//ww  w  .  ja v  a  2s  .co  m
        tosca_template_content = new String(Files.readAllBytes(Paths.get(tosca_template))).replace("\n", "\\n");
        postData.append(tosca_template_content);
    } catch (IOException ex) {
        log.error("Template '" + tosca_template + "'is not readable");
        throw new BadResource("Template '" + tosca_template + "'is not readable; template:" + LS + "'"
                + tosca_template_content + "'");
    }
    postData.append("\"  }");

    log.debug("JSON Data sent to the orchestrator: \n" + postData);
    HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) endpoint.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(postData.toString());
        wr.flush();
        wr.close();
        log.debug("Orchestrator status code: " + conn.getResponseCode());
        log.debug("Orchestrator status message: " + conn.getResponseMessage());
        if (conn.getResponseCode() == 201) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            orchestrator_result = new StringBuilder();
            String ln;
            while ((ln = br.readLine()) != null) {
                orchestrator_result.append(ln);
            }

            log.debug("Orchestrator result: " + orchestrator_result);
            String orchestratorDoc = orchestrator_result.toString();
            tosca_UUID = getDocumentValue(orchestratorDoc, "uuid");
            log.debug("Created resource has UUID: '" + tosca_UUID + "'");
            return orchestratorDoc;

        }
    } catch (IOException ex) {
        log.error("Connection error with the service at " + endpoint.toString());
        log.error(ex);
        throw new NoSuccessException("Connection error with the service at " + endpoint.toString());
    } catch (ParseException ex) {
        log.error("Orchestrator response not parsable");
        throw new NoSuccessException(
                "Orchestrator response not parsable:" + LS + "'" + orchestrator_result.toString() + "'");
    }
    return tosca_UUID;
}

From source file:com.example.kjpark.smartclass.NoticeTab.java

private void setSignatureLayout() {
    LayoutInflater dialogInflater = (LayoutInflater) getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    dialogView = dialogInflater.inflate(R.layout.dialog_signature, null);
    mSignaturePad = (SignaturePad) dialogView.findViewById(R.id.signature_pad);

    clearButton = (Button) dialogView.findViewById(R.id.clearButton);
    sendButton = (Button) dialogView.findViewById(R.id.sendButton);

    mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
        @Override/*from   w  w  w. ja  v  a2 s.  co  m*/
        public void onSigned() {
            clearButton.setEnabled(true);
            sendButton.setEnabled(true);
        }

        @Override
        public void onClear() {
            clearButton.setEnabled(false);
            sendButton.setEnabled(false);
        }
    });
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mSignaturePad.clear();
        }
    });
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //send sign image to server
            ConnectServer.getInstance().setAsncTask(new AsyncTask<String, Void, Boolean>() {
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                private String num = Integer.toString(currentViewItem);

                @Override
                protected Boolean doInBackground(String... params) {
                    URL obj = null;
                    try {
                        obj = new URL("http://165.194.104.22:5000/enroll_sign");
                        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

                        //implement below code if token is send to server
                        con = ConnectServer.getInstance().setHeader(con);

                        con.setDoOutput(true);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        signatureBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                        byte[] b = baos.toByteArray();
                        String sign_image = Base64.encodeToString(b, Base64.DEFAULT);
                        Log.d(TAG, "sign_image: " + sign_image.length());

                        String parameter = URLEncoder.encode("num", "UTF-8") + "="
                                + URLEncoder.encode(num, "UTF-8");
                        parameter += "&" + URLEncoder.encode("sign_image", "UTF-8") + "="
                                + URLEncoder.encode(sign_image, "UTF-8");

                        OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
                        wr.write(parameter);
                        wr.flush();

                        BufferedReader rd = null;

                        if (con.getResponseCode() == 200) {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));

                            Log.d("---- success ----", rd.toString());

                        } else {
                            // ? 
                            rd = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));
                            Log.d("---- failed ----", String.valueOf(rd.readLine()));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Boolean aBoolean) {

                }
            });
            ConnectServer.getInstance().execute();
            signature_dialog.dismiss();
            loadBoards();
        }
    });
}

From source file:org.guanxi.sp.engine.service.shibboleth.AuthConsumerServiceThread.java

/**
 * This opens the connection to the guard, sends the SOAP request, and reads the response.
 * //  w  ww  .  j  a  v  a  2s.  co  m
 * @param acsURL              The URL of the Guard Attribute Consumer Service
 * @param entityID            The entity ID of the Guard
 * @param keystoreFile        The location of the keystore to use to identify the engine to the guard
 * @param keystorePassword    The password for the keystore
 * @param truststoreFile      The location of the truststore to use to verify the guard
 * @param truststorePassword  The password for the truststore
 * @param soapRequest         The request that will be sent to the Guard
 * @param guardSession        The Guard's session ID
 * @return                    A string containing the response from the guard
 * @throws GuanxiException    If there is a problem creating the EntityConnection or setting the attributes on it
 * @throws IOException        If there is a problem using the EntityConnection to read or write data
 */
private String processGuardConnection(String acsURL, String entityID, String keystoreFile,
        String keystorePassword, String truststoreFile, String truststorePassword, EnvelopeDocument soapRequest,
        String guardSession) throws GuanxiException, IOException {
    ResponseDocument responseDoc = unmarshallSAML(soapRequest);
    Bag bag = getBag(responseDoc, guardSession);

    // Initialise the connection to the Guard's attribute consumer service
    EntityConnection connection = new EntityConnection(acsURL, entityID, keystoreFile, keystorePassword,
            truststoreFile, truststorePassword, EntityConnection.PROBING_OFF);
    connection.setDoOutput(true);
    connection.connect();

    // Send the data to the Guard in an explicit POST variable
    String json = URLEncoder.encode(Guanxi.REQUEST_PARAMETER_SAML_ATTRIBUTES, "UTF-8") + "="
            + URLEncoder.encode(bag.toJSON(), "UTF-8");

    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();

    // ...and read the response from the Guard
    return new String(Utils.read(connection.getInputStream()));
}

From source file:org.huahinframework.manager.rest.service.HiveService.java

@Path("/execute")
@POST//from w  w w.  j av  a 2  s .c o  m
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaTypeUtils.MULTIPART_FORM_DATA)
public void execute(@Context HttpServletResponse response, InMultiPart inMP) throws IOException {
    OutputStreamWriter out = null;
    Map<String, String> status = new HashMap<String, String>();
    Map<String, Object> result = new HashMap<String, Object>();
    try {
        out = new OutputStreamWriter(response.getOutputStream());
        if (!inMP.hasNext()) {
            status.put(Response.STATUS, "Query is empty");
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
            return;
        }

        JSONObject argument = createJSON(inMP.next().getInputStream());
        String query = argument.getString(JSON_QUERY);
        if (query == null || query.isEmpty()) {
            status.put(Response.STATUS, "Query is empty");
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
            return;
        }

        Class.forName(driverName);
        Connection con = DriverManager.getConnection(String.format(connectionFormat, hiveserver), "", "");
        Statement stmt = con.createStatement();

        int queryNo = 1;
        String command = "";
        for (String oneCmd : query.split(";")) {
            if (StringUtils.endsWith(oneCmd, "")) {
                command += StringUtils.chop(oneCmd) + ";";
                continue;
            } else {
                command += oneCmd;
            }

            if (StringUtils.isBlank(command)) {
                continue;
            }

            boolean b = stmt.execute(command);
            if (b) {
                result.clear();
                result.put(JSON_QUERY, queryNo);

                ResultSet resultSet = stmt.getResultSet();
                while (resultSet.next()) {
                    JSONObject jsonObject = new JSONObject();
                    for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                        jsonObject.put(resultSet.getMetaData().getColumnName(i), resultSet.getString(i));
                    }
                    result.put(RESULT, jsonObject);

                    out.write(new JSONObject(result).toString());
                    out.flush();
                }

                if (result.size() == 1) {
                    status.put(Response.STATUS, "SCCESS");
                    result.put(RESULT, status);

                    JSONObject jsonObject = new JSONObject(result);
                    out.write(jsonObject.toString());
                    out.flush();
                }
            } else {
                result.clear();
                status.clear();

                result.put(JSON_QUERY, queryNo);

                status.put(Response.STATUS, "SCCESS");
                result.put(RESULT, status);

                JSONObject jsonObject = new JSONObject(result);
                out.write(jsonObject.toString());
                out.flush();
            }

            command = "";
            queryNo++;
        }

        con.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
        log.error(e);
        if (out != null) {
            status.put(Response.STATUS, e.getMessage());
            out.write(new JSONObject(status).toString());
            out.flush();
            out.close();
        }
    }
}

From source file:com.roche.iceboar.demo.JnlpServlet.java

/**
 * This method handle all HTTP requests for *.jnlp files (defined in web.xml). Method check, is name correct
 * (allowed), read file from disk, replace #{codebase} (it's necessary to be generated based on where application
 * is deployed), #{host} () and write to the response.
 * <p>//from   w ww  .ja v a2s  .c  o m
 * You can use this class in your code for downloading JNLP files.
 * Return a content of requested jnlp file in response.
 *
 * @throws IOException when can't close some stream
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String contextPath = request.getContextPath();
    String requestURI = request.getRequestURI();
    String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    String codebase = host + contextPath;
    String filename = StringUtils.removeStart(requestURI, contextPath);
    response.setContentType("application/x-java-jnlp-file");
    response.addHeader("Pragma", "no-cache");
    response.addHeader("Expires", "-1");

    OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream());

    InputStream in = JnlpServlet.class.getResourceAsStream(filename);
    if (in == null) {
        error(response, "Can't open: " + filename);
        return;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));

    String line = reader.readLine();
    while (line != null) {
        line = line.replace("#{codebase}", codebase);
        line = line.replace("#{host}", host);
        out.write(line);
        out.write("\n");
        line = reader.readLine();
    }

    out.flush();
    out.close();
    reader.close();
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

private MemoryFileDTO createFile(final Collection<RecordDTO> records) {
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName(new Date().getTime() + ".mrc");
    try {/*  www  .j av a  2 s .  com*/
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        for (RecordDTO dto : records) {
            writer.write(dto.getIso2709());
            writer.write(ApplicationConstants.LINE_BREAK);
        }
        writer.flush();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return file;
}

From source file:MegaHandler.java

private String api_request(String data) {
    HttpURLConnection connection = null;
    try {/*from  w  w  w  .  j a  va 2s . c om*/
        String urlString = "https://g.api.mega.co.nz/cs?id=" + sequence_number;
        if (sid != null)
            urlString += "&sid=" + sid;

        URL url = new URL(urlString);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST"); //use post method
        connection.setDoOutput(true); //we will send stuff
        connection.setDoInput(true); //we want feedback
        connection.setUseCaches(false); //no caches
        connection.setAllowUserInteraction(false);
        connection.setRequestProperty("Content-Type", "text/xml");

        OutputStream out = connection.getOutputStream();
        try {
            OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write("[" + data + "]"); //data is JSON object containing the api commands
            wr.flush();
            wr.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the output stream
            if (out != null)
                out.close();
        }

        InputStream in = connection.getInputStream();
        StringBuffer response = new StringBuffer();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = rd.readLine()) != null) {
                response.append(line);
            }
            rd.close(); //close the reader
        } catch (IOException e) {
            e.printStackTrace();
        } finally { //in this case, we are ensured to close the input stream
            if (in != null)
                in.close();
        }

        return response.toString().substring(1, response.toString().length() - 1);

    } catch (IOException e) {
        e.printStackTrace();
    }

    return "";
}