Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:airlift.servlet.rest.RestServlet.java

/**
 * Process request./*from  w  w w  . j a va2 s .  c o  m*/
 *
 * @param _httpServletRequest the _http servlet request
 * @param _httpServletResponse the _http servlet response
 * @param _method the _method
 * @param _restContext the _rest context
 * @param _uriParameterMap the _uri parameter map
 * @throws ServletException the servlet exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected final void processRequest(HttpServletRequest _httpServletRequest,
        HttpServletResponse _httpServletResponse, String _method, RestContext _restContext,
        Map _uriParameterMap) throws ServletException, IOException {
    String userId = (_restContext.getUser() != null) ? _restContext.getUser().getUserId() : "";

    String appName = getServletName();
    String domainName = _restContext.getThisDomain();
    java.util.List<String> handlerPathList = _restContext.getHandlerPathList();

    try {
        String defaultMimeType = (this.getServletConfig().getInitParameter("a.default.mime.type") != null)
                ? this.getServletConfig().getInitParameter("a.default.mime.type")
                : "text/html";
        ContentContext contentContext = new SimpleContentContext(new byte[0], defaultMimeType);

        if (handlerPathList != null) {
            boolean handlerNotFound = false;

            try {
                contentContext = getHandlerContext().execute(appName, _restContext, _method, this,
                        _httpServletRequest, _httpServletResponse, _uriParameterMap);
            } catch (airlift.servlet.rest.HandlerException _handlerException) {
                if (_handlerException
                        .getErrorCode() == airlift.servlet.rest.HandlerException.ErrorCode.HANDLER_NOT_FOUND) {
                    handlerNotFound = true;
                } else {
                    throw _handlerException;
                }
            }

            if (handlerNotFound == true) {
                sendCodedPage("405", "Method Not Allowed", _httpServletResponse);
            }

            int responseCode = Integer.parseInt(contentContext.getResponseCode());

            _httpServletResponse.setStatus(responseCode);

            if (responseCode == 301 || responseCode == 302 || responseCode == 303)
            //TODO this should be checking to see if the method
            //call is a POST PUT or DELETE.  At this point the
            {
                _httpServletResponse.sendRedirect(contentContext.getRedirectUri());
            } else {
                if (contentContext.streamed != true) {
                    if (responseCode < 400
                            || contentContext.getContent() != null && contentContext.getContent().length > 0) {
                        for (java.util.Map.Entry<String, String[]> header : contentContext.getHeaderMap()
                                .entrySet()) {

                            String[] headerValues = header.getValue();

                            if (headerValues != null) {
                                for (int h = 0; h < headerValues.length; h++) {
                                    _httpServletResponse.addHeader(header.getKey(), headerValues[h]);
                                }
                            }
                        }

                        _httpServletResponse.setContentType(contentContext.getType());
                        byte[] content = contentContext.getContent();
                        _httpServletResponse.setContentLength(content.length);

                        java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
                        byteArrayOutputStream.write(content, 0, content.length);
                        byteArrayOutputStream.writeTo(_httpServletResponse.getOutputStream());
                        byteArrayOutputStream.flush();
                        _httpServletResponse.getOutputStream().flush();
                    } else {
                        sendCodedPage(contentContext.getResponseCode(), "", _httpServletResponse);
                    }
                }
            }
        } else {
            sendCodedPage("404", "Resource Not Found", _httpServletResponse);
        }
    } catch (Throwable t) {
        //log exception
        //log content generated so far
        log.severe("Airlift encountered exception: " + t.toString());

        String errorString = airlift.util.AirliftUtil.serializeStackTrace(t);
        log.severe("Airlift prints this stack trace: " + errorString);

        String reportJavaException = this.getServletConfig().getInitParameter("a.report.java.exception");

        ContentContext contentContext = new SimpleContentContext();

        if ("yes".equalsIgnoreCase(reportJavaException) == true) {

            contentContext.setType("text/html");
            contentContext.setContent(t.toString());
            _httpServletResponse.getWriter().print(contentContext.getContent());
        } else {
            sendCodedPage("500", "Internal Server Error", _httpServletResponse);
        }
    }
}

From source file:business.services.PaNumberService.java

public HttpEntity<InputStreamResource> writeAllPaNumbers(List<LabRequestRepresentation> labRequests)
        throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING);
    CSVWriter csvwriter = new CSVWriter(writer, ',', '"');
    csvwriter.writeNext(PA_NUMBERS_HEADER);
    for (LabRequestRepresentation labRequest : labRequests) {
        String labRequestCode = labRequest.getLabRequestCode();
        String status = labRequest.getStatus().toString();
        String labName = labRequest.getLab().getName();
        String requesterName = labRequest.getRequesterName();
        String requesterEmail = labRequest.getRequesterEmail();
        String requesterTelephone = labRequest.getRequesterTelephone();
        String labRequestSentDate = labRequest.getSendDate() == null ? "" : labRequest.getSendDate().toString();
        for (PathologyRepresentation item : labRequest.getPathologyList()) {
            csvwriter.writeNext(new String[] { labRequestCode, status, item.getPaNumber(), labName,
                    requesterName, requesterEmail, requesterTelephone, labRequestSentDate });
        }/*w  w w.  ja  va  2s  . com*/
    }
    csvwriter.flush();
    writer.flush();
    out.flush();
    InputStream in = new ByteArrayInputStream(out.toByteArray());
    csvwriter.close();
    writer.close();
    out.close();
    InputStreamResource resource = new InputStreamResource(in);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.valueOf("text/csv;charset=" + PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING));
    String filename = "pa_numbers.csv";
    headers.set("Content-Disposition", "attachment; filename=" + filename);
    HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
    return response;
}

From source file:com.ehsy.solr.util.SimplePostTool.java

/**
 * Reads an input stream into a byte array
 * @param is the input stream//from   w  ww  .j a  va  2s . c o  m
 * @return the byte array
 * @throws IOException If there is a low-level I/O error.
 */
protected byte[] inputStreamToByteArray(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int next = is.read();
    while (next > -1) {
        bos.write(next);
        next = is.read();
    }
    bos.flush();
    is.close();
    return bos.toByteArray();
}

From source file:com.android.launcher3.Utilities.java

/**
 * Compresses the bitmap to a byte array for serialization.
 *//*from w w w  .j a  v a 2s  . co m*/
public static byte[] flattenBitmap(Bitmap bitmap) {
    // Try go guesstimate how much space the icon will take when serialized
    // to avoid unnecessary allocations/copies during the write.
    int size = bitmap.getWidth() * bitmap.getHeight() * 4;
    ByteArrayOutputStream out = new ByteArrayOutputStream(size);
    try {
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        out.flush();
        out.close();
        return out.toByteArray();
    } catch (IOException e) {
        Log.w(TAG, "Could not write bitmap");
        return null;
    }
}

From source file:com.microsoft.rightsmanagement.sampleapp.MsipcTaskFragment.java

/**
 * Start content consumption and read protected content from ptxt file format
 * /*  w ww  .j av  a2 s  . c  o m*/
 * @param inputStream the input stream
 */
public void startContentConsumptionFromPtxtFileFormat(InputStream inputStream) {
    CreationCallback<ProtectedFileInputStream> protectedFileInputStreamCreationCallback = new CreationCallback<ProtectedFileInputStream>() {
        @Override
        public Context getContext() {
            return mApplicationContext;
        }

        @Override
        public void onCancel() {
            updateTaskStatus(new TaskStatus(TaskState.Cancelled,
                    "ProtectedFileInputStream creation was cancelled", true));
        }

        @Override
        public void onFailure(ProtectionException e) {
            updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
        }

        @Override
        public void onSuccess(ProtectedFileInputStream protectedFileInputStream) {
            mUserPolicy = protectedFileInputStream.getUserPolicy();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] dataChunk = new byte[16384];
            try {
                while ((nRead = protectedFileInputStream.read(dataChunk, 0, dataChunk.length)) != -1) {
                    buffer.write(dataChunk, 0, nRead);
                }
                buffer.flush();
                mDecryptedContent = new String(buffer.toByteArray(), Charset.forName("UTF-8"));
                buffer.close();
                protectedFileInputStream.close();
            } catch (IOException e) {
                updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
                return;
            }
            updateTaskStatus(
                    new TaskStatus(TaskState.Completed, "Content was consumed", true, Signal.ContentConsumed));
        }
    };

    try {
        updateTaskStatus(new TaskStatus(TaskState.Starting, "Consuming content", true));

        ProtectedFileInputStream.create(inputStream, null, mRmsAuthCallback, mConsentCallback,
                PolicyAcquisitionFlags.NONE, protectedFileInputStreamCreationCallback);
    } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {
        updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
    }
}

From source file:nl.surfsara.newsreader.pipeline.modules.NAFFileProvidedNewsreaderModule.java

@Override
public Module call() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayOutputStream bes = new ByteArrayOutputStream();

    String filename = UUID.randomUUID().toString();
    File xmlf = new File(getLocalDirectory() + "/" + filename);
    FileOutputStream fos = new FileOutputStream(xmlf);
    InputStream xmlStream = IOUtils.toInputStream(getInputDocument(), "UTF-8");
    IOUtils.copy(xmlStream, fos);//w  ww .j  ava 2s . c  o  m
    fos.flush();
    fos.close();
    xmlStream.close();

    File f = new File(pipelineStep.getModulePath() + "/run.sh.hadoop");
    File component = new File(pipelineStep.getModulePath());
    File scratch = new File(getLocalDirectory());

    super.setCommandLine("/bin/bash " + f.getAbsolutePath() + " " + component.getAbsolutePath() + "/ "
            + scratch.getAbsolutePath() + "/ " + xmlf.getAbsolutePath());

    super.setSubProcessStdIn(IOUtils.toInputStream(getInputDocument()));
    super.setSubProcessStdOut(bos);
    super.setSubProcessStdErr(bes);
    super.runSubprocess();

    String stderr = bes.toString();
    int newlines = stderr.split(System.getProperty("line.separator")).length;
    if (newlines > pipelineStep.getNumErrorLines()) {
        setFailed(true);
    }
    logger.error(stderr);
    bos.flush();
    setOutputDocument(bos.toString());
    bos.close();
    bes.close();
    xmlf.delete();
    return this;
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

@Override
public byte[] writeToStreamAndByteArray(OutputStream outStream) {
    byte[] data = null;
    if (this.renderedimage == null) { // no image available
        return data;
    }//from w  w w  .  j  a v a  2  s  .c  o m
    try {
        // create a buffered Image, which has no Alpha channel
        // as JPEG does not support Alpha Channels and the
        // ImageIO doesn't care - but will create a corrupt JPEG
        BufferedImage noAlphaBi = ImageManipulator.fromRenderedToBufferedNoAlpha(renderedimage);
        ImageOutputStream imageOutStream = ImageIO.createImageOutputStream(outStream);

        // Iterator<ImageWriter> writerIter = ImageIO
        // .getImageWritersByFormatName("jpg");
        // ImageWriter writer = writerIter.next(); // get writer from ImageIO
        ImageWriter writer = new JPEGImageWriter(new JPEGImageWriterSpi());

        // create metadata by creating an XML tree
        ImageWriteParam writerParam = writer.getDefaultWriteParam();
        ImageTypeSpecifier its = new ImageTypeSpecifier(noAlphaBi);

        // ImageTypeSpecifier its = new
        // ImageTypeSpecifier(image.getColorModel(),
        // image.getSampleModel());

        // IIOMetadata iomd = writer.getDefaultImageMetadata(new
        // ImageTypeSpecifier(image), writerParam);
        // Element tree =
        // (Element)iomd.getAsTree("javax_imageio_jpeg_image_1.0");
        // Element tree = (Element)iomd.getAsTree("javax_imageio_1.0");
        //
        IIOMetadata iomd = writer.getDefaultImageMetadata(its, writerParam);

        // create the XML tree and modify the appropriate DOM elements
        // to set the metadata
        setMetadata(iomd);

        // set compression
        writerParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        float comprvalue = ((float) writerCompressionValue) / 100;
        writerParam.setCompressionQuality(comprvalue);

        // set output
        writer.setOutput(imageOutStream);
        writer.prepareWriteSequence(null);

        // create new image parameters to set the compression
        // Locale locale = new Locale("en");
        // JPEGImageWriteParam jpegWriteParam = new
        // JPEGImageWriteParam(locale);

        // IIOImage iioImage = new IIOImage(renderedimage, null, iomd);

        IIOImage iioImage = new IIOImage(noAlphaBi, null, iomd);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageOutStream.flush();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        ImageOutputStream imageToFile = ImageIO.createImageOutputStream(baos);
        writer.setOutput(imageToFile);
        writer.prepareWriteSequence(null);
        writer.write(null, iioImage, writerParam);
        writer.endWriteSequence();
        imageToFile.flush();
        imageToFile.close();
        baos.flush();
        data = baos.toByteArray();
        baos.close();
        writer.dispose();
        imageOutStream.close();
    } catch (IOException e) {
        LOGGER.error("IOException occured", e);
    }
    return data;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

private String sendPostData(PostMethod post) throws IOException {
    // Buffer to hold the post body, except file content
    StringBuilder postedBody = new StringBuilder(1000);
    HTTPFileArg[] files = getHTTPFiles();
    // Check if we should do a multipart/form-data or an
    // application/x-www-form-urlencoded post request
    if (getUseMultipartForPost()) {
        // If a content encoding is specified, we use that as the
        // encoding of any parameter values
        String contentEncoding = getContentEncoding();
        if (isNullOrEmptyTrimmed(contentEncoding)) {
            contentEncoding = null;/*from   ww w  . j  av  a2 s  . c om*/
        }

        final boolean browserCompatible = getDoBrowserCompatibleMultipart();
        // We don't know how many entries will be skipped
        List<PartBase> partlist = new ArrayList<>();
        // Create the parts
        // Add any parameters
        for (JMeterProperty jMeterProperty : getArguments()) {
            HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
            String parameterName = arg.getName();
            if (arg.isSkippable(parameterName)) {
                continue;
            }
            StringPart part = new StringPart(arg.getName(), arg.getValue(), contentEncoding);
            if (browserCompatible) {
                part.setTransferEncoding(null);
                part.setContentType(null);
            }
            partlist.add(part);
        }

        // Add any files
        for (HTTPFileArg file : files) {
            File inputFile = FileServer.getFileServer().getResolvedFile(file.getPath());
            // We do not know the char set of the file to be uploaded, so we set it to null
            ViewableFilePart filePart = new ViewableFilePart(file.getParamName(), inputFile, file.getMimeType(),
                    null);
            filePart.setCharSet(null); // We do not know what the char set of the file is
            partlist.add(filePart);
        }

        // Set the multipart for the post
        int partNo = partlist.size();
        Part[] parts = partlist.toArray(new Part[partNo]);
        MultipartRequestEntity multiPart = new MultipartRequestEntity(parts, post.getParams());
        post.setRequestEntity(multiPart);

        // Set the content type
        String multiPartContentType = multiPart.getContentType();
        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, multiPartContentType);

        // If the Multipart is repeatable, we can send it first to
        // our own stream, without the actual file content, so we can return it
        if (multiPart.isRepeatable()) {
            // For all the file multiparts, we must tell it to not include
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(true); // .sendMultipartWithoutFileContent(bos);
                }
            }
            // Write the request to our own stream
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            multiPart.writeRequest(bos);
            bos.flush();
            // We get the posted bytes using the encoding used to create it
            postedBody.append(new String(bos.toByteArray(), contentEncoding == null ? "US-ASCII" // $NON-NLS-1$ this is the default used by HttpClient
                    : contentEncoding));
            bos.close();

            // For all the file multiparts, we must revert the hiding of
            // the actual file content
            for (int i = 0; i < partNo; i++) {
                if (parts[i] instanceof ViewableFilePart) {
                    ((ViewableFilePart) parts[i]).setHideFileData(false);
                }
            }
        } else {
            postedBody.append("<Multipart was not repeatable, cannot view what was sent>"); // $NON-NLS-1$
        }
    } else {
        // Check if the header manager had a content type header
        // This allows the user to specify his own content-type for a POST request
        Header contentTypeHeader = post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        boolean hasContentTypeHeader = contentTypeHeader != null && contentTypeHeader.getValue() != null
                && contentTypeHeader.getValue().length() > 0;
        // If there are no arguments, we can send a file as the body of the request
        // TODO: needs a multiple file upload scenerio
        if (!hasArguments() && getSendFileAsPostBody()) {
            // If getSendFileAsPostBody returned true, it's sure that file is not null
            HTTPFileArg file = files[0];
            if (!hasContentTypeHeader) {
                // Allow the mimetype of the file to control the content type
                if (file.getMimeType() != null && file.getMimeType().length() > 0) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                } else {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
            }

            FileRequestEntity fileRequestEntity = new FileRequestEntity(new File(file.getPath()), null);
            post.setRequestEntity(fileRequestEntity);

            // We just add placeholder text for file content
            postedBody.append("<actual file content, not shown here>");
        } else {
            // In a post request which is not multipart, we only support
            // parameters, no file upload is allowed

            // If a content encoding is specified, we set it as http parameter, so that
            // the post body will be encoded in the specified content encoding
            String contentEncoding = getContentEncoding();
            boolean haveContentEncoding = false;
            if (isNullOrEmptyTrimmed(contentEncoding)) {
                contentEncoding = null;
            } else {
                post.getParams().setContentCharset(contentEncoding);
                haveContentEncoding = true;
            }

            // If none of the arguments have a name specified, we
            // just send all the values as the post body
            if (getSendParameterValuesAsPostBody()) {
                // Allow the mimetype of the file to control the content type
                // This is not obvious in GUI if you are not uploading any files,
                // but just sending the content of nameless parameters
                // TODO: needs a multiple file upload scenerio
                if (!hasContentTypeHeader) {
                    HTTPFileArg file = files.length > 0 ? files[0] : null;
                    if (file != null && file.getMimeType() != null && file.getMimeType().length() > 0) {
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE, file.getMimeType());
                    } else {
                        // TODO - is this the correct default?
                        post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                                HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                    }
                }

                // Just append all the parameter values, and use that as the post body
                StringBuilder postBody = new StringBuilder();
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    String value;
                    if (haveContentEncoding) {
                        value = arg.getEncodedValue(contentEncoding);
                    } else {
                        value = arg.getEncodedValue();
                    }
                    postBody.append(value);
                }
                StringRequestEntity requestEntity = new StringRequestEntity(postBody.toString(),
                        post.getRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE).getValue(), contentEncoding);
                post.setRequestEntity(requestEntity);
            } else {
                // It is a normal post request, with parameter names and values

                // Set the content type
                if (!hasContentTypeHeader) {
                    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_TYPE,
                            HTTPConstants.APPLICATION_X_WWW_FORM_URLENCODED);
                }
                // Add the parameters
                for (JMeterProperty jMeterProperty : getArguments()) {
                    HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
                    // The HTTPClient always urlencodes both name and value,
                    // so if the argument is already encoded, we have to decode
                    // it before adding it to the post request
                    String parameterName = arg.getName();
                    if (arg.isSkippable(parameterName)) {
                        continue;
                    }
                    String parameterValue = arg.getValue();
                    if (!arg.isAlwaysEncoded()) {
                        // The value is already encoded by the user
                        // Must decode the value now, so that when the
                        // httpclient encodes it, we end up with the same value
                        // as the user had entered.
                        String urlContentEncoding = contentEncoding;
                        if (urlContentEncoding == null || urlContentEncoding.length() == 0) {
                            // Use the default encoding for urls
                            urlContentEncoding = EncoderCache.URL_ARGUMENT_ENCODING;
                        }
                        parameterName = URLDecoder.decode(parameterName, urlContentEncoding);
                        parameterValue = URLDecoder.decode(parameterValue, urlContentEncoding);
                    }
                    // Add the parameter, httpclient will urlencode it
                    post.addParameter(parameterName, parameterValue);
                }

                /*
                //                    // Alternative implementation, to make sure that HTTPSampler and HTTPSampler2
                //                    // sends the same post body.
                //
                //                    // Only include the content char set in the content-type header if it is not
                //                    // an APPLICATION_X_WWW_FORM_URLENCODED content type
                //                    String contentCharSet = null;
                //                    if(!post.getRequestHeader(HEADER_CONTENT_TYPE).getValue().equals(APPLICATION_X_WWW_FORM_URLENCODED)) {
                //                        contentCharSet = post.getRequestCharSet();
                //                    }
                //                    StringRequestEntity requestEntity = new StringRequestEntity(getQueryString(contentEncoding), post.getRequestHeader(HEADER_CONTENT_TYPE).getValue(), contentCharSet);
                //                    post.setRequestEntity(requestEntity);
                */
            }

            // If the request entity is repeatable, we can send it first to
            // our own stream, so we can return it
            if (post.getRequestEntity().isRepeatable()) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                post.getRequestEntity().writeRequest(bos);
                bos.flush();
                // We get the posted bytes using the encoding used to create it
                postedBody.append(new String(bos.toByteArray(), post.getRequestCharSet()));
                bos.close();
            } else {
                postedBody.append("<RequestEntity was not repeatable, cannot view what was sent>");
            }
        }
    }
    // Set the content length
    post.setRequestHeader(HTTPConstants.HEADER_CONTENT_LENGTH,
            Long.toString(post.getRequestEntity().getContentLength()));

    return postedBody.toString();
}

From source file:it.govpay.web.rs.dars.anagrafica.portali.PortaliHandler.java

@Override
public Portale creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Portale entry = null;//w w w.  j  a va 2  s  .  c  om
    String pagamentiAttesaId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".pagamentiAttesa.id");
    String pagamentiOnlineId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".pagamentiOnline.id");
    String dominiPaId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".dominiPa.id");
    String tipiTributoPaId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".tipiTributoPa.id");
    String dominiPoId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".dominiPo.id");
    String tipiTributoPoId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".tipiTributoPo.id");
    String versioneId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".versione.id");
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di scrittura
        this.darsService.checkDirittiServizioScrittura(bd, this.funzionalita);

        JsonConfig jsonConfig = new JsonConfig();

        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        classMap.put(dominiPaId, Long.class);
        classMap.put(tipiTributoPaId, Long.class);
        classMap.put(dominiPoId, Long.class);
        classMap.put(tipiTributoPoId, Long.class);
        jsonConfig.setClassMap(classMap);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

        baos.flush();
        baos.close();

        JSONObject jsonObjectPortale = JSONObject.fromObject(baos.toString());

        List<Acl> lstAclTributiPa = new ArrayList<Acl>();
        List<Acl> lstAclDominiPa = new ArrayList<Acl>();

        if (jsonObjectPortale.getBoolean(pagamentiAttesaId)) {
            JSONArray jsonTributi = jsonObjectPortale.getJSONArray(tipiTributoPaId);

            for (int i = 0; i < jsonTributi.size(); i++) {
                long idTributo = jsonTributi.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.TRIBUTO);
                acl.setServizio(Servizio.PAGAMENTI_ATTESA);
                if (idTributo > 0) {
                    acl.setIdTributo(idTributo);
                    lstAclTributiPa.add(acl);
                } else {
                    lstAclTributiPa.clear();
                    lstAclTributiPa.add(acl);
                    break;
                }
            }
            JSONArray jsonDomini = jsonObjectPortale.getJSONArray(dominiPaId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.PAGAMENTI_ATTESA);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiPa.add(acl);
                } else {
                    lstAclDominiPa.clear();
                    lstAclDominiPa.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte PA
        jsonObjectPortale.remove(pagamentiAttesaId);
        jsonObjectPortale.remove(tipiTributoPaId);
        jsonObjectPortale.remove(dominiPaId);

        List<Acl> lstAclTributiPo = new ArrayList<Acl>();
        List<Acl> lstAclDominiPo = new ArrayList<Acl>();

        if (jsonObjectPortale.getBoolean(pagamentiOnlineId)) {
            JSONArray jsonTributi = jsonObjectPortale.getJSONArray(tipiTributoPoId);

            for (int i = 0; i < jsonTributi.size(); i++) {
                long idTributo = jsonTributi.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.TRIBUTO);
                acl.setServizio(Servizio.PAGAMENTI_ONLINE);
                if (idTributo > 0) {
                    acl.setIdTributo(idTributo);
                    lstAclTributiPo.add(acl);
                } else {
                    lstAclTributiPo.clear();
                    lstAclTributiPo.add(acl);
                    break;
                }
            }
            JSONArray jsonDomini = jsonObjectPortale.getJSONArray(dominiPoId);

            for (int i = 0; i < jsonDomini.size(); i++) {
                long idDominio = jsonDomini.getLong(i);

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.PAGAMENTI_ONLINE);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiPo.add(acl);
                } else {
                    lstAclDominiPo.clear();
                    lstAclDominiPo.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte PA
        jsonObjectPortale.remove(pagamentiOnlineId);
        jsonObjectPortale.remove(tipiTributoPoId);
        jsonObjectPortale.remove(dominiPoId);

        Versione versione = this.getVersioneSelezionata(jsonObjectPortale, versioneId, true);

        jsonConfig.setRootClass(Portale.class);
        entry = (Portale) JSONObject.toBean(jsonObjectPortale, jsonConfig);

        entry.setVersione(versione);

        entry.setAcls(lstAclTributiPa);
        entry.getAcls().addAll(lstAclDominiPa);
        entry.getAcls().addAll(lstAclTributiPo);
        entry.getAcls().addAll(lstAclDominiPo);

        this.log.info("Esecuzione " + methodName + " completata.");
        return entry;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

From source file:coffeshop.PaymentPage.java

private void generateQR(String btcPay) throws Exception {
    BigDecimal dollar = new BigDecimal(btcPay);
    BigDecimal btcPriceIndex = btcPriceIndex();
    BigDecimal btc = dollar.divide(btcPriceIndex, 5, BigDecimal.ROUND_HALF_UP);
    byte[] imageInByte;
    BufferedImage originalImage = ImageIO.read(new File("src/ImageRes/QR.jpg"));
    String details = "bitcoin:12nAq7bJSkKFxJYaHjhjfPAaZ6sXgLqBJ7?amount=" + btc;
    QRCode.from(details).withSize(125, 125).file();
    QRCode.from(details).withSize(125, 125).stream();
    ByteArrayOutputStream out = QRCode.from(details).to(ImageType.JPG).stream();
    ImageIO.write(originalImage, "jpg", out);
    out.flush();
    imageInByte = out.toByteArray();/* w  w w .jav a2 s .c  o m*/
    out.close();
    InputStream in = new ByteArrayInputStream(imageInByte);
    BufferedImage bImageFromConvert = ImageIO.read(in);
    ImageIO.write(bImageFromConvert, "jpg", new File("src/ImageRes/QR.jpg"));
}