Example usage for javax.activation DataHandler getInputStream

List of usage examples for javax.activation DataHandler getInputStream

Introduction

In this page you can find the example usage for javax.activation DataHandler getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Get the InputStream for this object.

Usage

From source file:de.kp.ames.web.function.security.SecurityServiceImpl.java

/**
 * A helper method to update an existing password safe
 * /*w w w .j a  v  a2  s  . c  o m*/
 * @param service
 * @param creds
 * @param safe
 * @throws JSONException 
 * @throws JAXRException 
 * @throws UnsupportedCapabilityException 
 * @throws IOException 
 */
private void updateSafe(String service, String creds, ExtrinsicObjectImpl safe)
        throws JSONException, UnsupportedCapabilityException, JAXRException, IOException {

    JaxrTransaction transaction = new JaxrTransaction();
    /* 
     * Create credentials as JSON object
     */
    JSONObject jCredentials = new JSONObject(creds);

    DataHandler handler = safe.getRepositoryItem();
    if (handler == null)
        return;

    byte[] bytes = FileUtil.getByteArrayFromInputStream(handler.getInputStream());
    JSONObject jSafe = new JSONObject(new String(bytes));

    /* 
     * Update password safe
     */
    jSafe.put(service, jCredentials);

    bytes = jSafe.toString().getBytes("UTF-8");
    handler = new DataHandler(FileUtil.createByteArrayDataSource(bytes, "application/json"));

    safe.setRepositoryItem(handler);
    transaction.addObjectToSave(safe);

    JaxrLCM lcm = new JaxrLCM(jaxrHandle);
    lcm.saveObjects(transaction.getObjectsToSave(), false, false);

}

From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResponseProcessPlugin.java

private boolean saveBodyToFilesystem(final String responseId, final DataHandler dataHandler)
        throws IOException {
    final boolean erfolgreichGespeichert = false;

    final StringBuffer dateiName = new StringBuffer();

    dateiName.append(baueDateiname());/*from ww  w .j a  v a2  s .c  o m*/
    dateiName.append("-");
    dateiName.append(responseId);

    final File responseFile = new File(eingangOrdner, dateiName.toString());

    final FileOutputStream fileOutputStream = new FileOutputStream(responseFile);

    IOUtils.copyLarge(dataHandler.getInputStream(), fileOutputStream);

    transportObserver.responseDataForwarded(responseFile.getAbsolutePath(), responseFile.length());

    if (LOG.isTraceEnabled()) {
        LOG.trace("Dateiname: '" + dateiName + "'");
    }

    return erfolgreichGespeichert;
}

From source file:org.wso2.carbon.am.tests.APIManagerIntegrationTest.java

protected DataHandler setEndpoints(DataHandler dataHandler) throws XMLStreamException, IOException {

    String config = readInputStreamAsString(dataHandler.getInputStream());
    config = replaceEndpoints(config);/*from  ww  w.j av  a  2  s .  com*/
    ByteArrayDataSource dbs = new ByteArrayDataSource(config.getBytes());
    return new DataHandler(dbs);
}

From source file:de.extra.client.plugins.responseprocessplugin.filesystem.FileSystemResultPackageDataResponseProcessPlugin.java

/**
 * @param responseId//from w w  w .  ja va 2s  .  c om
 * @param responseBody
 * @return fileName
 */
private String saveBodyToFilesystem(final String incomingFileName, final String responseId,
        final DataHandler packageBodyDataHandler) {
    try {

        final String dateiName = buildFilename(incomingFileName, responseId);

        final File responseFile = new File(eingangOrdner, dateiName);

        final FileOutputStream fileOutputStream = new FileOutputStream(responseFile);
        final String dataHandlerName = packageBodyDataHandler.getName();
        logger.info("Receiving File : " + dataHandlerName);

        IOUtils.copy(packageBodyDataHandler.getInputStream(), fileOutputStream);

        IOUtils.closeQuietly(fileOutputStream);

        logger.info("Input file is stored under " + responseFile.getAbsolutePath());
        logger.info("ChecksumCRC32 " + FileUtils.checksumCRC32(responseFile));
        logger.info("Filesize: " + FileUtils.sizeOf(responseFile));

        transportObserver.responseDataForwarded(responseFile.getAbsolutePath(), responseFile.length());

        logger.info("Response gespeichert in File: '" + dateiName + "'");

        return dateiName;
    } catch (final IOException ioException) {
        throw new ExtraResponseProcessPluginRuntimeException(ExceptionCode.UNEXPECTED_INTERNAL_EXCEPTION,
                "Fehler beim schreiben der Antwort", ioException);
    }
}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index one message.//from w  w w. ja v a 2s  .  c  o m
 */
private void indexMessage(final Document doc, final Message m) throws MessagingException, IOException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return;
    }
    final long uid = ((UIDFolder) m.getFolder()).getUID(m);

    // form a URL that mozilla seems to accept. Couldn't get it to accept
    // what I thought was the standard

    String urlPrefix = "imap://" + user + "@" + host + ":143/fetch%3EUID%3E/";

    final String url = urlPrefix + m.getFolder().getFullName() + "%3E" + uid;
    doc.add(Field.Text("name", url));

    final String subject = m.getSubject();
    final Date recv = m.getReceivedDate();
    final Date sent = m.getSentDate();
    log.info("Folder: " + m.getFolder().getFullName() + ": Message received " + recv + ", subject: " + subject);
    // -------------------------------------------------------
    // data gathered, now add to doc

    if (subject != null) {
        doc.add(Field.Text(F_SUBJECT, m.getSubject()));
        doc.add(Field.Text("title", m.getSubject()));
    }

    if (recv != null) {
        doc.add(Field.Keyword(F_RECEIVED, DateTools.timeToString(recv.getTime(), DateTools.Resolution.SECOND)));
    }

    if (sent != null) {
        doc.add(Field.Keyword(F_SENT, DateTools.timeToString(sent.getTime(), DateTools.Resolution.SECOND)));
        // store date as yyyyMMdd
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        String dfString = df.format(new Date(sent.getTime()));
        doc.add(Field.Keyword("modified", dfString));
    }

    doc.add(Field.Keyword(F_URL, url));

    Address[] addrs = m.getAllRecipients();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_TO, "" + addrs[j]));
        }
    }

    addrs = m.getFrom();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_FROM, "" + addrs[j]));
            doc.add(Field.Keyword("author", "" + addrs[j]));
        }
    }
    addrs = m.getReplyTo();
    if (addrs != null) {
        for (int j = 0; j < addrs.length; j++) {
            doc.add(Field.Keyword(F_REPLY_TO, "" + addrs[j]));
        }
    }

    doc.add(Field.Keyword(F_UID, "" + uid));

    // could ignore docs that have the deleted flag set
    for (int j = 0; j < FLAGS.length; j++) {
        boolean val = m.isSet(FLAGS[j]);
        doc.add(Field.Keyword(SFLAGS[j], (val ? "true" : "false")));
    }

    // now special case for mime
    if (m instanceof MimeMessage) {
        // mime++;
        MimeMessage mm = (MimeMessage) m;
        log.debug("index, adding MimeMessage " + m.getFileName());
        indexMimeMessage(doc, mm);

    } else {
        // nmime++;

        final DataHandler dh = m.getDataHandler();
        log.debug("index, adding (non-MIME) Content " + m.getFileName());
        doc.add(Field.Text(F_CONTENTS, new InputStreamReader(dh.getInputStream())));
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.// w ww . j  a va 2s. c o  m
 * 
 * @throws Exception
 */
@Test
public void testScenario() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId);
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.// w w  w .  j av a  2  s .  co m
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvoke() throws Exception {
    // STS
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox: remove all messages.
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("RESPONSE: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:org.apache.synapse.mediators.bsf.ScriptMediator.java

/**
 * Prepares the mediator for the invocation of an external script
 *
 * @param synCtx MessageContext script/*w w  w  .  ja va 2 s.c  om*/
 * @throws ScriptException For any errors , when compile the script
 */
protected void prepareExternalScript(MessageContext synCtx) throws ScriptException {

    // TODO: only need this synchronized method for dynamic registry entries. If there was a way
    // to access the registry entry during mediator initialization then for non-dynamic entries
    // this could be done just the once during mediator initialization.

    // Derive actual key from xpath expression or get static key
    String generatedScriptKey = key.evaluateValue(synCtx);
    Entry entry = synCtx.getConfiguration().getEntryDefinition(generatedScriptKey);
    boolean needsReload = (entry != null) && entry.isDynamic() && (!entry.isCached() || entry.isExpired());
    resourceLock.lock();
    try {
        if (scriptSourceCode == null || needsReload) {
            Object o = synCtx.getEntry(generatedScriptKey);
            if (o instanceof OMElement) {
                scriptSourceCode = ((OMElement) (o)).getText();
                scriptEngine.eval(scriptSourceCode);
            } else if (o instanceof String) {
                scriptSourceCode = (String) o;
                scriptEngine.eval(scriptSourceCode);
            } else if (o instanceof OMText) {
                DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
                if (dataHandler != null) {
                    BufferedReader reader = null;
                    try {
                        reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
                        StringBuilder scriptSB = new StringBuilder();
                        String currentLine;
                        while ((currentLine = reader.readLine()) != null) {
                            scriptSB.append(currentLine).append('\n');
                        }
                        scriptSourceCode = scriptSB.toString();
                        scriptEngine.eval(scriptSourceCode);
                    } catch (IOException e) {
                        handleException("Error in reading script as a stream ", e, synCtx);
                    } finally {

                        if (reader != null) {
                            try {
                                reader.close();
                            } catch (IOException e) {
                                handleException("Error in closing input stream ", e, synCtx);
                            }
                        }

                    }
                }
            }

        }
    } finally {
        resourceLock.unlock();
    }

    // load <include /> scripts; reload each script if needed
    for (Value includeKey : includes.keySet()) {

        String includeSourceCode = (String) includes.get(includeKey);

        String generatedKey = includeKey.evaluateValue(synCtx);

        Entry includeEntry = synCtx.getConfiguration().getEntryDefinition(generatedKey);
        boolean includeEntryNeedsReload = (includeEntry != null) && includeEntry.isDynamic()
                && (!includeEntry.isCached() || includeEntry.isExpired());
        resourceLock.lock();
        try {
            if (includeSourceCode == null || includeEntryNeedsReload) {
                log.debug("Re-/Loading the include script with key " + includeKey);
                Object o = synCtx.getEntry(generatedKey);
                if (o instanceof OMElement) {
                    includeSourceCode = ((OMElement) (o)).getText();
                    scriptEngine.eval(includeSourceCode);
                } else if (o instanceof String) {
                    includeSourceCode = (String) o;
                    scriptEngine.eval(includeSourceCode);
                } else if (o instanceof OMText) {
                    DataHandler dataHandler = (DataHandler) ((OMText) o).getDataHandler();
                    if (dataHandler != null) {
                        BufferedReader reader = null;
                        try {
                            reader = new BufferedReader(new InputStreamReader(dataHandler.getInputStream()));
                            StringBuilder scriptSB = new StringBuilder();
                            String currentLine;
                            while ((currentLine = reader.readLine()) != null) {
                                scriptSB.append(currentLine).append('\n');
                            }
                            includeSourceCode = scriptSB.toString();
                            scriptEngine.eval(includeSourceCode);
                        } catch (IOException e) {
                            handleException("Error in reading script as a stream ", e, synCtx);
                        } finally {

                            if (reader != null) {
                                try {
                                    reader.close();
                                } catch (IOException e) {
                                    handleException("Error in closing input" + " stream ", e, synCtx);
                                }
                            }
                        }
                    }
                }
                includes.put(includeKey, includeSourceCode);
            }
        } finally {
            resourceLock.unlock();
        }
    }
}

From source file:org.bimserver.shared.json.JsonConverter.java

public void toJson(Object object, JsonWriter out) throws IOException, SerializerException {
    if (object instanceof SBase) {
        SBase base = (SBase) object;//from  w w  w .j  a v  a 2s  .  c om
        out.beginObject();
        out.name("__type");
        out.value(base.getSClass().getSimpleName());
        for (SField field : base.getSClass().getAllFields()) {
            out.name(field.getName());
            toJson(base.sGet(field), out);
        }
        out.endObject();
    } else if (object instanceof Collection) {
        Collection<?> collection = (Collection<?>) object;
        out.beginArray();
        for (Object value : collection) {
            toJson(value, out);
        }
        out.endArray();
    } else if (object instanceof Date) {
        out.value(((Date) object).getTime());
    } else if (object instanceof DataHandler) {
        DataHandler dataHandler = (DataHandler) object;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (dataHandler.getDataSource() instanceof CacheStoringEmfSerializerDataSource) {
            CacheStoringEmfSerializerDataSource cacheStoringEmfSerializerDataSource = (CacheStoringEmfSerializerDataSource) dataHandler
                    .getDataSource();
            cacheStoringEmfSerializerDataSource.writeToOutputStream(baos, null);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        } else {
            InputStream inputStream = dataHandler.getInputStream();
            IOUtils.copy(inputStream, baos);
            out.value(new String(Base64.encodeBase64(baos.toByteArray()), Charsets.UTF_8));
        }
    } else if (object instanceof byte[]) {
        byte[] data = (byte[]) object;
        out.value(new String(Base64.encodeBase64(data), Charsets.UTF_8));
    } else if (object instanceof String) {
        out.value((String) object);
    } else if (object instanceof Number) {
        out.value((Number) object);
    } else if (object instanceof Enum) {
        out.value(object.toString());
    } else if (object instanceof Boolean) {
        out.value((Boolean) object);
    } else if (object == null) {
        out.nullValue();
    } else {
        throw new UnsupportedOperationException(object.toString());
    }
}

From source file:org.bimserver.unittests.TestLowLevelChanges.java

private IfcModelInterface getSingleRevision(long roid)
        throws ServiceException, DeserializeException, IOException {
    SRevision revision = serviceInterface.getRevision(roid);
    SSerializerPluginConfiguration serializerByContentType = serviceInterface
            .getSerializerByContentType("application/ifc");
    long topicId = serviceInterface.download(Collections.singleton(revision.getOid()),
            DefaultQueries.allAsString(), serializerByContentType.getOid(), true);
    SDownloadResult downloadData = serviceInterface.getDownloadData(topicId);
    DataHandler dataHandler = downloadData.getFile();
    try {// w w  w  .  j a va 2s . co  m
        DeserializerPlugin deserializerPlugin = pluginManager.getFirstDeserializer("ifc", Schema.IFC2X3TC1,
                true);
        Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration());

        MetaDataManager metaDataManager = new MetaDataManager(pluginManager.getTempDir());
        PackageMetaData packageMetaData = metaDataManager.getPackageMetaData("ifc2x3tc1");

        deserializer.init(packageMetaData);
        IfcModelInterface model = deserializer.read(dataHandler.getInputStream(), "test.ifc", 0, null);
        return model;
    } catch (PluginException e) {
        e.printStackTrace();
    }
    return null;
}