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:com.microsoft.rightsmanagement.sampleapp.MsipcTaskFragment.java

/**
 * Start content consumption and read protected content from my own text file format 
 * //from   www.j  av a 2 s  .c om
 * My own File format:
 * serializedContentPolicy Length | serializedContentPolicy | Encrypted Content length | Encrypted Content
 * 
 * @param inputStream the input stream
 */
public void startContentConsumptionFromMyOwnProtectedTextFileFormat(final InputStream inputStream) {
    // This is a 2 step process
    // 1. Create a UserPolicy from serializedContentPolicy
    // 2. Create a CustomProtectedInputStream using UserPolicy and read content from it.
    CreationCallback<UserPolicy> userPolicyCreationCallbackFromSerializedContentPolicy = new CreationCallback<UserPolicy>() {
        @Override
        public void onSuccess(UserPolicy userPolicy) {
            CreationCallback<CustomProtectedInputStream> customProtectedInputStreamCreationCallback = new CreationCallback<CustomProtectedInputStream>() {
                @Override
                public Context getContext() {
                    return mApplicationContext;
                }

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

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

                @Override
                public void onSuccess(CustomProtectedInputStream customProtectedInputStream) {
                    mUserPolicy = customProtectedInputStream.getUserPolicy();
                    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                    int nRead;
                    byte[] dataChunk = new byte[16384];
                    try {
                        while ((nRead = customProtectedInputStream.read(dataChunk, 0,
                                dataChunk.length)) != -1) {
                            buffer.write(dataChunk, 0, nRead);
                        }
                        buffer.flush();
                        mDecryptedContent = new String(buffer.toByteArray(), Charset.forName("UTF-8"));
                        buffer.close();
                        customProtectedInputStream.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 {
                // Step 2: Create a CustomProtectedInputStream using UserPolicy and read content from it.
                // Retrieve the encrypted content size.
                long encryptedContentLength = readUnsignedInt(inputStream);
                updateTaskStatus(new TaskStatus(TaskState.Starting, "Consuming content", true));
                CustomProtectedInputStream.create(userPolicy, inputStream, encryptedContentLength,
                        customProtectedInputStreamCreationCallback);
            } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {
                updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
            } catch (IOException e) {
                updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
            }
        }

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

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

        @Override
        public Context getContext() {
            return mApplicationContext;
        }
    };

    try {
        // Step 1: Create a UserPolicy from serializedContentPolicy
        // Read the serializedContentPolicyLength from the inputStream.
        long serializedContentPolicyLength = readUnsignedInt(inputStream);
        // Read the PL bytes from the input stream using the PL size.
        byte[] serializedContentPolicy = new byte[(int) serializedContentPolicyLength];
        inputStream.read(serializedContentPolicy);
        updateTaskStatus(new TaskStatus(TaskState.Starting,
                "Acquring user policy to consume content from my own file format", true));

        UserPolicy.acquire(serializedContentPolicy, null, mRmsAuthCallback, mConsentCallback,
                PolicyAcquisitionFlags.NONE, userPolicyCreationCallbackFromSerializedContentPolicy);
    } catch (com.microsoft.rightsmanagement.exceptions.InvalidParameterException e) {
        updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
    } catch (IOException e) {
        updateTaskStatus(new TaskStatus(TaskState.Faulted, e.getLocalizedMessage(), true));
    }
}

From source file:microsoft.exchange.webservices.data.core.request.ServiceRequestBase.java

/**
 * Reads the response./*  w  w  w . j  a  v a 2s  . c  om*/
 *
 * @param response HTTP web request
 * @return response response object
 * @throws Exception on error
 */
protected T readResponse(HttpWebRequest response) throws Exception {
    T serviceResponse;

    if (!response.getResponseContentType().startsWith("text/xml")) {
        throw new ServiceRequestException("The response received from the service didn't contain valid XML.");
    }

    /**
     * If tracing is enabled, we read the entire response into a
     * MemoryStream so that we can pass it along to the ITraceListener. Then
     * we parse the response from the MemoryStream.
     */

    try {
        this.getService().processHttpResponseHeaders(TraceFlags.EwsResponseHttpHeaders, response);

        if (this.getService().isTraceEnabledFor(TraceFlags.EwsResponse)) {
            ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
            InputStream serviceResponseStream = ServiceRequestBase.getResponseStream(response);

            int data = serviceResponseStream.read();
            while (data != -1) {
                memoryStream.write(data);
                data = serviceResponseStream.read();
            }

            this.traceResponse(response, memoryStream);
            ByteArrayInputStream memoryStreamIn = new ByteArrayInputStream(memoryStream.toByteArray());
            EwsServiceXmlReader ewsXmlReader = new EwsServiceXmlReader(memoryStreamIn, this.getService());
            serviceResponse = this.readResponse(ewsXmlReader);
            serviceResponseStream.close();
            memoryStream.flush();
        } else {
            InputStream responseStream = ServiceRequestBase.getResponseStream(response);
            EwsServiceXmlReader ewsXmlReader = new EwsServiceXmlReader(responseStream, this.getService());
            serviceResponse = this.readResponse(ewsXmlReader);
        }

        return serviceResponse;
    } catch (HTTPException e) {
        if (e.getMessage() != null) {
            this.getService().processHttpResponseHeaders(TraceFlags.EwsResponseHttpHeaders, response);
        }
        throw new ServiceRequestException(String.format("The request failed. %s", e.getMessage()), e);
    } catch (IOException e) {
        throw new ServiceRequestException(String.format("The request failed. %s", e.getMessage()), e);
    } finally { // close the underlying response
        response.close();
    }
}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private byte[] createRequest() {
    try {//from   w  ww . j  a  va  2s .co m
        String packageName = PACKAGE_NAME;
        int baseLen;

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        os.write(10);
        writeString(os, mLoginInfo.get("Auth"));
        os.write(16);
        os.write(1);
        os.write(24);
        writeInt32(os, 2009011);
        os.write(34);
        writeString(os, mDeviceId);
        os.write(42);
        writeString(os, "passion:9");
        os.write(50);
        writeString(os, "en");
        os.write(58);
        writeString(os, "us");
        os.write(66);
        writeString(os, "DoCoMo");
        os.write(74);
        writeString(os, "DoCoMo");
        os.write(82);
        writeString(os, "44010");
        os.write(90);
        writeString(os, "44010");
        baseLen = os.size() + 1 - 3; // reduce three bytes - one marker (10) plus 2 bytes for baseLen
        os.write(19);
        os.write(82);
        writeInt32(os, packageName.length() + 2);
        os.write(10);
        writeString(os, packageName);
        os.write(20);
        os.flush();
        os.close();

        ByteArrayOutputStream request = new ByteArrayOutputStream();
        request.write(10);
        writeInt32(request, baseLen + 2);
        request.write(os.toByteArray(), 0, os.size());
        return request.toByteArray();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java

private static String save(PortletRequest request, ActionResponse response, PoolData data, boolean planOnly) {
    ImportStatus status = getImportStatus(request);
    if (data.abstractName == null || data.abstractName.equals("")) { // we're creating a new pool
        data.name = data.name.replaceAll("\\s", "");
        DeploymentManager mgr = ManagementHelper.getManagementHelper(request).getDeploymentManager();
        try {// w  w w  .j  a v  a2  s  .c o  m
            String rarPath = data.getRarPath();
            File rarFile = getRAR(request, rarPath);
            //URI uri = getRAR(request, data.getRarPath()).toURI();
            ConnectorDeployable deployable = new ConnectorDeployable(
                    PortletManager.getRepositoryEntryBundle(request, rarPath));
            DeploymentConfiguration config = mgr.createConfiguration(deployable);
            final DDBeanRoot ddBeanRoot = deployable.getDDBeanRoot();
            Connector15DCBRoot root = (Connector15DCBRoot) config.getDConfigBeanRoot(ddBeanRoot);
            ConnectorDCB connector = (ConnectorDCB) root
                    .getDConfigBean(ddBeanRoot.getChildBean(root.getXpaths()[0])[0]);

            EnvironmentData environment = new EnvironmentData();
            connector.setEnvironment(environment);
            org.apache.geronimo.deployment.service.jsr88.Artifact configId = new org.apache.geronimo.deployment.service.jsr88.Artifact();
            environment.setConfigId(configId);
            configId.setGroupId("console.dbpool");
            configId.setVersion("1.0");
            configId.setType("car");

            String artifactId = data.name;
            // simply replace / with _ if / exists within the artifactId
            // this is needed because we don't allow / within the artifactId
            artifactId = artifactId.replace('/', '_');

            // Let's check whether the artifact exists
            ConfigurationManager configurationManager = ConfigurationUtil
                    .getConfigurationManager(PortletManager.getKernel());
            if (configurationManager.isInstalled(new Artifact(configId.getGroupId(), artifactId,
                    configId.getVersion(), configId.getType()))) {
                artifactId = artifactId + "_" + new Random(System.currentTimeMillis()).nextInt(99);
            }

            configId.setArtifactId(artifactId);

            String[] jars = data.getJars();
            int length = jars[jars.length - 1].length() == 0 ? jars.length - 1 : jars.length;
            org.apache.geronimo.deployment.service.jsr88.Artifact[] dependencies = new org.apache.geronimo.deployment.service.jsr88.Artifact[length];
            for (int i = 0; i < dependencies.length; i++) {
                dependencies[i] = new org.apache.geronimo.deployment.service.jsr88.Artifact();
            }
            environment.setDependencies(dependencies);
            for (int i = 0; i < dependencies.length; i++) {
                Artifact tmp = Artifact.create(jars[i]);
                dependencies[i].setGroupId(tmp.getGroupId());
                dependencies[i].setArtifactId(tmp.getArtifactId());
                dependencies[i].setVersion(tmp.getVersion().toString());
                dependencies[i].setType(tmp.getType());
            }

            ResourceAdapter adapter = connector.getResourceAdapter()[0];
            ConnectionDefinition definition = new ConnectionDefinition();
            adapter.setConnectionDefinition(new ConnectionDefinition[] { definition });
            definition.setConnectionFactoryInterface("javax.sql.DataSource");
            ConnectionDefinitionInstance instance = new ConnectionDefinitionInstance();
            definition.setConnectionInstance(new ConnectionDefinitionInstance[] { instance });
            instance.setName(data.getName());
            ConfigPropertySetting[] settings = instance.getConfigPropertySetting();
            if (data.isGeneric()) { // it's a generic TranQL JDBC pool
                for (ConfigPropertySetting setting : settings) {
                    if (setting.getName().equals("UserName")) {
                        setting.setValue(data.user);
                    } else if (setting.getName().equals("Password")) {
                        setting.setValue(data.password);
                    } else if (setting.getName().equals("ConnectionURL")) {
                        setting.setValue(data.url);
                    } else if (setting.getName().equals("Driver")) {
                        setting.setValue(data.driverClass);
                    }
                }
            } else { // it's an XA driver or non-TranQL RA
                for (ConfigPropertySetting setting : settings) {
                    String value = data.properties.get("property-" + setting.getName());
                    setting.setValue(value == null ? "" : value);
                }
            }
            ConnectionManager manager = instance.getConnectionManager();
            if (XA.equals(data.transactionType)) {
                manager.setTransactionXA(true);
            } else if (NONE.equals(data.transactionType)) {
                manager.setTransactionNone(true);
            } else {
                manager.setTransactionLocal(true);
            }

            SinglePool pool = new SinglePool();
            manager.setPoolSingle(pool);
            pool.setMatchOne(true);
            // Max Size needs to be set before the minimum.  This is because
            // the connection manager will constrain the minimum based on the
            // current maximum value in the pool.  We might consider adding a
            // setPoolConstraints method to allow specifying both at the same time.
            if (data.maxSize != null && !data.maxSize.equals("")) {
                pool.setMaxSize(new Integer(data.maxSize));
            }
            if (data.minSize != null && !data.minSize.equals("")) {
                pool.setMinSize(new Integer(data.minSize));
            }
            if (data.blockingTimeout != null && !data.blockingTimeout.equals("")) {
                pool.setBlockingTimeoutMillis(new Integer(data.blockingTimeout));
            }
            if (data.idleTimeout != null && !data.idleTimeout.equals("")) {
                pool.setIdleTimeoutMinutes(new Integer(data.idleTimeout));
            }

            if (planOnly) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                config.save(out);
                out.close();
                return new String(out.toByteArray(), "US-ASCII");
            } else {
                File tempFile = File.createTempFile("console-deployment", ".xml");
                tempFile.deleteOnExit();
                log.debug("Writing database pool deployment plan to " + tempFile.getAbsolutePath());
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile));
                config.save(out);
                out.flush();
                out.close();
                Target[] targets = mgr.getTargets();
                if (null == targets) {
                    throw new IllegalStateException("No target to distribute to");
                }
                targets = new Target[] { targets[0] };

                ProgressObject po = mgr.distribute(targets, rarFile, tempFile);
                waitForProgress(po);
                if (po.getDeploymentStatus().isCompleted()) {
                    TargetModuleID[] ids = po.getResultTargetModuleIDs();
                    po = mgr.start(ids);
                    waitForProgress(po);
                    if (po.getDeploymentStatus().isCompleted()) {
                        ids = po.getResultTargetModuleIDs();
                        if (status != null) {
                            status.getCurrentPool().setName(data.getName());
                            status.getCurrentPool().setConfigurationName(ids[0].getModuleID());
                            status.getCurrentPool().setFinished(true);
                            response.setRenderParameter(MODE_KEY, IMPORT_STATUS_MODE);
                        }

                        log.info("Deployment completed successfully!");
                    }
                } else if (po.getDeploymentStatus().isFailed()) {
                    data.deployError = "Unable to deploy: " + data.name;
                    response.setRenderParameter(MODE_KEY, EDIT_MODE);
                    log.info("Deployment Failed!");
                }
            }
        } catch (Exception e) {
            log.error("Unable to save connection pool", e);
        } finally {
            if (mgr != null)
                mgr.release();
        }
    } else { // We're saving updates to an existing pool
        if (planOnly) {
            throw new UnsupportedOperationException("Can't update a plan for an existing deployment");
        }
        try {
            JCAManagedConnectionFactory factory = (JCAManagedConnectionFactory) PortletManager
                    .getManagedBean(request, new AbstractName(URI.create(data.getAbstractName())));
            if (data.isGeneric()) {
                factory.setConfigProperty("ConnectionURL", data.getUrl());
                factory.setConfigProperty("UserName", data.getUser());
                factory.setConfigProperty("Password", data.getPassword());
            } else {
                for (Map.Entry<String, String> entry : data.getProperties().entrySet()) {
                    factory.setConfigProperty(entry.getKey().substring("property-".length()), entry.getValue());
                }
            }
            /*Make pool setting effective after server restart*/
            Jsr77Naming naming = new Jsr77Naming();
            AbstractName connectionManagerName = naming.createChildName(
                    new AbstractName(URI.create(data.getAbstractName())), data.getName(),
                    NameFactory.JCA_CONNECTION_MANAGER);
            PoolingAttributes pool = (PoolingAttributes) PortletManager.getManagedBean(request,
                    connectionManagerName);

            pool.setPartitionMinSize(
                    data.minSize == null || data.minSize.equals("") ? 0 : Integer.parseInt(data.minSize));
            pool.setPartitionMaxSize(
                    data.maxSize == null || data.maxSize.equals("") ? 10 : Integer.parseInt(data.maxSize));
            pool.setBlockingTimeoutMilliseconds(
                    data.blockingTimeout == null || data.blockingTimeout.equals("") ? 5000
                            : Integer.parseInt(data.blockingTimeout));
            pool.setIdleTimeoutMinutes(data.idleTimeout == null || data.idleTimeout.equals("") ? 15
                    : Integer.parseInt(data.idleTimeout));

        } catch (Exception e) {
            log.error("Unable to save connection pool", e);
        }
    }
    return null;
}

From source file:org.andrewberman.sync.InheritMe.java

void downloadURLToFile(String url, File destFile) throws Exception {
    String origUrl = url;//from ww w.j  a  v  a  2s .  c om
    File origFile = destFile;

    Thread.sleep(200);
    try {
        destFile.getParentFile().mkdirs();
        destFile.createNewFile();
    } catch (Exception e) {
        errS.println("Error creating new file: " + destFile + " . Skipping this PDF...");
        throw e;
    }
    out.print("   Downloading: ");

    url = StringEscapeUtils.escapeHtml(url);
    System.out.println(url);
    url = url.replaceAll(" ", "%20");
    GetMethod get = new GetMethod(url);
    ByteArrayOutputStream outS = new ByteArrayOutputStream();
    try {
        System.out.println("     Executing get...");
        httpclient.executeMethod(get);
        System.out.println("     Done!");

        BufferedInputStream in = new BufferedInputStream(get.getResponseBodyAsStream());
        int i = 0;
        int ind = 0;
        long length = get.getResponseContentLength();
        int starRatio = (int) length / 20;
        int numStars = 0;
        while ((i = in.read()) != -1) {
            if (length != -1 && ind % starRatio == 0) {
                status(" Downloading..." + repeat(".", ++numStars));
                out.print("*");
            }
            if (ind % 512 == 0) {
                waitOrExit();
            }
            outS.write(i);
            ind++;
        }

        in.close();
        outS.flush();

        RandomAccessFile raf = new RandomAccessFile(destFile, "rw");
        raf.write(outS.toByteArray());
        //         raf.write(get.getResponseBody());
        raf.close();
    } catch (java.net.SocketTimeoutException ste) {
        ste.printStackTrace();
        if (this.retriesLeft > 0) {
            this.retriesLeft--;
            System.out.println("Retries left: " + this.retriesLeft);
            this.downloadURLToFile(origUrl, origFile);
        } else {
            throw ste;
        }
    } finally {
        outS.close();
        get.releaseConnection();
        outS = null;
        out.print("\n");
    }
}

From source file:com.openkm.module.direct.DirectWorkflowModule.java

@Override
public byte[] getProcessDefinitionImage(String token, long processDefinitionId, String node)
        throws RepositoryException, DatabaseException, WorkflowException {
    log.debug("getProcessDefinitionImage({}, {}, {})", new Object[] { token, processDefinitionId, node });
    JbpmContext jbpmContext = JBPMUtils.getConfig().createJbpmContext();
    byte[] image = null;
    Session session = null;/*ww  w.  ja  va2  s.  c  o  m*/

    try {
        if (token == null) {
            session = JCRUtils.getSession();
        } else {
            session = JcrSessionManager.getInstance().get(token);
        }

        GraphSession graphSession = jbpmContext.getGraphSession();
        org.jbpm.graph.def.ProcessDefinition pd = graphSession.getProcessDefinition(processDefinitionId);
        FileDefinition fileDef = pd.getFileDefinition();

        WorkflowUtils.DiagramInfo dInfo = WorkflowUtils.getDiagramInfo(fileDef.getInputStream("gpd.xml"));
        WorkflowUtils.DiagramNodeInfo dNodeInfo = dInfo.getNodeMap().get(node);
        BufferedImage img = ImageIO.read(fileDef.getInputStream("processimage.jpg"));

        // Obtain all nodes Y
        List<Integer> ordenadas = new ArrayList<Integer>();

        for (WorkflowUtils.DiagramNodeInfo nodeInfo : dInfo.getNodeMap().values()) {
            ordenadas.add(nodeInfo.getY());
        }

        // Calculate minimal Y
        Collections.sort(ordenadas);
        int fix = ordenadas.get(0);

        if (dNodeInfo != null) {
            // Select node
            log.debug("DiagramNodeInfo: {}", dNodeInfo);
            Graphics g = img.getGraphics();
            Graphics2D g2d = (Graphics2D) g;
            g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.25F));
            g2d.setColor(Color.blue);
            g2d.fillRect(dNodeInfo.getX(), dNodeInfo.getY() - fix, dNodeInfo.getWidth(), dNodeInfo.getHeight());
            g.dispose();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(img, "jpg", baos);
        image = baos.toByteArray();
        baos.flush();
        baos.close();

        // Activity log
        UserActivity.log(session.getUserID(), "GET_PROCESS_DEFINITION_IMAGE", "" + processDefinitionId, null);
    } catch (javax.jcr.RepositoryException e) {
        throw new RepositoryException(e.getMessage(), e);
    } catch (JbpmException e) {
        throw new WorkflowException(e.getMessage(), e);
    } catch (IOException e) {
        throw new WorkflowException(e.getMessage(), e);
    } finally {
        if (token == null)
            JCRUtils.logout(session);
        jbpmContext.close();
    }

    log.debug("getProcessDefinitionImage: {}", image);
    return image;
}

From source file:big.BigZip.java

/**
 * Version 2 that permits to extract the text from a compressed file without
 * creating any file on the disk./*from  w w w .  j  a  v  a2  s  . c  om*/
 * @param startPosition Offset where the file begins
 * @param endPosition   Offset where the file ends
 * @return      The source code of the compressed file
 */
public String extractBytesToRAM(final long startPosition, final Long endPosition) {

    String result = null;

    try {
        // enable random access to the BIG file (fast as heck)
        RandomAccessFile dataBIG = new RandomAccessFile(fileMainBIG, "r");
        // jump directly to the position where the file is positioned
        dataBIG.seek(startPosition);
        // create a byte array
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

        // now we start reading bytes during the mentioned interval
        while (dataBIG.getFilePointer() < endPosition) {
            // read a byte from our BIG archive
            int data = dataBIG.read();
            byteOutput.write(data);
        }
        // flush data at this point
        byteOutput.flush();
        // now convert the stream from input into an output (to feed the zip stream)
        ByteArrayInputStream byteInput = new ByteArrayInputStream(byteOutput.toByteArray());
        // where we place the decompressed bytes
        ByteArrayOutputStream textOutput = new ByteArrayOutputStream();
        // create the zip streamer
        final ArchiveInputStream archiveStream;
        archiveStream = new ArchiveStreamFactory().createArchiveInputStream("zip", byteInput);
        final ZipArchiveEntry entry = (ZipArchiveEntry) archiveStream.getNextEntry();
        // copy all bytes from one location to the other (and decompress the data)
        IOUtils.copy(archiveStream, textOutput);
        // flush the results
        textOutput.flush();
        // we've got the result right here!
        result = textOutput.toString();
        // now close all the streams that we have open
        dataBIG.close();
        byteOutput.close();
        byteInput.close();
        textOutput.close();
        archiveStream.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (IOException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (ArchiveException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:it.govpay.web.rs.dars.anagrafica.applicazioni.ApplicazioniHandler.java

@SuppressWarnings("unchecked")
@Override//  w w  w  . j  a v  a2  s . co  m
public Applicazione creaEntry(InputStream is, UriInfo uriInfo, BasicBD bd)
        throws WebApplicationException, ConsoleException {
    String methodName = "creaEntry " + this.titoloServizio;
    Applicazione entry = null;
    String rendicontazioneId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".rendicontazione.id");
    String versamentiId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".versamenti.id");
    String dominiRendicontazioneId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".dominiRendicontazione.id");
    String dominiVersamentiId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".dominiVersamenti.id");
    String tipiTributoVersamentiId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".tipiTributoVersamenti.id");
    String versioneId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".versione.id");
    String incassiId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".incassi.id");
    String dominiIncassiId = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + ".dominiIncassi.id");

    String tipoSslIdNot = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + "." + CONNETTORE_NOTIFICA + ".tipoSsl.id");
    String tipoSslIdVer = Utils.getInstance(this.getLanguage())
            .getMessageFromResourceBundle(this.nomeServizio + "." + CONNETTORE_VERIFICA + ".tipoSsl.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();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Utils.copy(is, baos);

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

        Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();
        classMap.put(dominiRendicontazioneId, Long.class);
        classMap.put(dominiVersamentiId, Long.class);
        classMap.put(tipiTributoVersamentiId, Long.class);
        classMap.put(dominiIncassiId, Long.class);
        jsonConfig.setClassMap(classMap);

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

        List<Acl> lstAclDominiRendicontazione = new ArrayList<Acl>();

        if (jsonObjectApplicazione.getBoolean(rendicontazioneId)) {
            JSONArray jsonDomini = jsonObjectApplicazione.getJSONArray(dominiRendicontazioneId);

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

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.RENDICONTAZIONE);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiRendicontazione.add(acl);
                } else {
                    lstAclDominiRendicontazione.clear();
                    lstAclDominiRendicontazione.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte rendicontazione
        jsonObjectApplicazione.remove(rendicontazioneId);
        jsonObjectApplicazione.remove(dominiRendicontazioneId);

        List<Acl> lstAclTributiVersamenti = new ArrayList<Acl>();
        List<Acl> lstAclDominiVersamenti = new ArrayList<Acl>();

        if (jsonObjectApplicazione.getBoolean(versamentiId)) {
            JSONArray jsonTributi = jsonObjectApplicazione.getJSONArray(tipiTributoVersamentiId);

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

                Acl acl = new Acl();
                acl.setTipo(Tipo.TRIBUTO);
                acl.setServizio(Servizio.VERSAMENTI);
                if (idTributo > 0) {
                    acl.setIdTributo(idTributo);
                    lstAclTributiVersamenti.add(acl);
                } else {
                    lstAclTributiVersamenti.clear();
                    lstAclTributiVersamenti.add(acl);
                    break;
                }
            }
            JSONArray jsonDomini = jsonObjectApplicazione.getJSONArray(dominiVersamentiId);

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

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.VERSAMENTI);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiVersamenti.add(acl);
                } else {
                    lstAclDominiVersamenti.clear();
                    lstAclDominiVersamenti.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte versamenti
        jsonObjectApplicazione.remove(versamentiId);
        jsonObjectApplicazione.remove(tipiTributoVersamentiId);
        jsonObjectApplicazione.remove(dominiVersamentiId);

        // Incassi
        List<Acl> lstAclDominiIncassi = new ArrayList<Acl>();

        if (jsonObjectApplicazione.getBoolean(incassiId)) {
            JSONArray jsonDomini = jsonObjectApplicazione.getJSONArray(dominiIncassiId);

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

                Acl acl = new Acl();
                acl.setTipo(Tipo.DOMINIO);
                acl.setServizio(Servizio.INCASSI);
                if (idDominio > 0) {
                    acl.setIdDominio(idDominio);
                    lstAclDominiIncassi.add(acl);
                } else {
                    lstAclDominiIncassi.clear();
                    lstAclDominiIncassi.add(acl);
                    break;
                }
            }
        }
        // rimuovo gli oggetti della parte incassi
        jsonObjectApplicazione.remove(incassiId);
        jsonObjectApplicazione.remove(dominiIncassiId);

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

        jsonConfig.setRootClass(Applicazione.class);
        entry = (Applicazione) JSONObject.toBean(jsonObjectApplicazione, jsonConfig);

        entry.setVersione(versione);

        entry.setAcls(lstAclDominiRendicontazione);
        entry.getAcls().addAll(lstAclTributiVersamenti);
        entry.getAcls().addAll(lstAclDominiVersamenti);
        entry.getAcls().addAll(lstAclDominiIncassi);

        String firmaRichiestaId = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".firmaRichiesta.id");
        String codFirma = jsonObjectApplicazione.getString(firmaRichiestaId);
        if (codFirma != null) {
            FirmaRichiesta enum1 = FirmaRichiesta.toEnum(codFirma);
            entry.setFirmaRichiesta(enum1);
        }

        String tipoSslNot = jsonObjectApplicazione.containsKey(tipoSslIdNot)
                ? jsonObjectApplicazione.getString(tipoSslIdNot)
                : null;
        if (tipoSslNot != null) {
            jsonObjectApplicazione.remove(tipoSslIdNot);
        }

        String tipoSslVer = jsonObjectApplicazione.containsKey(tipoSslIdVer)
                ? jsonObjectApplicazione.getString(tipoSslIdVer)
                : null;
        if (tipoSslVer != null) {
            jsonObjectApplicazione.remove(tipoSslIdVer);
        }

        String cvPrefix = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + "." + CONNETTORE_VERIFICA + ".idPrefix");
        JSONObject jsonObjectCV = new JSONObject();
        String cnPrefix = Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + "." + CONNETTORE_NOTIFICA + ".idPrefix");
        JSONObject jsonObjectCN = new JSONObject();

        Set<String> keySet = jsonObjectApplicazione.keySet();
        for (String key : keySet) {
            if (key.startsWith(cvPrefix)) {
                jsonObjectCV.put(key.substring(key.indexOf(cvPrefix) + cvPrefix.length()),
                        jsonObjectApplicazione.get(key));
            }
            if (key.startsWith(cnPrefix)) {
                jsonObjectCN.put(key.substring(key.indexOf(cnPrefix) + cnPrefix.length()),
                        jsonObjectApplicazione.get(key));
            }
        }

        jsonConfig.setRootClass(Connettore.class);
        Connettore cv = (Connettore) JSONObject.toBean(jsonObjectCV, jsonConfig);

        if (StringUtils.isNotEmpty(tipoSslVer)) {
            cv.setTipoSsl(EnumSslType.valueOf(tipoSslVer));
        }

        entry.setConnettoreVerifica(cv);

        Connettore cn = (Connettore) JSONObject.toBean(jsonObjectCN, jsonConfig);

        if (StringUtils.isNotEmpty(tipoSslNot)) {
            cn.setTipoSsl(EnumSslType.valueOf(tipoSslNot));
        }

        entry.setConnettoreNotifica(cn);

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