Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

/**
 * This function drives the initiating side of the context establishment
 * process. It is expected to be called in tandem with the
 * {@link #acceptSecContext(byte[], int, int) acceptSecContext} function.
 * <BR>/*w w  w  .  j a v a  2 s. co  m*/
 * The behavior of context establishment process can be modified by
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE},
 * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}, and
 * {@link GSSConstants#REJECT_LIMITED_PROXY GSSConstants.REJECT_LIMITED_PROXY}
 * context options. If the {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * option is set to {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL}
 * the context establishment process will be compatible with regular SSL
 * (no credential delegation support). If the option is set to
 * {@link GSIConstants#MODE_GSI GSIConstants.GSS_MODE_GSI}
 * credential delegation during context establishment process will performed.
 * The delegation type to be performed can be set using the
 * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}
 * context option. If the {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} option is enabled,
 * a peer presenting limited proxy credential will be automatically
 * rejected and the context establishment process will be aborted.
 *
 * @return a byte[] containing the token to be sent to the peer.
 *         null indicates that no token is generated (needs more data).
 */
public byte[] initSecContext(byte[] inBuff, int off, int len) throws GSSException {
    logger.debug("enter initSecContext");

    if (!this.conn) {
        this.role = INITIATE;

        logger.debug("enter initializing in initSecContext");

        if (this.anonymity || this.ctxCred.getName().isAnonymous()) {
            this.anonymity = true;
        } else {
            this.anonymity = false;

            setCredential();

            if (this.ctxCred.getUsage() != GSSCredential.INITIATE_ONLY
                    && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) {
                throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                        "badCredUsage");
            }
        }

        if (getCredDelegState()) {
            if (this.gssMode == GSIConstants.MODE_SSL) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT,
                        "initCtx00");
            }
            if (this.anonymity) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT,
                        "initCtx01");
            }
        }

        try {
            init(this.role);
        } catch (SSLException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.conn = true;
        logger.debug("done initializing in initSecContext");
    }

    // Unless explicitly disabled, check if delegation is
    // requested and expected target is null
    logger.debug("Require authz with delegation: " + this.requireAuthzWithDelegation);
    if (!Boolean.FALSE.equals(this.requireAuthzWithDelegation)) {

        if (this.expectedTargetName == null && getCredDelegState()) {
            throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx02");
        }
    }

    /*DEL
            this.out.reset();
            this.in.putToken(inBuff, off, len);
    */

    this.outByteBuff.clear();
    ByteBuffer inByteBuff;
    if (savedInBytes != null) {
        if (len > 0) {
            byte[] allInBytes = new byte[savedInBytes.length + len];
            logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n");
            System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length);
            System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len);
            inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length);
        } else {
            inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length);
        }
        savedInBytes = null;
    } else {
        inByteBuff = ByteBuffer.wrap(inBuff, off, len);
    }

    switch (state) {

    case HANDSHAKE:
        try {

            logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString());
            SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus();

            if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // return null;
                throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!");
            } else {
                outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff);
            }

            logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString());

            outByteBuff.flip();
            /*DEL
                            this.conn.getHandshake().processHandshake();
                            if (this.conn.getHandshake().finishedP()) {
            */
            if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // the wrap/unwrap above has resulted in handshaking
                // being complete on our end.
                logger.debug("initSecContext handshake finished");
                handshakeFinished();

                /*DEL
                                    Vector chain = this.conn.getCertificateChain();
                                    X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1);
                                    setGoodUntil(crt.getValidityNotAfter());
                */
                Certificate[] chain = this.sslEngine.getSession().getPeerCertificates();
                if (!(chain instanceof X509Certificate[])) {
                    throw new Exception("Certificate chain not of type X509Certificate");
                }

                for (X509Certificate cert : (X509Certificate[]) chain) {
                    setGoodUntil(cert.getNotAfter());
                }

                // acceptor - peer

                /*DEL
                                    String identity = verifyChain(chain);
                */
                // chain verification would have already been done by
                // JSSE

                String identity = BouncyCastleUtil.getIdentity(
                        bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain)));
                this.targetName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false));

                this.peerLimited = Boolean.valueOf(ProxyCertificateUtil
                        .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0])));

                logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName
                        + " Limited Proxy: " + this.peerLimited.toString());

                // initiator
                if (this.anonymity) {
                    this.sourceName = new GlobusGSSName();
                } else {
                    for (X509Certificate cert : this.ctxCred.getCertificateChain()) {
                        setGoodUntil(cert.getNotAfter());
                    }
                    this.sourceName = this.ctxCred.getName();
                }

                // mutual authentication test
                if (this.expectedTargetName != null && !this.expectedTargetName.equals(this.targetName)) {
                    throw new GlobusGSSException(GSSException.UNAUTHORIZED, GlobusGSSException.BAD_NAME,
                            "authFailed00", new Object[] { this.expectedTargetName, this.targetName });
                }

                if (this.gssMode == GSIConstants.MODE_GSI) {
                    this.state = CLIENT_START_DEL;
                    // if there is data to return then
                    // break. otherwise we fall through!!!
                    if (this.outByteBuff.remaining() > 0) {
                        break;
                    }
                } else {
                    setDone();
                    break;
                }

            } else {
                break;
            }
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

    case CLIENT_START_DEL:

        logger.debug("CLIENT_START_DEL");
        // sanity check - might be invalid state
        if (this.state != CLIENT_START_DEL || this.outByteBuff.remaining() > 0) {
            throw new GSSException(GSSException.FAILURE);
        }
        if (inByteBuff.hasRemaining()) {
            throw new GlobusGSSException(GSSException.FAILURE,
                    new Exception(
                            "Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                                    + " Handshaking status: " + sslEngine.getHandshakeStatus()));
        }
        this.outByteBuff.clear();

        try {
            String deleg;

            if (getCredDelegState()) {
                deleg = Character.toString(GSIConstants.DELEGATION_CHAR);
                this.state = CLIENT_END_DEL;
            } else {
                deleg = Character.toString('0');
                setDone();
            }

            byte[] a = deleg.getBytes("US-ASCII");
            inByteBuff = ByteBuffer.wrap(a, 0, a.length);
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        break;

    case CLIENT_END_DEL:

        logger.debug("CLIENT_END_DEL");
        if (!inByteBuff.hasRemaining()) {
            throw new GSSException(GSSException.DEFECTIVE_TOKEN);
        }

        ByteArrayInputStream byteArrayInputStream = null;
        try {
            /*DEL
                            if (this.in.available() <= 0) {
            return null;
                            }
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            if (!outByteBuff.hasRemaining())
                break;

            byte[] certReq = new byte[outByteBuff.remaining()];
            outByteBuff.get(certReq, 0, certReq.length);

            X509Certificate[] chain = this.ctxCred.getCertificateChain();

            byteArrayInputStream = new ByteArrayInputStream(certReq);
            X509Certificate cert = this.certFactory.createCertificate(byteArrayInputStream, chain[0],
                    this.ctxCred.getPrivateKey(), -1,
                    /*DEL
                                                       getDelegationType(chain[0]));
                    */
                    BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType));

            byte[] enc = cert.getEncoded();
            /*DEL
                            this.conn.getOutStream().write(enc, 0, enc.length);
            */
            inByteBuff = ByteBuffer.wrap(enc, 0, enc.length);
            outByteBuff.clear();
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

            setDone();
        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } finally {
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (Exception e) {
                    logger.warn("Unable to close stream.");
                }
            }
        }

        break;

    default:
        throw new GSSException(GSSException.FAILURE);
    }

    if (inByteBuff.hasRemaining()) {
        // Likely BUFFER_UNDERFLOW; save the
        // inByteBuff bytes here like in the unwrap() case
        logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                + " Handshaking status: " + sslEngine.getHandshakeStatus());
        logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n");
        savedInBytes = new byte[inByteBuff.remaining()];
        inByteBuff.get(savedInBytes, 0, savedInBytes.length);
    }

    logger.debug("exit initSecContext");
    //XXX: Why is here a check for CLIENT_START_DEL?
    // if (this.outByteBuff.hasRemaining() || this.state == CLIENT_START_DEL) {
    if (this.outByteBuff.hasRemaining()) {
        // TODO can we avoid this copy if the ByteBuffer is array based
        // and we return that array, each time allocating a new array
        // for outByteBuff?
        byte[] out = new byte[this.outByteBuff.remaining()];
        this.outByteBuff.get(out, 0, out.length);
        return out;
    } else
        return null;
}

From source file:com.inmobi.grill.driver.hive.HiveDriver.java

@Override
public synchronized void updateStatus(QueryContext context) throws GrillException {
    LOG.debug("GetStatus: " + context.getQueryHandle());
    if (context.getDriverStatus().isFinished()) {
        return;/*from ww  w.  j  a v a 2s  . c  o  m*/
    }
    OperationHandle hiveHandle = getHiveHandle(context.getQueryHandle());
    ByteArrayInputStream in = null;
    try {
        // Get operation status from hive server
        LOG.debug("GetStatus hiveHandle: " + hiveHandle);
        OperationStatus opStatus = getClient().getOperationStatus(hiveHandle);
        LOG.debug("GetStatus on hiveHandle: " + hiveHandle + " returned state:" + opStatus);

        switch (opStatus.getState()) {
        case CANCELED:
            context.getDriverStatus().setState(DriverQueryState.CANCELED);
            context.getDriverStatus().setStatusMessage("Query has been cancelled!");
            break;
        case CLOSED:
            context.getDriverStatus().setState(DriverQueryState.CLOSED);
            context.getDriverStatus().setStatusMessage("Query has been closed!");
            break;
        case ERROR:
            context.getDriverStatus().setState(DriverQueryState.FAILED);
            context.getDriverStatus().setStatusMessage(
                    "Query failed with errorCode:" + opStatus.getOperationException().getErrorCode()
                            + " with errorMessage: " + opStatus.getOperationException().getMessage());
            break;
        case FINISHED:
            context.getDriverStatus().setState(DriverQueryState.SUCCESSFUL);
            context.getDriverStatus().setStatusMessage("Query is successful!");
            context.getDriverStatus().setResultSetAvailable(hiveHandle.hasResultSet());
            break;
        case INITIALIZED:
            context.getDriverStatus().setState(DriverQueryState.INITIALIZED);
            context.getDriverStatus().setStatusMessage("Query is initiazed in HiveServer!");
            break;
        case RUNNING:
            context.getDriverStatus().setState(DriverQueryState.RUNNING);
            context.getDriverStatus().setStatusMessage("Query is running in HiveServer!");
            break;
        case PENDING:
            context.getDriverStatus().setState(DriverQueryState.PENDING);
            context.getDriverStatus().setStatusMessage("Query is pending in HiveServer");
            break;
        case UNKNOWN:
        default:
            throw new GrillException("Query is in unknown state at HiveServer");
        }

        float progress = 0f;
        String jsonTaskStatus = opStatus.getTaskStatus();
        String errorMsg = null;
        if (StringUtils.isNotBlank(jsonTaskStatus)) {
            ObjectMapper mapper = new ObjectMapper();
            in = new ByteArrayInputStream(jsonTaskStatus.getBytes("UTF-8"));
            List<TaskStatus> taskStatuses = mapper.readValue(in, new TypeReference<List<TaskStatus>>() {
            });
            int completedTasks = 0;
            StringBuilder errorMessage = new StringBuilder();
            for (TaskStatus taskStat : taskStatuses) {
                String tstate = taskStat.getTaskState();
                if ("FINISHED_STATE".equalsIgnoreCase(tstate)) {
                    completedTasks++;
                }
                if ("FAILED_STATE".equalsIgnoreCase(tstate)) {
                    appendTaskIds(errorMessage, taskStat);
                    errorMessage.append(" has failed! ");
                }
            }
            progress = taskStatuses.size() == 0 ? 0 : (float) completedTasks / taskStatuses.size();
            errorMsg = errorMessage.toString();
        } else {
            LOG.warn("Empty task statuses");
        }
        String error = null;
        if (StringUtils.isNotBlank(errorMsg)) {
            error = errorMsg;
        } else if (opStatus.getState().equals(OperationState.ERROR)) {
            error = context.getDriverStatus().getStatusMessage();
        }
        context.getDriverStatus().setErrorMessage(error);
        context.getDriverStatus().setProgressMessage(jsonTaskStatus);
        context.getDriverStatus().setProgress(progress);
        context.getDriverStatus().setDriverStartTime(opStatus.getOperationStarted());
        context.getDriverStatus().setDriverFinishTime(opStatus.getOperationCompleted());
    } catch (Exception e) {
        LOG.error("Error getting query status", e);
        throw new GrillException("Error getting query status", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.ejbca.ui.web.admin.rainterface.RAInterfaceBean.java

private EndEntityProfile getEEProfileFromByteArray(String profilename, byte[] profileBytes)
        throws AuthorizationDeniedException {

    ByteArrayInputStream is = new ByteArrayInputStream(profileBytes);
    EndEntityProfile eprofile = new EndEntityProfile();
    try {//from w  ww  .  j  av  a2  s  .  c  o  m
        XMLDecoder decoder = getXMLDecoder(is);

        // Add end entity profile
        Object data = null;
        try {
            data = decoder.readObject();
        } catch (IllegalArgumentException e) {
            if (log.isDebugEnabled()) {
                log.debug("IllegalArgumentException parsing certificate profile data: " + e.getMessage());
            }
            return null;
        }
        decoder.close();
        eprofile.loadData(data);

        // Translate cert profile ids that have changed after import
        String availableCertProfiles = "";
        String defaultCertProfile = eprofile.getValue(EndEntityProfile.DEFAULTCERTPROFILE, 0);
        for (String currentCertProfile : (Collection<String>) eprofile.getAvailableCertificateProfileIds()) {
            Integer currentCertProfileId = Integer.parseInt(currentCertProfile);

            if (certificateProfileSession.getCertificateProfile(currentCertProfileId) != null
                    || CertificateProfileConstants.isFixedCertificateProfile(currentCertProfileId)) {
                availableCertProfiles += (availableCertProfiles.equals("") ? "" : ";") + currentCertProfile;
            } else {
                log.warn("End Entity Profile '" + profilename + "' references certificate profile "
                        + currentCertProfile + " that does not exist.");
                if (currentCertProfile.equals(defaultCertProfile)) {
                    defaultCertProfile = "";
                }
            }
        }
        if (availableCertProfiles.equals("")) {
            log.warn(
                    "End Entity Profile only references certificate profile(s) that does not exist. Using ENDUSER profile.");
            availableCertProfiles = "1"; // At least make sure the default profile is available
        }
        if (defaultCertProfile.equals("")) {
            defaultCertProfile = availableCertProfiles.split(";")[0]; // Use first available profile from list as default if original default was missing
        }
        eprofile.setValue(EndEntityProfile.AVAILCERTPROFILES, 0, availableCertProfiles);
        eprofile.setValue(EndEntityProfile.DEFAULTCERTPROFILE, 0, defaultCertProfile);
        // Remove any unknown CA and break if none is left
        String defaultCA = eprofile.getValue(EndEntityProfile.DEFAULTCA, 0);
        String availableCAs = eprofile.getValue(EndEntityProfile.AVAILCAS, 0);
        List<String> cas = Arrays.asList(availableCAs.split(";"));
        availableCAs = "";
        for (String currentCA : cas) {
            Integer currentCAInt = Integer.parseInt(currentCA);
            // The constant ALLCAS will not be searched for among available CAs
            try {
                if (currentCAInt.intValue() != SecConst.ALLCAS) {
                    caSession.getCAInfo(administrator, currentCAInt);
                }
                availableCAs += (availableCAs.equals("") ? "" : ";") + currentCA; // No Exception means CA exists
            } catch (CADoesntExistsException e) {
                log.warn("CA with id " + currentCA
                        + " was not found and will not be used in end entity profile '" + profilename + "'.");
                if (defaultCA.equals(currentCA)) {
                    defaultCA = "";
                }
            }
        }
        if (availableCAs.equals("")) {
            log.error("No CAs left in end entity profile '" + profilename + "'. Using ALLCAs.");
            availableCAs = Integer.toString(SecConst.ALLCAS);
        }
        if (defaultCA.equals("")) {
            defaultCA = availableCAs.split(";")[0]; // Use first available
            log.warn("Changing default CA in end entity profile '" + profilename + "' to " + defaultCA + ".");
        }
        eprofile.setValue(EndEntityProfile.AVAILCAS, 0, availableCAs);
        eprofile.setValue(EndEntityProfile.DEFAULTCA, 0, defaultCA);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unknown IOException was caught when closing stream", e);
        }
    }
    return eprofile;
}

From source file:bookkeepr.jettyhandlers.WebHandler.java

public void handle(String path, HttpServletRequest request, HttpServletResponse response, int dispatch)
        throws IOException, ServletException {
    if (path.equals("/")) {
        response.sendRedirect("/web/");
    }//from  w  w w. j  a v a 2s . c o m

    HttpClient httpclient = null;
    if (path.startsWith("/web/xmlify")) {
        ((Request) request).setHandled(true);
        if (request.getMethod().equals("POST")) {
            try {
                String remotePath = path.substring(11);

                BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
                XMLAble xmlable = null;
                try {
                    xmlable = httpForm2XmlAble(reader.readLine());
                } catch (BookKeeprException ex) {
                    response.sendError(400,
                            "Server could not form xml from the form data you submitted. " + ex.getMessage());
                    return;
                }
                if (xmlable == null) {
                    response.sendError(500,
                            "Server could not form xml from the form data you submitted. The server created a null value!");
                    return;

                }
                //                    XMLWriter.write(System.out, xmlable);
                //                    if(true)return;

                HttpPost httppost = new HttpPost(bookkeepr.getConfig().getExternalUrl() + remotePath);
                httppost.getParams().setBooleanParameter("http.protocol.strict-transfer-encoding", false);

                ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                XMLWriter.write(out, xmlable);
                ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
                httppost.setEntity(new InputStreamEntity(in, -1));
                Logger.getLogger(WebHandler.class.getName()).log(Level.INFO,
                        "Xmlifier posting to " + bookkeepr.getConfig().getExternalUrl() + remotePath);

                httpclient = bookkeepr.checkoutHttpClient();
                HttpResponse httpresp = httpclient.execute(httppost);
                for (Header head : httpresp.getAllHeaders()) {
                    if (head.getName().equalsIgnoreCase("transfer-encoding")) {
                        continue;
                    }
                    response.setHeader(head.getName(), head.getValue());
                }
                response.setStatus(httpresp.getStatusLine().getStatusCode());

                httpresp.getEntity().writeTo(response.getOutputStream());

            } catch (HttpException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                        "HttpException " + ex.getMessage(), ex);
                response.sendError(500, ex.getMessage());

            } catch (URISyntaxException ex) {
                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING, ex.getMessage(), ex);
                response.sendError(400, "Invalid target URI");
            } finally {
                if (httpclient != null) {
                    bookkeepr.returnHttpClient(httpclient);
                }
            }

        }
        return;
    }

    if (request.getMethod().equals("GET")) {
        if (path.startsWith("/web")) {
            ((Request) request).setHandled(true);

            if (badchar.matcher(path).matches()) {
                response.sendError(400, "User Error");
                return;
            }
            String localpath = path.substring(4);
            Logger.getLogger(WebHandler.class.getName()).log(Level.FINE,
                    "Transmitting " + localroot + localpath);
            File targetFile = new File(localroot + localpath);
            if (targetFile.isDirectory()) {
                if (path.endsWith("/")) {
                    targetFile = new File(localroot + localpath + "index.html");
                } else {
                    response.sendRedirect(path + "/");
                    return;
                }
            }
            if (targetFile.exists()) {
                if (targetFile.getName().endsWith(".html") || targetFile.getName().endsWith(".xsl")) {
                    BufferedReader in = new BufferedReader(new FileReader(targetFile));
                    PrintStream out = null;
                    String hdr = request.getHeader("Accept-Encoding");
                    if (hdr != null && hdr.contains("gzip")) {
                        // if the host supports gzip encoding, gzip the output for quick transfer speed.
                        out = new PrintStream(new GZIPOutputStream(response.getOutputStream()));
                        response.setHeader("Content-Encoding", "gzip");
                    } else {
                        out = new PrintStream(response.getOutputStream());
                    }
                    String line = in.readLine();
                    while (line != null) {
                        if (line.trim().startsWith("%%%")) {
                            BufferedReader wrapper = new BufferedReader(
                                    new FileReader(localroot + "/wrap/" + line.trim().substring(3) + ".html"));
                            String line2 = wrapper.readLine();
                            while (line2 != null) {
                                out.println(line2);
                                line2 = wrapper.readLine();
                            }
                            wrapper.close();
                        } else if (line.trim().startsWith("***chooser")) {
                            String[] elems = line.trim().split("\\s");
                            try {
                                int type = TypeIdManager
                                        .getTypeFromClass(Class.forName("bookkeepr.xmlable." + elems[1]));
                                List<IdAble> items = this.bookkeepr.getMasterDatabaseManager()
                                        .getAllOfType(type);
                                out.printf("<select name='%sId'>\n", elems[1]);
                                for (IdAble item : items) {
                                    out.printf("<option value='%x'>%s</option>", item.getId(), item.toString());
                                }
                                out.println("</select>");

                            } catch (Exception e) {
                                Logger.getLogger(WebHandler.class.getName()).log(Level.WARNING,
                                        "Could not make a type ID for " + line.trim());
                            }
                        } else {

                            out.println(line);
                        }
                        line = in.readLine();
                    }
                    in.close();
                    out.close();
                } else {
                    outputToInput(new FileInputStream(targetFile), response.getOutputStream());
                }

            } else {
                response.sendError(HttpStatus.SC_NOT_FOUND);
            }
        }
    }
}

From source file:org.jlibrary.core.jcr.JCRRepositoryService.java

private javax.jcr.Node internalCreateDocument(javax.jcr.Session session, Ticket ticket,
        DocumentProperties properties, InputStream contentStream)
        throws RepositoryException, SecurityException {

    ByteArrayInputStream bais = null;
    try {/*from w w w. ja  v  a 2s .  com*/
        String parentId = (String) properties.getProperty(DocumentProperties.DOCUMENT_PARENT).getValue();
        String name = ((String) properties.getProperty(DocumentProperties.DOCUMENT_NAME).getValue());
        String path = ((String) properties.getProperty(DocumentProperties.DOCUMENT_PATH).getValue());
        String extension = FileUtils.getExtension(path);
        String description = ((String) properties.getProperty(DocumentProperties.DOCUMENT_DESCRIPTION)
                .getValue());
        Integer typecode = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_TYPECODE).getValue());
        Integer position = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_POSITION).getValue());
        Integer importance = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_IMPORTANCE)
                .getValue());
        String title = (String) properties.getProperty(DocumentProperties.DOCUMENT_TITLE).getValue();
        String url = ((String) properties.getProperty(DocumentProperties.DOCUMENT_URL).getValue());
        String language = ((String) properties.getProperty(DocumentProperties.DOCUMENT_LANGUAGE).getValue());
        Author author = ((Author) properties.getProperty(DocumentProperties.DOCUMENT_AUTHOR).getValue());
        Date metadataDate = ((Date) properties.getProperty(DocumentProperties.DOCUMENT_CREATION_DATE)
                .getValue());
        Calendar date = Calendar.getInstance();
        date.setTime(metadataDate);

        String keywords = ((String) properties.getProperty(DocumentProperties.DOCUMENT_KEYWORDS).getValue());

        javax.jcr.Node parent = session.getNodeByUUID(parentId);

        if (!JCRSecurityService.canWrite(parent, ticket.getUser().getId())) {
            throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
        }
        String escapedName = JCRUtils.buildValidChildNodeName(parent, extension, name);
        name = Text.unescape(escapedName);
        if ((extension != null) && !escapedName.endsWith(extension)) {
            escapedName += extension;
        }

        javax.jcr.Node child = parent.addNode(escapedName, JCRConstants.JCR_FILE);

        child.addMixin(JCRConstants.JCR_REFERENCEABLE);
        child.addMixin(JCRConstants.JCR_LOCKABLE);
        child.addMixin(JCRConstants.JCR_VERSIONABLE);
        child.addMixin(JLibraryConstants.DOCUMENT_MIXIN);

        child.setProperty(JLibraryConstants.JLIBRARY_NAME, name);
        child.setProperty(JLibraryConstants.JLIBRARY_DESCRIPTION, description);
        child.setProperty(JLibraryConstants.JLIBRARY_CREATED, Calendar.getInstance());
        child.setProperty(JLibraryConstants.JLIBRARY_IMPORTANCE, importance.longValue());
        child.setProperty(JLibraryConstants.JLIBRARY_CREATOR, ticket.getUser().getId());
        child.setProperty(JLibraryConstants.JLIBRARY_TYPECODE, typecode.longValue());
        child.setProperty(JLibraryConstants.JLIBRARY_POSITION, position.longValue());

        child.setProperty(JLibraryConstants.JLIBRARY_TITLE, title);
        child.setProperty(JLibraryConstants.JLIBRARY_DOCUMENT_URL, url);
        child.setProperty(JLibraryConstants.JLIBRARY_KEYWORDS, keywords);
        child.setProperty(JLibraryConstants.JLIBRARY_LANGUAGE, language);
        child.setProperty(JLibraryConstants.JLIBRARY_CREATION_DATE, date);

        child.setProperty(JLibraryConstants.JLIBRARY_PATH, getPath(parent) + FileUtils.getFileName(path));

        // Handle authors
        if (author.equals(Author.UNKNOWN)) {
            child.setProperty(JLibraryConstants.JLIBRARY_AUTHOR, authorsModule.findUnknownAuthor(ticket));
        } else {
            javax.jcr.Node authorNode = session.getNodeByUUID(author.getId());
            child.setProperty(JLibraryConstants.JLIBRARY_AUTHOR, authorNode.getUUID());
        }

        // Handle document categories
        child.setProperty(JLibraryConstants.JLIBRARY_CATEGORIES, new Value[] {});
        PropertyDef[] categories = properties.getPropertyList(DocumentProperties.DOCUMENT_ADD_CATEGORY);
        if (categories != null) {
            for (int i = 0; i < categories.length; i++) {
                String category = (String) categories[i].getValue();
                javax.jcr.Node categoryNode = categoriesModule.getCategoryNode(session, category);
                categoriesModule.addCategory(ticket, categoryNode, child);
            }
        } else {
            categoriesModule.addUnknownCategory(ticket, child);
        }

        // Handle document relations
        child.setProperty(JLibraryConstants.JLIBRARY_RELATIONS, new Value[] {});

        // Handle document restrictions
        child.setProperty(JLibraryConstants.JLIBRARY_RESTRICTIONS, new Value[] {});
        javax.jcr.Node userNode = JCRSecurityService.getUserNode(session, ticket.getUser().getId());
        addRestrictionsToNode(child, parent, userNode);

        // Handle document resources. 
        child.setProperty(JLibraryConstants.JLIBRARY_RESOURCES, new Value[] {});

        javax.jcr.Node resNode = child.addNode(JcrConstants.JCR_CONTENT, JCRConstants.JCR_RESOURCE);
        resNode.addMixin(JLibraryConstants.CONTENT_MIXIN);

        InputStream streamToSet;
        if (contentStream == null) {
            byte[] content = (byte[]) properties.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue();
            if (content == null) {
                // Empty file
                content = new byte[] {};
            }
            bais = new ByteArrayInputStream(content);
            streamToSet = bais;
        } else {
            streamToSet = contentStream;
        }

        //TODO: Handle encoding
        String mimeType = Types.getMimeTypeForExtension(FileUtils.getExtension(path));
        resNode.setProperty(JCRConstants.JCR_MIME_TYPE, mimeType);
        resNode.setProperty(JCRConstants.JCR_ENCODING, JCRConstants.DEFAULT_ENCODING);
        resNode.setProperty(JCRConstants.JCR_DATA, streamToSet);
        Calendar lastModified = Calendar.getInstance();
        lastModified.setTimeInMillis(new Date().getTime());
        resNode.setProperty(JCRConstants.JCR_LAST_MODIFIED, lastModified);

        child.setProperty(JLibraryConstants.JLIBRARY_SIZE,
                resNode.getProperty(JCRConstants.JCR_DATA).getLength());

        return child;
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
                throw new RepositoryException(ioe);
            }
        }
    }
}

From source file:org.exoplatform.forum.service.impl.JCRDataStorage.java

public void importXML(String nodePath, ByteArrayInputStream bis, int typeImport) throws Exception {
    String nodeName = "";
    byte[] bdata = new byte[bis.available()];
    bis.read(bdata);//from  w ww .  j  av  a2 s  .  c  o m
    DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
    ByteArrayInputStream is = new ByteArrayInputStream(bdata);
    Document doc = docBuilder.parse(is);
    doc.getDocumentElement().normalize();
    String typeNodeExport = ((org.w3c.dom.Node) doc.getFirstChild().getChildNodes().item(0).getChildNodes()
            .item(0)).getTextContent();
    SessionProvider sProvider = CommonUtils.createSystemProvider();
    List<String> patchNodeImport = new ArrayList<String>();
    try {
        Node forumHome = getForumHomeNode(sProvider);
        is = new ByteArrayInputStream(bdata);
        if (!typeNodeExport.equals(EXO_FORUM_CATEGORY) && !typeNodeExport.equals(EXO_FORUM)) {
            // All nodes when import need reset childnode
            if (typeNodeExport.equals(EXO_CATEGORY_HOME)) {
                nodePath = getCategoryHome(sProvider).getPath();
                Node categoryHome = getCategoryHome(sProvider);
                nodeName = "CategoryHome";
                addDataFromXML(categoryHome, nodePath, sProvider, is, nodeName);
            } else if (typeNodeExport.equals(EXO_USER_PROFILE_HOME)) {
                Node userProfile = getUserProfileHome(sProvider);
                nodeName = "UserProfileHome";
                nodePath = getUserProfileHome(sProvider).getPath();
                addDataFromXML(userProfile, nodePath, sProvider, is, nodeName);
            } else if (typeNodeExport.equals(EXO_TAG_HOME)) {
                Node tagHome = getTagHome(sProvider);
                nodePath = getTagHome(sProvider).getPath();
                nodeName = "TagHome";
                addDataFromXML(tagHome, nodePath, sProvider, is, nodeName);
            } else if (typeNodeExport.equals(EXO_FORUM_BB_CODE_HOME)) {
                nodePath = dataLocator.getBBCodesLocation();
                Node bbcodeNode = getBBCodesHome(sProvider);
                nodeName = "forumBBCode";
                addDataFromXML(bbcodeNode, nodePath, sProvider, is, nodeName);
            }
            // Node import but don't need reset childnodes
            else if (typeNodeExport.equals(EXO_ADMINISTRATION_HOME)) {
                nodePath = getForumSystemHome(sProvider).getPath();
                Node node = getAdminHome(sProvider);
                node.remove();
                getForumSystemHome(sProvider).save();
                typeImport = ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING;
                Session session = forumHome.getSession();
                session.importXML(nodePath, is, typeImport);
                session.save();
            } else if (typeNodeExport.equals(EXO_BAN_IP_HOME)) {
                nodePath = getForumSystemHome(sProvider).getPath();
                Node node = getBanIPHome(sProvider);
                node.remove();
                getForumSystemHome(sProvider).save();
                typeImport = ImportUUIDBehavior.IMPORT_UUID_COLLISION_REPLACE_EXISTING;
                Session session = forumHome.getSession();
                session.importXML(nodePath, is, typeImport);
                session.save();
            } else {
                throw new RuntimeException("unknown type of node to export :" + typeNodeExport);
            }
        } else {
            if (typeNodeExport.equals(EXO_FORUM_CATEGORY)) {
                // Check if import forum but the data import have structure of a category --> Error
                if (nodePath.split("/").length == 6) {
                    throw new ConstraintViolationException();
                }

                nodePath = getCategoryHome(sProvider).getPath();
            }

            Session session = forumHome.getSession();
            NodeIterator iter = ((Node) session.getItem(nodePath)).getNodes();
            while (iter.hasNext()) {
                patchNodeImport.add(iter.nextNode().getName());
            }
            session.importXML(nodePath, is, typeImport);
            session.save();
            NodeIterator newIter = ((Node) session.getItem(nodePath)).getNodes();
            while (newIter.hasNext()) {
                Node node = newIter.nextNode();
                if (patchNodeImport.contains(node.getName()))
                    patchNodeImport.remove(node.getName());
                else
                    patchNodeImport.add(node.getName());
            }
        }
        // update forum statistic and profile of owner post.
        if (typeNodeExport.equals(EXO_FORUM_CATEGORY) || typeNodeExport.equals(EXO_FORUM)) {
            for (String string : patchNodeImport) {
                updateForum(nodePath + "/" + string, false);
            }
        } else if (typeNodeExport.equals(EXO_CATEGORY_HOME)) {
            updateForum(null);
        }
    } finally {
        is.close();
    }
}

From source file:org.jlibrary.core.jcr.JCRRepositoryService.java

public Document updateDocument(Ticket ticket, DocumentProperties properties, InputStream contentStream)
        throws RepositoryException, SecurityException, ResourceLockedException {

    // TODO: Check name updates with new code

    ByteArrayInputStream bais = null;
    try {//  ww  w.j  a v  a  2 s .  c  om
        String docId = (String) properties.getProperty(DocumentProperties.DOCUMENT_ID).getValue();
        String parentId = (String) properties.getProperty(DocumentProperties.DOCUMENT_PARENT).getValue();
        String name = ((String) properties.getProperty(DocumentProperties.DOCUMENT_NAME).getValue());
        String description = ((String) properties.getProperty(DocumentProperties.DOCUMENT_DESCRIPTION)
                .getValue());
        Integer typecode = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_TYPECODE).getValue());
        Integer position = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_POSITION).getValue());
        Integer importance = ((Integer) properties.getProperty(DocumentProperties.DOCUMENT_IMPORTANCE)
                .getValue());
        String title = (String) properties.getProperty(DocumentProperties.DOCUMENT_TITLE).getValue();
        String url = ((String) properties.getProperty(DocumentProperties.DOCUMENT_URL).getValue());
        String language = ((String) properties.getProperty(DocumentProperties.DOCUMENT_LANGUAGE).getValue());
        Author author = ((Author) properties.getProperty(DocumentProperties.DOCUMENT_AUTHOR).getValue());
        Date metadataDate = ((Date) properties.getProperty(DocumentProperties.DOCUMENT_CREATION_DATE)
                .getValue());
        Calendar date = Calendar.getInstance();
        date.setTime(metadataDate);

        String keywords = ((String) properties.getProperty(DocumentProperties.DOCUMENT_KEYWORDS).getValue());

        SessionManager manager = SessionManager.getInstance();
        Session session = manager.getSession(ticket);

        javax.jcr.Node node = session.getNodeByUUID(docId);
        if (!JCRSecurityService.canWrite(node, ticket.getUser().getId())) {
            throw new SecurityException(SecurityException.NOT_ENOUGH_PERMISSIONS);
        }

        Object syncLock = LockUtility.obtainLock(node);
        synchronized (syncLock) {
            locksModule.checkLockAccess(ticket, node);

            JCRUtils.checkinIfNecessary(node);

            node.checkout();

            node.setProperty(JLibraryConstants.JLIBRARY_DESCRIPTION, description);
            node.setProperty(JLibraryConstants.JLIBRARY_CREATED, Calendar.getInstance());
            node.setProperty(JLibraryConstants.JLIBRARY_IMPORTANCE, importance.longValue());
            node.setProperty(JLibraryConstants.JLIBRARY_CREATOR, ticket.getUser().getId());
            node.setProperty(JLibraryConstants.JLIBRARY_TYPECODE, typecode.longValue());
            node.setProperty(JLibraryConstants.JLIBRARY_POSITION, position.longValue());

            node.setProperty(JLibraryConstants.JLIBRARY_TITLE, title);
            node.setProperty(JLibraryConstants.JLIBRARY_DOCUMENT_URL, url);
            node.setProperty(JLibraryConstants.JLIBRARY_KEYWORDS, keywords);
            node.setProperty(JLibraryConstants.JLIBRARY_LANGUAGE, language);
            node.setProperty(JLibraryConstants.JLIBRARY_CREATION_DATE, date);

            //Handle relations         
            PropertyDef[] relations = properties.getPropertyList(DocumentProperties.DOCUMENT_DELETE_RELATION);
            if (relations != null) {
                for (int i = 0; i < relations.length; i++) {
                    Relation relation = (Relation) relations[i].getValue();
                    String destinationId = relation.getDestinationNode().getId();

                    JCRUtils.removeNodeFromProperty(destinationId, node, JLibraryConstants.JLIBRARY_RELATIONS);
                    if (relation.isBidirectional()) {
                        javax.jcr.Node referencedNode = session.getNodeByUUID(destinationId);
                        JCRUtils.removeNodeFromProperty(node.getUUID(), referencedNode,
                                JLibraryConstants.JLIBRARY_RELATIONS);

                    }
                }
            }

            relations = properties.getPropertyList(DocumentProperties.DOCUMENT_ADD_RELATION);
            if (relations != null) {
                for (int i = 0; i < relations.length; i++) {
                    Relation relation = (Relation) relations[i].getValue();
                    String destinationId = relation.getDestinationNode().getId();

                    JCRUtils.addNodeToProperty(destinationId, node, JLibraryConstants.JLIBRARY_RELATIONS);
                    if (relation.isBidirectional()) {
                        javax.jcr.Node referencedNode = session.getNodeByUUID(destinationId);
                        JCRUtils.addNodeToProperty(node.getUUID(), referencedNode,
                                JLibraryConstants.JLIBRARY_RELATIONS);

                    }
                }
            }

            //Handle authors
            if (author.equals(Author.UNKNOWN)) {
                node.setProperty(JLibraryConstants.JLIBRARY_AUTHOR, authorsModule.findUnknownAuthor(ticket));
            } else {
                javax.jcr.Node authorNode = session.getNodeByUUID(author.getId());
                node.setProperty(JLibraryConstants.JLIBRARY_AUTHOR, authorNode.getUUID());
            }

            // Handle document categories
            PropertyDef[] categories = properties.getPropertyList(DocumentProperties.DOCUMENT_DELETE_CATEGORY);
            if (categories != null) {
                for (int i = 0; i < categories.length; i++) {
                    String category = (String) categories[i].getValue();
                    javax.jcr.Node categoryNode = categoriesModule.getCategoryNode(session, category);
                    categoriesModule.removeCategory(ticket, categoryNode, node);
                }
                if (categoriesModule.numberOfCategories(node) == 0) {
                    categoriesModule.addUnknownCategory(ticket, node);
                }
            }

            categories = properties.getPropertyList(DocumentProperties.DOCUMENT_ADD_CATEGORY);
            if (categories != null) {
                if (categoriesModule.containsUnknownCategory(ticket, node)) {
                    categoriesModule.removeUnknownCategory(ticket, node);
                }
                for (int i = 0; i < categories.length; i++) {
                    String category = (String) categories[i].getValue();
                    javax.jcr.Node categoryNode = categoriesModule.getCategoryNode(session, category);
                    categoriesModule.addCategory(ticket, categoryNode, node);
                }
            }

            // Handle document notes
            PropertyDef[] notes = properties.getPropertyList(DocumentProperties.DOCUMENT_ADD_NOTE);
            if (notes != null) {
                javax.jcr.Node userNode = JCRSecurityService.getUserNode(session, ticket.getUser().getId());
                for (int i = 0; i < notes.length; i++) {
                    Note note = (Note) notes[i].getValue();
                    javax.jcr.Node noteNode = node.addNode(JLibraryConstants.JLIBRARY_NOTE,
                            JLibraryConstants.NOTE_MIXIN);
                    noteNode.addMixin(JCRConstants.JCR_REFERENCEABLE);
                    Calendar noteDate = Calendar.getInstance();
                    noteDate.setTime(new Date());

                    noteNode.setProperty(JLibraryConstants.JLIBRARY_DATE, noteDate);
                    noteNode.setProperty(JLibraryConstants.JLIBRARY_TEXT, note.getNote());
                    noteNode.setProperty(JLibraryConstants.JLIBRARY_USER, userNode.getUUID());
                }
            }

            notes = properties.getPropertyList(DocumentProperties.DOCUMENT_UPDATE_NOTE);
            if (notes != null) {
                for (int i = 0; i < notes.length; i++) {
                    Note note = (Note) notes[i].getValue();
                    javax.jcr.Node noteNode = session.getNodeByUUID(note.getId());
                    Calendar noteDate = Calendar.getInstance();
                    noteDate.setTime(new Date());

                    noteNode.setProperty(JLibraryConstants.JLIBRARY_DATE, noteDate);
                    noteNode.setProperty(JLibraryConstants.JLIBRARY_TEXT, note.getNote());
                    noteNode.setProperty(JLibraryConstants.JLIBRARY_USER, ticket.getUser().getId());
                }
            }

            notes = properties.getPropertyList(DocumentProperties.DOCUMENT_DELETE_NOTE);
            if (notes != null) {
                for (int i = 0; i < notes.length; i++) {
                    Note note = (Note) notes[i].getValue();
                    NodeIterator it = node.getNodes();
                    while (it.hasNext()) {
                        javax.jcr.Node childNode = (javax.jcr.Node) it.next();
                        if (childNode.isNodeType(JLibraryConstants.NOTE_MIXIN)) {
                            String noteId = childNode.getUUID();
                            if (noteId.equals(note.getId())) {
                                childNode.remove();
                            }
                        }
                    }
                }
            }

            // Handle custom properties
            List customProperties = properties.getCustomProperties();
            Iterator it = customProperties.iterator();
            while (it.hasNext()) {
                PropertyDef property = (PropertyDef) it.next();
                node.setProperty(property.getKey().toString(), JCRUtils.getValue(property.getValue()));
            }

            // Handle content
            byte[] content = null;
            if (properties.getProperty(DocumentProperties.DOCUMENT_CONTENT) != null) {
                content = (byte[]) properties.getProperty(DocumentProperties.DOCUMENT_CONTENT).getValue();
            }
            if (contentStream != null || content != null) {
                // need to update content too
                javax.jcr.Node child = node.getNode(JCRConstants.JCR_CONTENT);

                InputStream streamToSet;
                if (contentStream == null) {
                    bais = new ByteArrayInputStream(content);
                    streamToSet = bais;
                } else {
                    streamToSet = contentStream;
                }
                String path = node.getProperty(JLibraryConstants.JLIBRARY_PATH).getString();
                String mimeType = Types.getMimeTypeForExtension(FileUtils.getExtension(path));
                child.setProperty(JCRConstants.JCR_MIME_TYPE, mimeType);
                child.setProperty(JCRConstants.JCR_ENCODING, JCRConstants.DEFAULT_ENCODING);
                child.setProperty(JCRConstants.JCR_DATA, streamToSet);
                Calendar lastModified = Calendar.getInstance();
                lastModified.setTimeInMillis(new Date().getTime());
                child.setProperty(JCRConstants.JCR_LAST_MODIFIED, lastModified);

                node.setProperty(JLibraryConstants.JLIBRARY_SIZE,
                        child.getProperty(JCRConstants.JCR_DATA).getLength());
            }

            String previousName = node.getProperty(JLibraryConstants.JLIBRARY_NAME).getString();
            if (!previousName.equals(name)) {
                String path = node.getProperty(JLibraryConstants.JLIBRARY_NAME).getString();
                String extension = FileUtils.getExtension(path);
                String escapedName = JCRUtils.buildValidChildNodeName(node.getParent(), extension, name);
                if ((extension != null) && !escapedName.endsWith(extension)) {
                    escapedName += extension;
                }
                name = Text.unescape(escapedName);
                node.setProperty(JLibraryConstants.JLIBRARY_NAME, name);
                session.move(node.getPath(), node.getParent().getPath() + "/" + escapedName);
            }

            if (ticket.isAutocommit()) {
                SaveUtils.safeSaveSession(session);
            }

            // create first version
            node.checkin();
            // restore to read-write state
            node.checkout();
        }

        javax.jcr.Node root = JCRUtils.getRootNode(session);
        return JCRAdapter.createDocument(node, parentId, root.getUUID());
    } catch (Throwable e) {
        logger.error(e.getMessage(), e);
        throw new RepositoryException(e);
    } finally {
        if (bais != null) {
            try {
                bais.close();
            } catch (IOException ioe) {
                logger.error(ioe.getMessage(), ioe);
                throw new RepositoryException(ioe);
            }
        }
    }

}

From source file:jp.co.opentone.bsol.linkbinder.service.correspon.impl.CorresponSearchServiceImplTest.java

/**
 * ZIP?./*w w w.ja  v a  2  s.c  o  m*/
 */
@Test
public void testGenerateZip() throws Exception {
    MockAbstractService.RET_CURRENT_PROJECT_ID = "PJ1";

    //  ?????
    //  ???????????
    //  ????
    Correspon noNotAssigned = new Correspon();
    PropertyUtils.copyProperties(noNotAssigned, list.get(list.size() - 1));
    noNotAssigned.setCorresponNo(null);
    noNotAssigned.setId(Long.valueOf(list.size() + 1));

    list.add(noNotAssigned);

    Correspon c = new Correspon();
    c.setId(7L);
    c.setCorresponNo("YOC:OT:BUILDING-00007");
    CorresponGroup from = new CorresponGroup();
    from.setId(new Long(6L));
    from.setName("YOC:BUILDING");
    c.setFromCorresponGroup(from);
    c.setSubject("Mock");
    List<AddressCorresponGroup> addressGroups = new ArrayList<AddressCorresponGroup>();
    AddressCorresponGroup addressGroup = new AddressCorresponGroup();
    CorresponGroup group = new CorresponGroup();
    group.setId(2L);
    group.setName("YOC:IT");
    addressGroup.setCorresponGroup(group);
    addressGroup.setAddressType(AddressType.TO);
    addressGroups.add(addressGroup);
    addressGroup = new AddressCorresponGroup();
    group = new CorresponGroup();
    group.setId(2L);
    group.setName("TOK:BUILDING");
    addressGroup.setCorresponGroup(group);
    addressGroup.setAddressType(AddressType.CC);
    addressGroups.add(addressGroup);
    c.setAddressCorresponGroups(addressGroups);
    CorresponType ct = new CorresponType();
    ct.setId(new Long(1L));
    ct.setCorresponType("Request");
    c.setCorresponType(ct);
    c.setWorkflowStatus(WorkflowStatus.ISSUED);
    c.setIssuedAt(new GregorianCalendar(2009, 3, 5, 1, 1, 1).getTime());
    c.setCreatedAt(new GregorianCalendar(2009, 3, 1, 1, 1, 1).getTime());
    c.setUpdatedAt(new GregorianCalendar(2009, 3, 10, 10, 10, 10).getTime());
    User u = new User();
    u.setEmpNo("00001");
    u.setNameE("Test User");
    c.setIssuedBy(u);
    c.setCreatedBy(u);
    c.setUpdatedBy(u);
    c.setCorresponStatus(CorresponStatus.OPEN);
    c.setCustomField1Label("FIELD1");
    c.setCustomField1Value("VALUE1");
    c.setCustomField2Label("FIELD2");
    c.setCustomField2Value("VALUE2");
    c.setCustomField3Label("FIELD3");
    c.setCustomField3Value("VALUE3");
    c.setCustomField4Label("FIELD4");
    c.setCustomField4Value("VALUE4");
    c.setCustomField5Label("FIELD5");
    c.setCustomField5Value("VALUE5");
    c.setCustomField6Label("FIELD6");
    c.setCustomField6Value("VALUE6");
    c.setCustomField7Label("FIELD7");
    c.setCustomField7Value("VALUE7");
    c.setCustomField8Label("FIELD8");
    c.setCustomField8Value("VALUE8");
    c.setCustomField9Label("FIELD9");
    c.setCustomField9Value("VALUE9");
    c.setCustomField10Label("FIELD10");
    c.setCustomField10Value("VALUE10");
    c.setWorkflows(new ArrayList<Workflow>());
    c.setPreviousRevCorresponId(null);
    group = new CorresponGroup();
    group.setName("YOC:IT");
    c.setToCorresponGroup(group);
    c.setToCorresponGroupCount(2L);
    c.setIssuedAt(null);
    c.setIssuedBy(null);
    c.setReplyRequired(null);
    c.setDeadlineForReply(null);
    list.add(c);

    MockCorresponService.RET_FIND = list;
    MockAbstractService.CORRESPONS = list;
    byte[] actual = service.generateZip(list);

    ByteArrayInputStream bi = new ByteArrayInputStream(actual);
    ZipInputStream zis = new ZipInputStream(bi);
    byte[] b = new byte[1024];
    StringBuilder sb = new StringBuilder();
    String[] expFileNames = { "PJ1_YOC-OT-BUILDING-00001(0000000001).html",
            "PJ1_YOC-OT-BUILDING-00002(0000000002).html", "PJ1_YOC-OT-BUILDING-00003(0000000003).html",
            "PJ1_YOC-OT-BUILDING-00001-001(0000000004).html", "PJ1_YOC-OT-BUILDING-00001-002(0000000005).html",
            "PJ1_(0000000006).html", "PJ1_YOC-OT-BUILDING-00007(0000000007).html" };
    int index = 0;
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat f2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
        for (ZipEntry ze = zis.getNextEntry(); ze != null; ze = zis.getNextEntry()) {
            String expFileName = expFileNames[index];
            assertEquals(expFileName, ze.getName());
            if (ze.isDirectory()) {
                continue;
            }

            c = list.get(index);
            int i;
            while ((i = zis.read(b, 0, b.length)) != -1) {
                sb.append(new String(b, 0, i));
            }
            String html = sb.toString();

            // ??script????????
            assertTrue(html.contains("<body>"));
            assertFalse(html.contains(">Print</a>"));
            assertFalse(html.contains(">Close</a>"));

            // ???
            assertTrue(c.getId().toString(), html.contains(getExpectedString(c.getId().toString())));
            assertTrue(c.getCorresponStatus().getLabel(),
                    html.contains(getExpectedHTMLString(c.getCorresponStatus().getLabel())));

            //  ?????
            //  ?????????
            if (c.getCorresponNo() == null) {
                assertTrue(c.getCorresponNo(),
                        html.contains(getExpectedHTMLString(CorresponPageFormatter.DEFAULT_CORRESPON_NO)));
            } else {
                assertTrue(c.getCorresponNo(), html.contains(getExpectedHTMLString(c.getCorresponNo())));
            }

            assertTrue(c.getWorkflowStatus().getLabel(),
                    html.contains(getExpectedHTMLString(c.getWorkflowStatus().getLabel())));
            if (c.getParentCorresponId() != null) {
                assertTrue(c.getParentCorresponNo(),
                        html.contains(getExpectedHTMLString(c.getParentCorresponNo())));
            }
            if (c.getPreviousRevCorresponId() != null) {
                assertTrue(c.getPreviousRevCorresponNo(),
                        html.contains(getExpectedHTMLString(c.getPreviousRevCorresponNo())));
            }
            assertTrue(c.getFromCorresponGroup().getName() + " " + index,
                    html.contains(getExpectedString(c.getFromCorresponGroup().getName())));
            if (c.getAddressCorresponGroups() != null) {
                for (AddressCorresponGroup addressCorresponGroup : c.getAddressCorresponGroups()) {
                    assertTrue(addressCorresponGroup.getCorresponGroup().getName(),
                            html.contains(addressCorresponGroup.getCorresponGroup().getName()));
                    if (addressCorresponGroup.getUsers() == null) {
                        continue;
                    }
                    for (AddressUser aUser : addressCorresponGroup.getUsers()) {
                        if (addressCorresponGroup.isTo() && aUser.isAttention()) {
                            assertTrue(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                            if (aUser.getPersonInCharges() != null) {
                                assertTrue(aUser.getPersonInCharges().get(0).getUser().getLabel(),
                                        html.contains(aUser.getPersonInCharges().get(0).getUser().getLabel()));
                            }
                        } else if (addressCorresponGroup.isTo() && !aUser.isAttention()) {
                            assertFalse(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                        } else if (addressCorresponGroup.isCc() && aUser.isCc()) {
                            assertTrue(aUser.getUser().getLabel(), html.contains(aUser.getUser().getLabel()));
                        }
                    }
                }
            }
            assertTrue(c.getCorresponType().getName(),
                    html.contains(getExpectedHTMLString(c.getCorresponType().getName())));
            assertTrue(c.getSubject(), html.contains(getExpectedHTMLString(c.getSubject())));
            assertTrue(c.getBody(), html.contains(getExpectedHTMLString(c.getBody())));
            if (ReplyRequired.YES.equals(c.getReplyRequired())) {
                assertTrue(c.getDeadlineForReply().toString(),
                        html.contains(f.format(c.getDeadlineForReply())));
            }
            if (c.getFile1FileName() != null) {
                assertTrue(c.getFile1FileName(), html.contains(c.getFile1FileName()));
            }
            if (c.getFile2FileName() != null) {
                assertTrue(c.getFile2FileName(), html.contains(c.getFile2FileName()));
            }
            if (c.getFile3FileName() != null) {
                assertTrue(c.getFile3FileName(), html.contains(c.getFile3FileName()));
            }
            if (c.getFile4FileName() != null) {
                assertTrue(c.getFile4FileName(), html.contains(c.getFile4FileName()));
            }
            if (c.getFile5FileName() != null) {
                assertTrue(c.getFile5FileName(), html.contains(c.getFile5FileName()));
            }
            if (c.getCustomField1Label() != null) {
                assertTrue(c.getCustomField1Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField1Label())));
                assertTrue(c.getCustomField1Value(), html.contains(c.getCustomField1Value()));
            }
            if (c.getCustomField2Label() != null) {
                assertTrue(c.getCustomField2Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField2Label())));
                assertTrue(c.getCustomField2Value(), html.contains(c.getCustomField2Value()));
            }
            if (c.getCustomField3Label() != null) {
                assertTrue(c.getCustomField3Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField3Label())));
                assertTrue(c.getCustomField3Value(), html.contains(c.getCustomField3Value()));
            }
            if (c.getCustomField4Label() != null) {
                assertTrue(c.getCustomField4Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField4Label())));
                assertTrue(c.getCustomField4Value(), html.contains(c.getCustomField4Value()));
            }
            if (c.getCustomField5Label() != null) {
                assertTrue(c.getCustomField5Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField5Label())));
                assertTrue(c.getCustomField5Value(), html.contains(c.getCustomField5Value()));
            }
            if (c.getCustomField6Label() != null) {
                assertTrue(c.getCustomField6Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField6Label())));
                assertTrue(c.getCustomField6Value(), html.contains(c.getCustomField6Value()));
            }
            if (c.getCustomField7Label() != null) {
                //  ???HTML??????????...
                //  ????????????????
                //  ?
                //                    assertTrue("" + index + "*"+c.getCustomField7Label()+"*",
                //                        html.contains(getExpectedHTMLString(c.getCustomField7Label())));
                //                    assertTrue(c.getCustomField7Value(),
                //                        html.contains(c.getCustomField7Value()));
            }
            if (c.getCustomField8Label() != null) {
                assertTrue(c.getCustomField8Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField8Label())));
                assertTrue(c.getCustomField8Value(), html.contains(c.getCustomField8Value()));
            }
            if (c.getCustomField9Label() != null) {
                assertTrue(c.getCustomField9Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField9Label())));
                assertTrue(c.getCustomField9Value(), html.contains(c.getCustomField9Value()));
            }
            if (c.getCustomField10Label() != null) {
                assertTrue(c.getCustomField10Label(),
                        html.contains(getExpectedHTMLString(c.getCustomField10Label())));
                assertTrue(c.getCustomField10Value(), html.contains(c.getCustomField10Value()));
            }
            //Created??????????
            //                assertTrue(c.getCreatedAt().toString(),
            //                   html.contains(getExpectedHTMLString(f2.format(c.getCreatedAt()))));
            if (c.getIssuedAt() != null) {
                assertTrue(c.getIssuedAt().toString(),
                        html.contains(getExpectedHTMLString(f2.format(c.getIssuedAt()))));
            }
            assertTrue(c.getUpdatedAt().toString(),
                    html.contains(getExpectedHTMLString(f2.format(c.getUpdatedAt()))));
            //Created??????????
            //                assertTrue(c.getCreatedBy().getNameE() + "/" + c.getCreatedBy().getEmpNo(),
            //                    html.contains(
            //                        c.getCreatedBy().getNameE() + "/" + c.getCreatedBy().getEmpNo()));
            if ((c.getIssuedBy() != null) && (c.getIssuedBy().getNameE() != null)
                    && (c.getIssuedBy().getEmpNo() != null)) {
                assertTrue(c.getIssuedBy().getNameE() + "/" + c.getIssuedBy().getEmpNo(),
                        html.contains(c.getIssuedBy().getNameE() + "/" + c.getIssuedBy().getEmpNo()));
            }
            assertTrue(c.getUpdatedBy().getNameE() + "/" + c.getUpdatedBy().getEmpNo(),
                    html.contains(c.getUpdatedBy().getNameE() + "/" + c.getUpdatedBy().getEmpNo()));
            if (c.getWorkflows() != null) {
                for (Workflow flow : c.getWorkflows()) {
                    assertTrue(flow.getWorkflowNo().toString(),
                            html.contains(getExpectedHTMLString(flow.getWorkflowNo().toString())));
                    assertTrue(flow.getWorkflowType().getLabel(),
                            html.contains(getExpectedHTMLString(flow.getWorkflowType().getLabel())));
                    assertTrue(flow.getUser().getNameE() + "/" + flow.getUser().getEmpNo(), html.contains(
                            getExpectedString(flow.getUser().getNameE() + "/" + flow.getUser().getEmpNo())));
                    assertTrue(flow.getWorkflowProcessStatus().getLabel(),
                            html.contains(getExpectedString(flow.getWorkflowProcessStatus().getLabel())));
                    if (flow.getUpdatedBy() != null) {
                        assertTrue(flow.getUpdatedBy().getNameE() + "/" + flow.getUpdatedBy().getEmpNo(),
                                html.contains(getExpectedString(flow.getUpdatedBy().getNameE() + "/"
                                        + flow.getUpdatedBy().getEmpNo())));
                        assertTrue(flow.getUpdatedAt().toString(),
                                html.contains(f2.format(flow.getUpdatedAt())));
                    }
                    assertTrue(flow.getCommentOn(), html.contains(getExpectedString(flow.getCommentOn())));
                }
            }

            index++;
        }
    } finally {
        zis.close();
        bi.close();
    }
}