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:cz.zcu.kiv.eegdatabase.webservices.client.ClientServiceImpl.java

@Override
public int addScenario(ScenarioInfo info, @XmlMimeType("application/octet-stream") DataHandler inputData)
        throws ClientServiceException {
    Scenario s = new Scenario();
    s.setDescription(info.getDescription());
    Person p = personDao.read(info.getOwnerPersonId());
    s.setPerson(p);/*from www  . j  a  va2 s  . c o m*/
    ResearchGroup r = researchGroupDao.read(info.getResearchGroupId());
    s.setResearchGroup(r);
    s.setPrivateScenario(info.isPrivateScenario());
    s.setScenarioLength(info.getScenarioLength());
    s.setTitle(info.getTitle());
    try {
        if (inputData != null) {
            s.setMimetype(info.getMimetype());
            s.setScenarioName(info.getScenarioName());
            Blob blob = dataFileDao.createBlob(inputData.getInputStream(), (int) info.getFileLength());
        }
    } catch (IOException ex) {
        log.error(ex.getMessage(), ex);
        throw new ClientServiceException(ex);
    }
    int scenarioId = scenarioDao.create(s);
    log.debug("User " + personDao.getLoggedPerson().getEmail() + " created new Scenario (primary key "
            + scenarioId + ").");
    p.getScenarios().add(s);
    personDao.update(p);
    r.getScenarios().add(s);
    researchGroupDao.update(r);
    return scenarioId;
}

From source file:be.e_contract.dssp.client.DigitalSignatureServiceClient.java

/**
 * Downloads the signed document./*w  ww. j  a  v  a2s.  c  o  m*/
 * 
 * @param session
 *            the session object.
 * @return the signed document.
 */
public byte[] downloadSignedDocument(DigitalSignatureServiceSession session) {

    if (false == session.isSignResponseVerified()) {
        throw new SecurityException("SignResponse not verified");
    }

    PendingRequest pendingRequest = this.asyncObjectFactory.createPendingRequest();
    pendingRequest.setProfile(DigitalSignatureServiceConstants.PROFILE);

    AnyType optionalInputs = this.objectFactory.createAnyType();
    pendingRequest.setOptionalInputs(optionalInputs);

    optionalInputs.getAny().add(
            this.objectFactory.createAdditionalProfile(DigitalSignatureServiceConstants.DSS_ASYNC_PROFILE));

    optionalInputs.getAny().add(this.asyncObjectFactory.createResponseID(session.getResponseId()));

    RequestSecurityTokenType requestSecurityToken = this.wstObjectFactory.createRequestSecurityTokenType();
    optionalInputs.getAny().add(this.wstObjectFactory.createRequestSecurityToken(requestSecurityToken));
    requestSecurityToken.getAny().add(this.wstObjectFactory
            .createRequestType(DigitalSignatureServiceConstants.WS_TRUST_CANCEL_REQUEST_TYPE));
    CancelTargetType cancelTarget = this.wstObjectFactory.createCancelTargetType();
    requestSecurityToken.getAny().add(this.wstObjectFactory.createCancelTarget(cancelTarget));
    SecurityTokenReferenceType securityTokenReference = this.wsseObjectFactory
            .createSecurityTokenReferenceType();
    cancelTarget.setAny(this.wsseObjectFactory.createSecurityTokenReference(securityTokenReference));
    ReferenceType reference = this.wsseObjectFactory.createReferenceType();
    securityTokenReference.getAny().add(this.wsseObjectFactory.createReference(reference));
    reference.setValueType(DigitalSignatureServiceConstants.WS_SEC_CONV_TOKEN_TYPE);
    reference.setURI(session.getSecurityTokenId());

    this.wsSecuritySOAPHandler.setSession(session);
    SignResponse signResponse = this.dssPort.pendingRequest(pendingRequest);

    AnyType optionalOutputs = signResponse.getOptionalOutputs();
    List<Object> optionalOutputsList = optionalOutputs.getAny();
    for (Object optionalOutputsObject : optionalOutputsList) {
        LOG.debug("optional outputs object type: " + optionalOutputsObject.getClass().getName());
        if (optionalOutputsObject instanceof DocumentWithSignature) {
            DocumentWithSignature documentWithSignature = (DocumentWithSignature) optionalOutputsObject;
            DocumentType document = documentWithSignature.getDocument();
            if (document.getBase64XML() != null) {
                return document.getBase64XML();
            }
            if (document.getBase64Data() != null) {
                return document.getBase64Data().getValue();
            }
            if (document.getAttachmentReference() != null) {
                AttachmentReferenceType attachmentReference = document.getAttachmentReference();
                String attachmentUri = attachmentReference.getAttRefURI();
                LOG.debug("attachment URI: " + attachmentUri);
                // skip 'cid:'
                String attachmentContentId = attachmentUri.substring(4);
                LOG.debug("attachment content id: " + attachmentContentId);
                Map<String, DataHandler> inboundAttachments = this.attachmentsSOAPHandler
                        .getInboundAttachments();
                for (String attachmentId : inboundAttachments.keySet()) {
                    LOG.debug("actual attachment id: " + attachmentId);
                }
                DataHandler dataHandler;
                if (inboundAttachments.size() == 1) {
                    dataHandler = inboundAttachments.values().iterator().next();
                } else {
                    // JAX-WS RI 1.8 and CXF
                    dataHandler = inboundAttachments.get(attachmentContentId);
                    if (null == dataHandler) {
                        // JAX-WS RI 1.7 adds '<' and '>'.
                        attachmentContentId = '<' + attachmentContentId + '>';
                        dataHandler = inboundAttachments.get(attachmentContentId);
                    }
                }
                LOG.debug("received data handler: " + (null != dataHandler));
                try {
                    byte[] signedDocument = IOUtils.toByteArray(dataHandler.getInputStream());
                    LOG.debug("signed document size: " + signedDocument.length);
                    return signedDocument;
                } catch (IOException e) {
                    throw new RuntimeException("IO error: " + e.getMessage(), e);
                }
            }
        }
    }

    return null;
}

From source file:com.idega.xroad.client.business.impl.XRoadServicesImpl.java

@Override
public InputStream getPreffiledDocument(String applicationID, String taskID, User user, String language) {
    if (user == null || StringUtil.isEmpty(applicationID)) {
        return null;
    }/*from  ww  w  .ja va  2 s . com*/

    if (taskID == null) {
        taskID = CoreConstants.EMPTY;
    }

    GetPrefilledDocumentRequest request = getInstantiatedObject(GetPrefilledDocumentRequest.class);
    request.setCitizenId(user.getPersonalID());
    request.setServiceId(applicationID);
    request.setStepId(taskID);

    LangType langType = getInstantiatedObject(LangType.class);
    langType.setLangType(language);

    request.setLanguageId(langType);

    GetPrefilledDocument prefilledDocument = getInstantiatedObject(GetPrefilledDocument.class);
    prefilledDocument.setRequest(request);

    GetPrefilledDocumentE prefilledDocumentE = getInstantiatedObject(GetPrefilledDocumentE.class);
    prefilledDocumentE.setGetPrefilledDocument(prefilledDocument);

    GetPrefilledDocumentResponseE preffiledDocumentResponseE = null;
    try {
        preffiledDocumentResponseE = getEhubserviceServiceStub().getPrefilledDocument(prefilledDocumentE,
                getConsumer(), getProducer(), getUserId(user), getServiceID(applicationID),
                getService(XRoadClientConstants.SERVICE_GET_PREFILLED_DOCUMENT), getIssue("Some issue"));
    } catch (RemoteException e) {
        getLogger().log(Level.WARNING, "Unable to get " + GetPrefilledDocumentResponseE.class + " cause of: ",
                e);
    }

    if (preffiledDocumentResponseE == null) {
        getLogger().warning("Unable to get: " + GetPrefilledDocumentResponseE.class
                + " by service provider ID: " + applicationID + " and user personal id: " + user.getPersonalID()
                + " and language: " + language);
        return null;
    }

    GetPrefilledDocumentResponse preffiledDocumentResponse = preffiledDocumentResponseE
            .getGetPrefilledDocumentResponse();
    if (preffiledDocumentResponse == null) {
        getLogger().warning("Unable to get: " + GetPrefilledDocumentResponse.class + " by service provider ID: "
                + applicationID + " and user personal id: " + user.getPersonalID() + " and language: "
                + language);
    }

    PreffiledDocument response = preffiledDocumentResponse.getResponse();
    if (response == null) {
        getLogger().warning(
                "Unable to get: " + PreffiledDocument.class + " by service provider ID: " + applicationID
                        + " and user personal id: " + user.getPersonalID() + " and language: " + language);
    }

    DataHandler documentHandler = response.getDocument();
    if (documentHandler == null) {
        getLogger().warning("Unable to get: " + DataHandler.class + " by service provider ID: " + applicationID
                + " and user personal id: " + user.getPersonalID() + " and language: " + language);
    }

    try {
        return documentHandler.getInputStream();
    } catch (IOException e) {
        getLogger().log(Level.WARNING, "Failed to get " + InputStream.class, e);
    }

    return null;
}

From source file:org.wso2.carbon.bpmn.rest.service.runtime.WorkflowTaskService.java

@POST
@Path("/{taskId}/attachments")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createAttachmentForBinary(@PathParam("taskId") String taskId, MultipartBody multipartBody,
        @Context HttpServletRequest httpServletRequest) {

    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();

    int attachmentSize = attachments.size();

    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }/*from  www.  ja  va 2s.  co  m*/
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();

    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);

        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");

        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }

        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();

            Map<String, String> contentDispositionHeaderValueMap = Utils
                    .processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();

            OutputStream outputStream = null;

            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }

                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }

            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }

                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }

            } else if ("description".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured",
                            e);
                }

                if (outputStream != null) {
                    String description = outputStream.toString();
                    attachmentDataHolder.setDescription(description);
                }
            }

            if (contentType != null) {
                if ("file".equals(dispositionName)) {

                    InputStream inputStream = null;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException(
                                "Error Occured During processing empty body.", e);
                    }

                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }

    attachmentDataHolder.printDebug();

    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException(
                "Empty attachment body was found in request body after " + "decoding the request" + ".");
    }

    TaskService taskService = BPMNOSGIService.getTaskService();
    Task task = getTaskFromRequest(taskId);
    Response.ResponseBuilder responseBuilder = Response.ok();

    AttachmentResponse result = null;
    try {

        InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
        Attachment createdAttachment = taskService.createAttachment(attachmentDataHolder.getContentType(),
                task.getId(), task.getProcessInstanceId(), attachmentDataHolder.getName(),
                attachmentDataHolder.getDescription(), inputStream);

        responseBuilder.status(Response.Status.CREATED);
        result = new RestResponseFactory().createAttachmentResponse(createdAttachment,
                uriInfo.getBaseUri().toString());
    } catch (Exception e) {
        throw new ActivitiException("Error creating attachment response", e);
    }

    return responseBuilder.status(Response.Status.CREATED).entity(result).build();
}

From source file:es.pode.catalogadorWeb.presentacion.exportar.ExportarControllerImpl.java

public final void exportarLomes(ActionMapping mapping, ExportarLomesForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    CatalogadorAvSession catAv = this.getCatalogadorAvSession(request);
    final int BUFFER_SIZE = 2048;

    DataHandler dh;
    try {//from   w w  w. j  a va2 s  .  c o  m
        dh = this.getSrvCatalogacionAvanzadaService().exportarLomes(catAv.getIdentificador(),
                catAv.getUsuario(), catAv.getMDSesion(), catAv.getIdioma());
    } catch (Exception e) {
        logger.error(e);
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    if (dh == null) {
        logger.error("Fichero  vacio. Abortamos descarga.");
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    //           asignamos el titulo del fichero que vamos a exportar
    response.setContentType("text/xml;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=metadataLOMES.xml");
    OutputStream out = response.getOutputStream();

    InputStream in = dh.getInputStream();
    logger.debug("Descargando metadata.xml");
    byte[] buffer = new byte[BUFFER_SIZE];
    int count;
    while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
        out.write(buffer, 0, count);
    }

    out.flush();
}

From source file:org.wso2.carbon.bpmn.rest.service.runtime.ProcessInstanceService.java

protected RestVariable setBinaryVariable(MultipartBody multipartBody, Execution execution,
        int responseVariableType, boolean isNew) throws IOException, ServletException {

    boolean debugEnabled = log.isDebugEnabled();
    List<org.apache.cxf.jaxrs.ext.multipart.Attachment> attachments = multipartBody.getAllAttachments();

    int attachmentSize = attachments.size();

    if (attachmentSize <= 0) {
        throw new ActivitiIllegalArgumentException("No Attachments found with the request body");
    }// w ww  .java 2  s . c om
    AttachmentDataHolder attachmentDataHolder = new AttachmentDataHolder();

    for (int i = 0; i < attachmentSize; i++) {
        org.apache.cxf.jaxrs.ext.multipart.Attachment attachment = attachments.get(i);

        String contentDispositionHeaderValue = attachment.getHeader("Content-Disposition");
        String contentType = attachment.getHeader("Content-Type");

        if (debugEnabled) {
            log.debug("Going to iterate:" + i);
            log.debug("contentDisposition:" + contentDispositionHeaderValue);
        }

        if (contentDispositionHeaderValue != null) {
            contentDispositionHeaderValue = contentDispositionHeaderValue.trim();

            Map<String, String> contentDispositionHeaderValueMap = Utils
                    .processContentDispositionHeader(contentDispositionHeaderValue);
            String dispositionName = contentDispositionHeaderValueMap.get("name");
            DataHandler dataHandler = attachment.getDataHandler();

            OutputStream outputStream;

            if ("name".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Name Reading error occured", e);
                }

                if (outputStream != null) {
                    String fileName = outputStream.toString();
                    attachmentDataHolder.setName(fileName);
                }

            } else if ("type".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Type Reading error occured", e);
                }

                if (outputStream != null) {
                    String typeName = outputStream.toString();
                    attachmentDataHolder.setType(typeName);
                }

            } else if ("scope".equals(dispositionName)) {
                try {
                    outputStream = Utils.getAttachmentStream(dataHandler.getInputStream());
                } catch (IOException e) {
                    throw new ActivitiIllegalArgumentException("Attachment Description Reading error occured",
                            e);
                }

                if (outputStream != null) {
                    String scope = outputStream.toString();
                    attachmentDataHolder.setScope(scope);
                }
            }
            if (contentType != null) {
                if ("file".equals(dispositionName)) {

                    InputStream inputStream;
                    try {
                        inputStream = dataHandler.getInputStream();
                    } catch (IOException e) {
                        throw new ActivitiIllegalArgumentException(
                                "Error Occured During processing empty body.", e);
                    }

                    if (inputStream != null) {
                        attachmentDataHolder.setContentType(contentType);
                        byte[] attachmentArray = new byte[0];
                        try {
                            attachmentArray = IOUtils.toByteArray(inputStream);
                        } catch (IOException e) {
                            throw new ActivitiIllegalArgumentException("Processing Attachment Body Failed.", e);
                        }
                        attachmentDataHolder.setAttachmentArray(attachmentArray);
                    }
                }
            }
        }
    }

    attachmentDataHolder.printDebug();

    String variableScope = attachmentDataHolder.getScope();
    String variableName = attachmentDataHolder.getName();
    String variableType = attachmentDataHolder.getType();

    if (attachmentDataHolder.getName() == null) {
        throw new ActivitiIllegalArgumentException("Attachment name is required.");
    }

    if (attachmentDataHolder.getAttachmentArray() == null) {
        throw new ActivitiIllegalArgumentException(
                "Empty attachment body was found in request body after " + "decoding the request" + ".");
    }

    if (debugEnabled) {
        log.debug("variableScope:" + variableScope + " variableName:" + variableName + " variableType:"
                + variableType);
    }

    try {

        // Validate input and set defaults
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("No variable name was found in request body.");
        }

        if (variableType != null) {
            if (!RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variableType)
                    && !RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variableType)) {
                throw new ActivitiIllegalArgumentException(
                        "Only 'binary' and 'serializable' are supported as variable type.");
            }
        } else {
            variableType = RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE;
        }

        RestVariable.RestVariableScope scope = RestVariable.RestVariableScope.LOCAL;
        if (variableScope != null) {
            scope = RestVariable.getScopeFromString(variableScope);
        }

        if (variableType.equals(RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE)) {
            // Use raw bytes as variable value
            setVariable(execution, variableName, attachmentDataHolder.getAttachmentArray(), scope, isNew);

        } else {
            // Try deserializing the object
            try (InputStream inputStream = new ByteArrayInputStream(attachmentDataHolder.getAttachmentArray());
                    ObjectInputStream stream = new ObjectInputStream(inputStream);) {
                Object value = stream.readObject();
                setVariable(execution, variableName, value, scope, isNew);
            }

        }

        RestResponseFactory restResponseFactory = new RestResponseFactory();
        if (responseVariableType == RestResponseFactory.VARIABLE_PROCESS) {

            return new RestResponseFactory().createBinaryRestVariable(variableName, scope, variableType, null,
                    null, execution.getId(), uriInfo.getBaseUri().toString());
        } else {
            return restResponseFactory.createBinaryRestVariable(variableName, scope, variableType, null,
                    execution.getId(), null, uriInfo.getBaseUri().toString());
        }

    } catch (IOException ioe) {
        throw new ActivitiIllegalArgumentException("Could not process multipart content", ioe);
    } catch (ClassNotFoundException ioe) {
        throw new BPMNContentNotSupportedException(
                "The provided body contains a serialized object for which the " + "class is not found: "
                        + ioe.getMessage());
    }

}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Import RegistryObjects defined in an XML file within a ebRS
 * SubmitObjectsRequest and publish them to the registry user current user
 * context./*from ww w.  j a  v a  2  s . c om*/
 */
@SuppressWarnings("rawtypes")
public void exportToFile(Collection registryObjects) {
    FileOutputStream fos = null;
    File zipFile = null;
    try {
        // For now we only handle the case where a single RO with zip RI is
        // being exported.
        if (registryObjects.size() == 0) {
            displayError(resourceBundle.getString("message.info.nothingToExport"));
            return;
        }

        if (registryObjects.size() != 1) {
            // ??I18N
            displayError(resourceBundle.getString("message.error.exactlyOneObjectMustBeSelectedForExport"));
            return;
        }

        Object obj = registryObjects.toArray()[0];

        if (!(obj instanceof ExtrinsicObject)) {
            displayError(CommonResourceBundle.getInstance().getString("message.unexpectedObjectType",
                    new Object[] { "javax.xml.registry.infomodel.ExtrinsicObject", obj.getClass().getName() }));
            return;
        }

        ExtrinsicObject eo = (ExtrinsicObject) obj;

        // TODO: Replace with canonical constant
        if (!(eo.getMimeType().equalsIgnoreCase("application/zip"))) {
            // TODO: Add new message that is mimeType specific
            displayError(CommonResourceBundle.getInstance().getString("message.unexpectedObjectType",
                    new Object[] { "application/zip", eo.getMimeType() }));
        }

        zipFile = File.createTempFile("JavaUIExportAction", ".zip");
        zipFile.deleteOnExit();
        fos = new FileOutputStream(zipFile);

        DataHandler ri = eo.getRepositoryItem();
        InputStream is = ri.getInputStream();

        // Copy is to fos
        int n;
        byte[] buffer = new byte[1024];
        while ((n = is.read(buffer)) > -1) {
            fos.write(buffer, 0, n);
        }
    } catch (Exception e) {
        displayError(e.getMessage(), e);
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
        } catch (Exception e) {
            displayError(e);
        }
    }
    displayInfo(resourceBundle.getString("message.info.ExportSuccessful",
            new Object[] { zipFile.getAbsolutePath() }));

}

From source file:org.bimserver.webservices.impl.PluginServiceImpl.java

public void installPluginBundleFromFile(DataHandler file) throws UserException, ServerException {
    requireRealUserAuthentication();//from w w w .  j a v  a2  s  .co  m
    DatabaseSession session = getBimServer().getDatabase().createSession();
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        IOUtils.copy(file.getInputStream(), byteArrayOutputStream);
        session.executeAndCommitAction(new InstallPluginBundleFromBytes(session, getInternalAccessMethod(),
                getBimServer(), byteArrayOutputStream.toByteArray()));
    } catch (Exception e) {
        handleException(e);
    } finally {
        session.close();
    }
}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasico.CatBasicoControllerImpl.java

public void exportarLomes(ActionMapping mapping, ExportarLomesForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    CatalogadorBSession catBas = this.getCatalogadorBSession(request);
    final int BUFFER_SIZE = 2048;

    DataHandler dh = null;
    try {//from w ww  . j  av  a 2  s.  co  m
        dh = this.getSrvCatalogacionBasicaService().exportarLomes(catBas.getIdentificador(),
                catBas.getUsuario(), form.getLomExportar(), catBas.getIdioma());

    } catch (Exception e) {
        logger.error(e);
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    if (dh == null) {
        logger.error("Fichero  vacio. Abortamos descarga.");
        throw new ValidatorException("{catalogadorAvanzado.exportar.error.fichero}");
    }

    //        asignamos el titulo del fichero que vamos a exportar

    response.setContentType("text/xml;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename=metadataLOMES.xml");
    OutputStream out = response.getOutputStream();
    InputStream in = dh.getInputStream();
    logger.debug("Descargando metadata.xml");
    byte[] buffer = new byte[BUFFER_SIZE];
    int count;
    while ((count = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
        out.write(buffer, 0, count);
    }

    out.flush();
}

From source file:ro.cs.logaudit.web.servlet.ReportServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    logger.debug("doPost START");
    ServletOutputStream sos = null;/*from  w  w  w.j a va 2 s  .c  o m*/
    StopWatch sw = new StopWatch();
    sw.start("Retrieve report");
    try {
        //create the bean containing the report parameters which will be passed to the Report Web Service Client
        AuditEventsReportParams reportParams = new AuditEventsReportParams();

        //Retrieve the start date param for the report request
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
        Date startDate = sdf.parse(ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM), new ParsePosition(0));
        if (startDate != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_START_DATE_PARAM, startDate);
        }

        //Retrieve the end date param for the report request
        Date endDate = sdf.parse(ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM), new ParsePosition(0));
        if (endDate != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_END_DATE_PARAM, endDate);
        }

        //Retrieve the personId param for the report request
        String personId = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM);
        if (personId != null && personId != "") {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PERSON_ID_PARAM,
                    Integer.valueOf(personId));
        }

        //Retrieve the message param for the report request
        String message = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM);
        if (message != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MESSAGE_PARAM, message);
        }

        //Retrieve the event param for the report request
        String event = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM);
        if (event != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_EVENT_PARAM, event);
        }

        //Retrieve the moduleId param for the report request
        Integer moduleId = ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM);
        if (moduleId != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM, moduleId);
        }

        //Retrieve the reportTitle param for the report request
        String reportTitle = ServletRequestUtils.getStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE);
        if (reportTitle != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_PARAM_REPORT_TITLE,
                    reportTitle);
        }

        //Retrieve the orientation param for the report request
        String orientation = ServletRequestUtils.getRequiredStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM);
        if (orientation != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORIENTATION_PARAM,
                    orientation);
        }

        //Retrieve the report format param for the report request
        String format = ServletRequestUtils.getRequiredStringParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM);
        if (format != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_FORMAT_PARAM,
                    format.toLowerCase());
        }

        //Retrieve the organisationId param for the report request
        Integer organisationId = ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM);
        if (organisationId != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_ORGANISATION_ID_PARAM,
                    organisationId);
        }

        reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_LOCALE_PARAM,
                request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME)
                        .toString().toLowerCase().substring(0, 2));

        //if the attachment param exists on the request, it means that the generated report must be a whole html page with head and body tags, 
        //otherwise the report must be embeddable in an existent html page(no head and body tags)
        if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, false);
        } else {
            reportParams.setProperty(IReportsWsClientConstant.AUDIT_EVENTS_REPORT_HTML_IS_EMBEDDABLE, true);
        }

        //Servlet's OutputStream
        sos = response.getOutputStream();

        //get the requested report
        DataHandler reportFileReceived = ReportsWebServiceClient.getInstance()
                .getAuditEventsReport(reportParams);

        //set the response content type
        if (format.toLowerCase().equals("html")) {
            response.setContentType("text/html");
            if (ServletRequestUtils.getBooleanParameters(request, ATTACHMENT) != null) {
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"".concat(reportTitle).concat(".html\""));
            } else {
                response.setHeader("Content-Disposition",
                        "inline; filename=\"".concat(reportTitle).concat(".html\""));
            }
        } else if (format.toLowerCase().equals("pdf")) {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=\"".concat(reportTitle).concat(".pdf\""));
        } else if (format.toLowerCase().equals("doc")) {
            response.setContentType("application/msword");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".doc\""));
        } else if (format.toLowerCase().equals("xls")) {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"".concat(reportTitle).concat(".xls\""));
        }

        //write the received report bytes stream to response output stream
        byte buffer[] = new byte[4096];
        BufferedInputStream bis = new BufferedInputStream(reportFileReceived.getInputStream());
        int size = 0;
        int i;
        while ((i = bis.read(buffer, 0, 4096)) != -1) {
            sos.write(buffer, 0, i);
            size += i;
        }

        if (size == 0) {
            response.setContentType("text/plain");
            sos.write("No content !".getBytes());
        }

        bis.close();
        response.setContentLength(size);

        logger.debug("**** report transfer completed !");
    } catch (Exception ex) {
        logger.error("", ex);
        response.setContentType("text/html");
        String exceptionCode = null;
        ;
        if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_OM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITOM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_DM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITDM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_CM_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITCM_REPORT_CREATE;
        } else if (((Integer) ServletRequestUtils.getIntParameter(request,
                IReportsWsClientConstant.AUDIT_EVENTS_REPORT_MODULE_ID_PARAM))
                        .equals(new Integer(IConstant.NOM_MODULE_TS_LABEL_KEY))) {
            exceptionCode = ICodeException.AUDITTS_REPORT_CREATE;
        }
        response.getWriter().write("<html xmlns=\"http://www.w3.org/1999/xhtml\">"
                + "<head>   <script type=\"text/javascript\" src=\"js/cs/cs_common.js\"></script>"
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/style.css\"/> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/fonts-min.css\" /> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/container.css\" /> </head> "
                + "<link rel=\"stylesheet\" type=\"text/css\" href=\"themes/standard/css/yui/button.css\" />"
                + "<body> <div id=\"errorsContainer\" class=\"errorMessagesDiv\"> "
                + "<table class=\"errorMessagesTable\">" + "<tr>" + "<td>" + "</td>" + "<td>"
                + "<div class=\"hd\">" + "<div id=\"closeErrors\" class=\"messagesCloseButon\"></div>"
                + "</div>" + "</td>" + "</tr>" + "<tr>" + "<td>" + "<div class=\"bd\">"
                + "<div style=\"width:470px\"> "
                + messageSource.getMessage(CREATE_ERROR,
                        new Object[] { exceptionCode, ControllerUtils.getInstance().getFormattedCurrentTime() },
                        (Locale) request.getSession()
                                .getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME))
                + "<br/> " + "</div>" + "</div>" + "</td>" + "<td>" + "</td>" + "</tr>" + "</table>"
                + "<div class=\"ft\">&nbsp;</div>" + "</div>" + "<script> "
                + "if(typeof(YAHOO.widget.Module) != \"undefined\") { "
                + "YAHOO.audit.errorsContainer = new YAHOO.widget.Module(\"errorsContainer\", {visible:true} ); "
                + "YAHOO.audit.errorsContainer.render() ;" + "YAHOO.audit.errorsContainer.show();"
                + "YAHOO.util.Event.addListener(\"closeErrors\", \"click\", function () {   "
                + "YAHOO.audit.errorsContainer.hide();" + "YAHOO.audit.errorsContainer.destroy(); "
                + "}, YAHOO.audit.errorsContainer, true);" + "}" + "</script> </body></html>");
        response.getWriter().flush();
    } finally {
        if (sos != null) {
            //Flushing and Closing OutputStream
            sos.flush();
            sos.close();
            logger.debug("**** servlet output stream closed.");
        }
    }
    logger.debug("doPost END");
    //list all the tasks performed
    logger.debug(sw.prettyPrint());
    sw.stop();
}