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:org.wso2.carbon.user.mgt.UserAdmin.java

/**
 * @param fileName/*from www.  ja v  a 2 s.  c o  m*/
 * @param handler
 * @param defaultPassword
 * @throws UserAdminException
 */
public void bulkImportUsers(String fileName, DataHandler handler, String defaultPassword)
        throws UserAdminException {
    if (fileName == null || handler == null || defaultPassword == null) {
        throw new UserAdminException("Required data not provided");
    }
    try {
        InputStream inStream = handler.getInputStream();
        getUserAdminProxy().bulkImportUsers(fileName, inStream, defaultPassword);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        throw new UserAdminException(e.getMessage(), e);
    }

}

From source file:org.wso2.carbon.mapred.mgt.HadoopJobRunner.java

public void putJar(String friendlyName, DataHandler dataHandler) throws MapredManagerException {
    CarbonContext cc = CarbonContext.getCurrentContext();
    Registry reg = cc.getRegistry(RegistryType.USER_CONFIGURATION);
    try {//w  w  w  .  j a v a  2 s  . c  om
        if (reg.resourceExists(REG_JAR_PATH + getCurrentUser() + File.separator + friendlyName)) {
            log.info("Deleting already exsiting " + REG_JAR_PATH + getCurrentUser() + File.separator
                    + friendlyName);
            reg.delete(REG_JAR_PATH + getCurrentUser() + File.separator + friendlyName);
        }
        Resource resource = reg.newResource();
        resource.setContentStream(dataHandler.getInputStream());
        String out = reg.put(REG_JAR_PATH + getCurrentUser() + File.separator + friendlyName, resource);
    } catch (Exception e) {
        String msg = "Error while putting jar to the registry";
        log.error(msg, e);
        throw new MapredManagerException(msg, e);
    }
}

From source file:es.pode.administracion.presentacion.logs.listar.ListarLogControllerImpl.java

public final void recuperarFicheroLog(org.apache.struts.action.ActionMapping mapping,
        es.pode.administracion.presentacion.logs.listar.RecuperarFicheroLogForm form,
        javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
        throws java.lang.Exception {
    try {/* w w w  .j  ava  2  s.c o m*/
        String fichero = (String) form.getNombre();
        DataHandler dataHandler = null;
        SrvLogService logService = this.getSrvLogService();
        try {
            dataHandler = logService.recuperarFicheroLog(fichero);

        } catch (Exception e) {
            log.error("Error al recuperar el fichero");
        }
        if (dataHandler == null) {
            log.error("El fichero recuperado est vacio");
            throw new ValidatorException("{recuperarFicheroLog.FALLO}");
        }
        if (fichero.endsWith(".log")) {
            response.setContentType("application/text");
        } else {
            response.setContentType("application/zip");
        }
        response.setHeader("Content-Disposition", "attachment;filename=" + fichero);
        OutputStream out = response.getOutputStream();
        InputStream in = dataHandler.getInputStream();
        if (log.isDebugEnabled())
            log.debug("recuperando el fichero " + fichero);
        byte[] buffer = new byte[BUFFER_SIZE];
        int count;
        while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
            out.write(buffer, 0, count);
        }

        out.flush();
        out.close();

    } catch (ValidatorException e) {
        throw e;
    } catch (Exception e) {
        log.error("Se ha producido el siguiente error: " + e);
        throw e;
    }

}

From source file:org.wso2.esb.integration.common.utils.ESBIntegrationTest.java

protected DataHandler setEndpoints(DataHandler dataHandler)
        throws XMLStreamException, IOException, XPathExpressionException {
    if (isBuilderEnabled()) {
        return dataHandler;
    }//from  w w w .java  2  s. co m
    String config = readInputStreamAsString(dataHandler.getInputStream());
    config = replaceEndpoints(config);
    ByteArrayDataSource dbs = new ByteArrayDataSource(config.getBytes());
    return new DataHandler(dbs);
}

From source file:org.apache.axiom.attachments.Attachments.java

/**
 * @return the InputStream which includes the SOAP Envelope. It assumes that the root mime part
 *         is always pointed by "start" parameter in content-type.
 *///  ww  w .j av  a2s  .  co  m
public InputStream getSOAPPartInputStream() throws OMException {
    DataHandler dh;
    if (noStreams) {
        throw new OMException("Invalid operation. Attachments are created programatically.");
    }
    try {
        dh = getDataHandler(getSOAPPartContentID());
        if (dh == null) {
            throw new OMException("Mandatory Root MIME part containing the SOAP Envelope is missing");
        }
        return dh.getInputStream();
    } catch (IOException e) {
        throw new OMException("Problem with DataHandler of the Root Mime Part. ", e);
    }
}

From source file:org.wso2.carbon.relay.module.handler.SkipAdminServiceHandler.java

public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    try {/*from  w  w w  .  j a va  2  s  .c om*/
        Parameter relayParam = msgContext.getParameter(RelayConstants.RELAY_CONFIG_PARAM);

        if (relayParam == null) {
            handleException("Relay not initialized");
        }

        RelayConfiguration relConf = (RelayConfiguration) relayParam.getValue();

        if (relConf == null) {
            handleException("Relay not initialized");
        }

        if (isFilteredOutService(msgContext.getAxisService(), relConf)) {
            SOAPEnvelope envelope = msgContext.getEnvelope();

            OMElement contentEle = envelope.getBody()
                    .getFirstChildWithName(RelayConstants.BINARY_CONTENT_QNAME);

            if (contentEle != null) {
                OMNode node = contentEle.getFirstOMChild();
                if (node != null && (node instanceof OMText)) {
                    OMText binaryDataNode = (OMText) node;
                    DataHandler dh = (DataHandler) binaryDataNode.getDataHandler();

                    if (dh == null) {
                        if (log.isDebugEnabled()) {
                            log.warn("Message has the Binary content element. "
                                    + "But doesn't have binary content embedded within it");
                        }
                        return InvocationResponse.CONTINUE;
                    }

                    DataSource dataSource = dh.getDataSource();
                    //Ask the data source to stream, if it has not alredy cached the request
                    if (dataSource instanceof StreamingOnRequestDataSource) {
                        ((StreamingOnRequestDataSource) dataSource).setLastUse(true);
                    }
                    InputStream in = dh.getInputStream();
                    //extract the wrapped binary content

                    //Select the right builder, create the envelope and stick it in.
                    String contentType = (String) msgContext.getProperty(Constants.Configuration.CONTENT_TYPE);

                    OMElement element = relConf.getMessageBuilder().getDocument(contentType, msgContext, in);

                    if (element != null) {
                        msgContext.setEnvelope(TransportUtils.createSOAPEnvelope(element));

                        msgContext.setProperty(MessageBuilder.RELAY_FORMATTERS_MAP,
                                relConf.getMessageBuilder().getFormatters());
                    } else {
                        log.warn("Error building the message, skipping message building");
                    }
                    //now we have undone thing done  by Relay
                    if (log.isDebugEnabled()) {
                        log.debug("Undo wrapping done by Relay");
                    }
                } else {
                    //if is not wrapped binary content, there is nothing to be done
                    if (log.isDebugEnabled()) {
                        log.debug("not wrapped binary content, there is nothing to be done");
                    }
                }
            } else {
                //there is no body content, we will let it go
                if (log.isDebugEnabled()) {
                    log.debug("Body of the Soap Envelope is empty, nothing to unwrap");
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Not a admin service, nothing to be done");
            }
        }
        return InvocationResponse.CONTINUE;
    } catch (OMException e) {
        throw AxisFault.makeFault(e);
    } catch (IOException e) {
        throw AxisFault.makeFault(e);
    } catch (XMLStreamException e) {
        throw AxisFault.makeFault(e);
    }
}

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

/**
 * Retrieve password safe associated with the caller's user
 * /* w  ww .j a  va  2 s  .  co  m*/
 * @param service
 * @return
 * @throws Exception
 */
private String getCredentials(String service) throws Exception {

    /*
     * Retrieve caller's unique identifier
     */
    String uid = jaxrHandle.getUser();

    if (uid == null) {
        /*
         * Return empty JSON object
         */
        return new JSONObject().toString();

    }

    /*
     * Login
     */
    JaxrClient.getInstance().logon(jaxrHandle);
    JaxrDQM dqm = new JaxrDQM(jaxrHandle);

    String sqlString = FncSQL.getSQLAssertions_Safe(uid);
    List<AssociationImpl> as = dqm.getAssociationsByQuery(sqlString);

    if (as.size() == 0) {
        /*
         * Logoff
         */
        JaxrClient.getInstance().logoff(jaxrHandle);

        /*
         * Return empty JSON object
         */
        return new JSONObject().toString();

    }

    ExtrinsicObjectImpl safe = (ExtrinsicObjectImpl) as.get(0).getTargetObject();
    DataHandler handler = safe.getRepositoryItem();

    if (handler == null) {
        /*
         * Logoff
         */
        JaxrClient.getInstance().logoff(jaxrHandle);

        /*
         * Return empty JSON object
         */
        return new JSONObject().toString();

    }

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

    if (jSafe.has(service) == false) {
        /*
         * Logoff
         */
        JaxrClient.getInstance().logoff(jaxrHandle);

        /*
         * Return empty JSON object
         */
        return new JSONObject().toString();

    }

    String content = jSafe.getJSONObject(service).toString();

    /*
     * Logoff
     */
    JaxrClient.getInstance().logoff(jaxrHandle);

    return content;

}

From source file:com.cloud.bridge.service.controller.s3.S3ObjectAction.java

private void executeGetObject(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY);
    String key = (String) request.getAttribute(S3Constants.OBJECT_ATTR_KEY);
    String[] paramList = null;//from ww w  .  j  a  v a 2s . co  m

    S3GetObjectRequest engineRequest = new S3GetObjectRequest();
    engineRequest.setBucketName(bucket);
    engineRequest.setKey(key);
    engineRequest.setInlineData(true);
    engineRequest.setReturnData(true);
    //engineRequest.setReturnMetadata(true);
    engineRequest = setRequestByteRange(request, engineRequest);

    // -> is this a request for a specific version of the object?  look for "versionId=" in the query string
    String queryString = request.getQueryString();
    if (null != queryString) {
        paramList = queryString.split("[&=]");
        if (null != paramList)
            engineRequest.setVersion(returnParameter(paramList, "versionId"));
    }

    S3GetObjectResponse engineResponse = ServiceProvider.getInstance().getS3Engine()
            .handleRequest(engineRequest);
    response.setStatus(engineResponse.getResultCode());

    String deleteMarker = engineResponse.getDeleteMarker();
    if (null != deleteMarker) {
        response.addHeader("x-amz-delete-marker", "true");
        response.addHeader("x-amz-version-id", deleteMarker);
    } else {
        String version = engineResponse.getVersion();
        if (null != version)
            response.addHeader("x-amz-version-id", version);
    }

    // -> was the get conditional?
    if (!conditionPassed(request, response, engineResponse.getLastModified().getTime(),
            engineResponse.getETag()))
        return;

    // -> is there data to return
    // -> from the Amazon REST documentation it appears that Meta data is only returned as part of a HEAD request
    //returnMetaData( engineResponse, response );

    DataHandler dataHandler = engineResponse.getData();
    if (dataHandler != null) {
        response.addHeader("ETag", engineResponse.getETag());
        response.addHeader("Last-Modified", DateHelper.getDateDisplayString(DateHelper.GMT_TIMEZONE,
                engineResponse.getLastModified().getTime(), "E, d MMM yyyy HH:mm:ss z"));

        response.setContentLength((int) engineResponse.getContentLength());
        S3RestServlet.writeResponse(response, dataHandler.getInputStream());
    }
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, String title, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//ww w. j  a  v  a 2s  .  c  o  m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(System.getProperty("user.dir") + "/fileTemp/" + title + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}

From source file:org.mule.modules.wechat.common.HttpsConnection.java

public Map<String, Object> postFile(String httpsURL, DataHandler attachment) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost post = new HttpPost(httpsURL);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    // Get extension of attachment
    TikaConfig config = TikaConfig.getDefaultConfig();
    MimeTypes allTypes = config.getMimeRepository();
    String ext = allTypes.forName(attachment.getContentType()).getExtension();
    if (ext.equals("")) {
        ContentTypeEnum contentTypeEnum = ContentTypeEnum
                .getContentTypeEnumByContentType(attachment.getContentType().toLowerCase());
        ext = java.util.Optional.ofNullable(contentTypeEnum.getExtension()).orElse("");
    }//from  w w w  .j  a  v  a 2 s  .co m

    // Create file
    InputStream fis = attachment.getInputStream();
    byte[] bytes = IOUtils.toByteArray(fis);
    File f = new File(
            System.getProperty("user.dir") + "/fileTemp/" + attachment.getName().replace(ext, "") + ext);
    FileUtils.writeByteArrayToFile(f, bytes);
    builder.addBinaryBody("media", f);

    // Post to wechat
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    CloseableHttpResponse httpResponse = httpClient.execute(post);
    String content = "";
    try {
        HttpEntity _entity = httpResponse.getEntity();
        content = EntityUtils.toString(_entity);
        EntityUtils.consume(_entity);
    } finally {
        httpResponse.close();
    }
    f.delete();

    // Convert JSON string to Map
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });

    return map;
}