List of usage examples for javax.activation DataHandler getName
public String getName()
From source file:org.shredzone.cilla.admin.AbstractImageBean.java
/** * Creates a {@link StreamedContent} for the given {@link DataHandler}, with the image * having the given width and height. The aspect ratio is kept. A PNG type image is * returned.//from w w w.j av a2s. c o m * <p> * <em>NOTE:</em> The scaled image is cached related to the {@link DataHandler}. Thus, * it is not possible to create different sizes of the same {@link DataHandler} using * this method. A weak cache is used, to keep the memory footprint as small as * possible. * * @param dh * {@link DataHandler} to stream * @param process * Width, height and image type to be used * @return {@link StreamedContent} containing that image */ protected StreamedContent createStreamedContent(DataHandler dh, ImageProcessing process) { byte[] scaledData = null; if (dh != null) { scaledData = weakScaleCache.get(dh); if (scaledData == null) { try { BufferedImage image = ImageIO.read(dh.getInputStream()); if (image != null) { BufferedImage scaled = scale(image, process.getWidth(), process.getHeight()); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { ImageIO.write(scaled, process.getType().getFormatName(), bos); scaledData = bos.toByteArray(); } if (weakScaleCache.size() < maxCache) { weakScaleCache.put(dh, scaledData); } } } catch (IOException ex) { log.error("Exception while streaming scaled content: " + dh.getName(), ex); } } } if (scaledData != null) { return new DefaultStreamedContent(new ByteArrayInputStream(scaledData), process.getType().getContentType()); } else { return createEmptyStreamedContent(); } }
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(""); }/* ww w . j a va 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; }
From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java
protected MultipartRequestEntity createMultiPart(MuleMessage msg, EntityEnclosingMethod method) throws Exception { Part[] parts;/* www .j a va 2s . c om*/ int i = 0; if (msg.getPayload() instanceof NullPayload) { parts = new Part[msg.getOutboundAttachmentNames().size()]; } else { parts = new Part[msg.getOutboundAttachmentNames().size() + 1]; parts[i++] = new FilePart("payload", new ByteArrayPartSource("payload", msg.getPayloadAsBytes())); } for (final Iterator<String> iterator = msg.getOutboundAttachmentNames().iterator(); iterator .hasNext(); i++) { final String attachmentNames = iterator.next(); String fileName = attachmentNames; final DataHandler dh = msg.getOutboundAttachment(attachmentNames); if (dh.getDataSource() instanceof StringDataSource) { final StringDataSource ds = (StringDataSource) dh.getDataSource(); parts[i] = new StringPart(ds.getName(), IOUtils.toString(ds.getInputStream())); } else { if (dh.getDataSource() instanceof FileDataSource) { fileName = ((FileDataSource) dh.getDataSource()).getFile().getName(); } else if (dh.getDataSource() instanceof URLDataSource) { fileName = ((URLDataSource) dh.getDataSource()).getURL().getFile(); // Don't use the whole file path, just the file name final int x = fileName.lastIndexOf("/"); if (x > -1) { fileName = fileName.substring(x + 1); } } parts[i] = new FilePart(dh.getName(), new ByteArrayPartSource(fileName, IOUtils.toByteArray(dh.getInputStream())), dh.getContentType(), null); } } return new MultipartRequestEntity(parts, method.getParams()); }
From source file:edu.harvard.i2b2.fr.ws.FileRepositoryService.java
public OMElement recvfileRequest(OMElement request) { LoaderQueryRequestDelegate queryDelegate = new LoaderQueryRequestDelegate(); OMElement responseElement = null;// ww w .j ava 2 s.c om FileDataSource fileDataSource; DataHandler fileDataHandler; try { String requestXml = request.toString(); if (requestXml.indexOf("<soapenv:Body>") > -1) { requestXml = requestXml.substring(requestXml.indexOf("<soapenv:Body>") + 14, requestXml.indexOf("</soapenv:Body>")); } RecvfileRequestHandler handler = new RecvfileRequestHandler(requestXml); String response = queryDelegate.handleRequest(requestXml, handler); String filename = handler.getFilename(); // We can obtain the request (incoming) MessageContext as follows MessageContext inMessageContext = MessageContext.getCurrentMessageContext(); // We can obtain the operation context from the request message // context OperationContext operationContext = inMessageContext.getOperationContext(); MessageContext outMessageContext = operationContext .getMessageContext(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); outMessageContext.setDoingSwA(true); outMessageContext.setDoingREST(false); if (!filename.equals("")) { fileDataSource = new FileDataSource(filename); fileDataHandler = new DataHandler(fileDataSource); // use requested filename as content ID outMessageContext.addAttachment(handler.getRequestedFilename(), fileDataHandler); outMessageContext.setDoingMTOM(false); outMessageContext.setDoingSwA(true); responseElement = buildOMElementFromString(response, fileDataHandler.getName()); } else { log.error("where did the file go? "); } } catch (XMLStreamException e) { log.error("xml stream exception", e); } catch (I2B2Exception e) { log.error("i2b2 exception", e); } catch (Throwable e) { log.error("Throwable", e); } return responseElement; }
From source file:com.collabnet.ccf.pi.cee.pt.v50.ProjectTrackerReader.java
@Override public List<GenericArtifact> getArtifactAttachments(Document syncInfo, GenericArtifact artifactData) { String artifactId = artifactData.getSourceArtifactId(); String artifactIdentifier = artifactId.substring(artifactId.lastIndexOf(":") + 1); Date lastModifiedDate = this.getLastModifiedDate(syncInfo); long fromTime = lastModifiedDate.getTime(); // long toTime = System.currentTimeMillis(); TrackerArtifactType trackerArtifactType = this.getTrackerArtifactTypeForArtifactId(syncInfo, artifactId); ArtifactType[] ata = new ArtifactType[1]; ata[0] = new ArtifactType(trackerArtifactType.getTagName(), trackerArtifactType.getNamespace(), trackerArtifactType.getDisplayName()); ArrayList<GenericArtifact> attachmentGAs = new ArrayList<GenericArtifact>(); TrackerWebServicesClient twsclient = null; try {/*from ww w . j a v a 2 s. co m*/ twsclient = this.getConnection(syncInfo); ArtifactHistoryList ahl = ProjectTrackerReader.artifactHistoryList.get(); History historyList[] = null; if (ahl != null) historyList = ahl.getHistory(); if (historyList != null) { for (History history : historyList) { HistoryTransaction[] transactions = history.getHistoryTransaction(); int transactionsCount = transactions == null ? 0 : transactions.length; for (int i = 0; i < transactionsCount; i++) { HistoryTransaction ht = transactions[i]; String modifiedBy = ht.getModifiedBy(); if ((!getConnectorUserDisplayName().equals(modifiedBy) || !isIgnoreConnectorUserUpdates()) && (!modifiedBy.equals( getResyncUserDisplayName() == null ? "" : getResyncUserDisplayName()) || !isIgnoreConnectorUserUpdates()) && ht.getModifiedOn() > fromTime) { HistoryActivity[] haa = ht.getHistoryActivity(); for (HistoryActivity ha : haa) { String historyArtifactId = ha.getArtifactId(); if (historyArtifactId.equals(artifactIdentifier)) { if (ha.getTagName().equals(ATTACHMENT_TAG_NAME)) { if (ha.getType().equals(ATTACHMENT_ADDED_HISTORY_ACTIVITY_TYPE)) { String[] attachmentIds = ha.getNewValue(); for (String attachmentId : attachmentIds) { if (attachmentId == null || attachmentIDNameMap == null) continue; String attachmentName = null; String attachmentDescription = null; ClientArtifactAttachment attachment = attachmentIDNameMap .get(attachmentId); if (attachment == null) { log.warn("Attachment with id " + attachmentId + " does not exist!"); continue; } attachmentName = attachment.getAttachmentName(); attachmentDescription = attachment.getDescription(); if (StringUtils.isEmpty(attachmentName)) { attachmentName = "PT-Attachment" + attachmentId + ".file"; log.warn( "Could not determine attachment name for attachment id " + attachmentId); } GenericArtifact ga = new GenericArtifact(); ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE); ga.setSourceArtifactLastModifiedDate( artifactData.getSourceArtifactLastModifiedDate()); ga.setArtifactMode( GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT); ga.setDepParentSourceArtifactId(artifactId); ga.setSourceArtifactId(attachmentId); ga.setSourceArtifactVersion( artifactData.getSourceArtifactVersion()); GenericArtifactField contentTypeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_TYPE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); contentTypeField .setFieldValue(AttachmentMetaData.AttachmentType.DATA); contentTypeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); contentTypeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField sourceURLField = ga.addNewField( AttachmentMetaData.ATTACHMENT_SOURCE_URL, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); sourceURLField .setFieldValue(AttachmentMetaData.AttachmentType.LINK); sourceURLField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); sourceURLField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField nameField = ga.addNewField( AttachmentMetaData.ATTACHMENT_NAME, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); nameField.setFieldValue(attachmentName); nameField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); nameField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField descriptionField = ga.addNewField( AttachmentMetaData.ATTACHMENT_DESCRIPTION, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); descriptionField.setFieldValue(attachmentDescription); descriptionField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); descriptionField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField mimeTypeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_MIME_TYPE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); mimeTypeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); mimeTypeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); long size = 0; DataHandler handler = null; try { handler = twsclient.getDataHandlerForAttachment( artifactIdentifier, attachmentId); } catch (WSException e) { int code = e.getCode(); if (code == 214) { continue; } else throw e; } String contentType = handler.getContentType(); mimeTypeField.setFieldValue(contentType); String axisFileName = handler.getName(); File attachmentAxisFile = new File(axisFileName); size = attachmentAxisFile.length(); long maxAttachmentSize = this.getMaxAttachmentSizePerArtifact(); if (size > maxAttachmentSize) { log.warn("Attachment " + attachmentName + " is of size " + size + " bytes." + " This is more than the configured maximum attachment size" + " that can be shipped in an artifact"); continue; } if (!this.isShipAttachmentsWithArtifact()) { File tempFile = null; FileOutputStream fos = null; FileInputStream fis = null; try { if (attachmentAxisFile.exists()) { byte[] bytes = new byte[1024 * 3]; tempFile = File.createTempFile("PT_Attachment", ".file"); String attachmentDataFile = tempFile.getAbsolutePath(); int readBytes = 0; fos = new FileOutputStream(tempFile); fis = new FileInputStream(attachmentAxisFile); while ((readBytes = fis.read(bytes)) != -1) { fos.write(bytes, 0, readBytes); } fos.close(); GenericArtifactField attachmentDataFileField = ga .addNewField( AttachmentMetaData.ATTACHMENT_DATA_FILE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); attachmentDataFileField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); attachmentDataFileField .setFieldValue(attachmentDataFile); attachmentDataFileField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); bytes = null; } } catch (IOException e) { String message = "Could not write attachment content to temp file." + " Shipping the attachment with the artifact."; log.error(message, e); throw new CCFRuntimeException(message, e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.warn("Could not close input stream for " + attachmentAxisFile.getAbsolutePath()); } } if (fos != null) { try { fos.close(); } catch (IOException e) { String filename = ""; if (tempFile != null) { filename = tempFile.getAbsolutePath(); } log.warn("Could not close output stream for " + filename); } } } } else { InputStream is = handler.getInputStream(); byte[] bytes = new byte[(int) size]; is.read(bytes); is.close(); ga.setRawAttachmentData(bytes); } GenericArtifactField sizeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_SIZE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); sizeField.setFieldValue(size); sizeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); sizeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); populateSrcAndDestForAttachment(syncInfo, ga); attachmentGAs.add(ga); } } else if (ha.getType().equals(ATTACHMENT_DELETED_HISTORY_ACTIVITY_TYPE)) { String[] attachmentIds = ha.getOldValue(); for (String attachmentId : attachmentIds) { if (attachmentId == null) continue; GenericArtifact ga = new GenericArtifact(); ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE); ga.setSourceArtifactLastModifiedDate( artifactData.getSourceArtifactLastModifiedDate()); ga.setArtifactMode( GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT); ga.setDepParentSourceArtifactId(artifactId); ga.setSourceArtifactId(attachmentId); ga.setSourceArtifactVersion( artifactData.getSourceArtifactVersion()); GenericArtifactField contentTypeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_TYPE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); contentTypeField .setFieldValue(AttachmentMetaData.AttachmentType.DATA); contentTypeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); contentTypeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); populateSrcAndDestForAttachment(syncInfo, ga); attachmentGAs.add(ga); } } else if (ha.getType().equals(URL_ADDED_HISTORY_ACTIVITY_TYPE)) { String[] attachmentIds = ha.getNewValue(); for (String attachmentId : attachmentIds) { if (linkIDNameMap == null || linkIDNameMap.size() == 0) continue; Set<Entry<String, ClientArtifactAttachment>> linkIDEntry = linkIDNameMap .entrySet(); Iterator<Entry<String, ClientArtifactAttachment>> linkEntryIt = linkIDEntry .iterator(); String attachmentName = null; String attachmentDescription = null; if (linkEntryIt.hasNext()) { Entry<String, ClientArtifactAttachment> entry = linkEntryIt .next(); ClientArtifactAttachment clientArtifactAttachment = entry .getValue(); attachmentName = clientArtifactAttachment.getAttachmentName(); attachmentDescription = clientArtifactAttachment .getDescription(); attachmentId = entry.getKey(); } GenericArtifact ga = new GenericArtifact(); ga.setArtifactAction(GenericArtifact.ArtifactActionValue.CREATE); ga.setSourceArtifactLastModifiedDate( artifactData.getSourceArtifactLastModifiedDate()); ga.setArtifactMode( GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT); ga.setDepParentSourceArtifactId(artifactId); ga.setSourceArtifactId(attachmentId); ga.setSourceArtifactVersion( artifactData.getSourceArtifactVersion()); GenericArtifactField contentTypeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_TYPE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); contentTypeField .setFieldValue(AttachmentMetaData.AttachmentType.LINK); contentTypeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); contentTypeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField sourceURLField = ga.addNewField( AttachmentMetaData.ATTACHMENT_SOURCE_URL, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); sourceURLField.setFieldValue(attachmentName); sourceURLField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); sourceURLField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField descriptionField = ga.addNewField( AttachmentMetaData.ATTACHMENT_DESCRIPTION, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); descriptionField.setFieldValue(attachmentDescription); descriptionField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); descriptionField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); GenericArtifactField nameField = ga.addNewField( AttachmentMetaData.ATTACHMENT_NAME, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); nameField.setFieldValue(attachmentName); nameField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); nameField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); populateSrcAndDestForAttachment(syncInfo, ga); attachmentGAs.add(ga); } } else if (ha.getType().equals(URL_DELETED_HISTORY_ACTIVITY_TYPE)) { String[] attachmentIds = ha.getOldValue(); for (String attachmentId : attachmentIds) { if (attachmentId == null) continue; GenericArtifact ga = new GenericArtifact(); ga.setArtifactAction(GenericArtifact.ArtifactActionValue.DELETE); ga.setSourceArtifactLastModifiedDate( artifactData.getSourceArtifactLastModifiedDate()); ga.setArtifactMode( GenericArtifact.ArtifactModeValue.CHANGEDFIELDSONLY); ga.setArtifactType(GenericArtifact.ArtifactTypeValue.ATTACHMENT); ga.setDepParentSourceArtifactId(artifactId); ga.setSourceArtifactId(attachmentId); ga.setSourceArtifactVersion( artifactData.getSourceArtifactVersion()); GenericArtifactField contentTypeField = ga.addNewField( AttachmentMetaData.ATTACHMENT_TYPE, GenericArtifactField.VALUE_FIELD_TYPE_FLEX_FIELD); contentTypeField .setFieldValue(AttachmentMetaData.AttachmentType.DATA); contentTypeField.setFieldAction( GenericArtifactField.FieldActionValue.REPLACE); contentTypeField.setFieldValueType( GenericArtifactField.FieldValueTypeValue.STRING); populateSrcAndDestForAttachment(syncInfo, ga); attachmentGAs.add(ga); } } } } } } } } } } catch (Exception e) { String message = "Exception while getting the attachment data"; log.error(message, e); throw new CCFRuntimeException(message, e); } finally { ProjectTrackerReader.artifactHistoryList.set(null); this.attachmentIDNameMap = null; this.linkIDNameMap = null; if (twsclient != null) { getConnectionManager().releaseConnection(twsclient); twsclient = null; } } return attachmentGAs; }
From source file:org.bimserver.webservices.Service.java
@Override public Integer checkin(final Long poid, final String comment, String deserializerName, Long fileSize, DataHandler dataHandler, Boolean merge, Boolean sync) throws ServerException, UserException { requireAuthenticationAndRunningServer(); final DatabaseSession session = bimServer.getDatabase().createSession(); String username = "Unknown"; String userUsername = "Unknown"; try {//from w w w. ja v a2s.co m User user = (User) session.get(StorePackage.eINSTANCE.getUser(), currentUoid, false, null); username = user.getName(); userUsername = user.getUsername(); } finally { session.close(); } try { File homeDirIncoming = new File(bimServer.getHomeDir(), "incoming"); if (!homeDirIncoming.isDirectory()) { homeDirIncoming.mkdir(); } File userDirIncoming = new File(homeDirIncoming, userUsername); if (!userDirIncoming.exists()) { userDirIncoming.mkdir(); } InputStream inputStream = null; String fileName = dataHandler.getName(); if (fileName == null || fileName.trim().equals("")) { inputStream = dataHandler.getInputStream(); } else { if (fileName.contains("/")) { fileName = fileName.substring(fileName.lastIndexOf("/") + 1); } if (fileName.contains("\\")) { fileName = fileName.substring(fileName.lastIndexOf("\\") + 1); } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); fileName = dateFormat.format(new Date()) + "-" + fileName; File file = new File(userDirIncoming, fileName); inputStream = new MultiplexingInputStream(dataHandler.getInputStream(), new FileOutputStream(file)); } try { EmfDeserializer deserializer = bimServer.getEmfDeserializerFactory() .createDeserializer(deserializerName); if (deserializer == null) { throw new UserException("Deserializer " + deserializerName + " not found"); } try { deserializer.init(bimServer.getPluginManager().requireSchemaDefinition()); } catch (PluginException e) { throw new UserException(e); } IfcModelInterface model = deserializer.read(inputStream, fileName, false, fileSize); if (model.size() == 0) { throw new DeserializeException("Cannot checkin empty model"); } CheckinDatabaseAction checkinDatabaseAction = new CheckinDatabaseAction(bimServer, null, accessMethod, poid, currentUoid, model, comment, merge, true); LongCheckinAction longAction = new LongCheckinAction(bimServer, username, userUsername, currentUoid, checkinDatabaseAction); bimServer.getLongActionManager().start(longAction); if (sync) { longAction.waitForCompletion(); } return longAction.getId(); } catch (UserException e) { throw e; } catch (DeserializeException e) { throw new UserException(e); } finally { inputStream.close(); } } catch (UserException e) { throw e; } catch (Throwable e) { LOGGER.error("", e); throw new ServerException(e); } finally { session.close(); } }
From source file:es.pode.publicacion.negocio.servicios.SrvPublicacionServiceImpl.java
/** * Publica objetos en formato PIF (ZIP). * /*from w w w. j av a 2 s.c om*/ * @param pif * Objeto en formato PIF que se va a publicar. * @param idUsuario * Identificador del usuario. * @param comentarios * Comentarios que puede llevar la publicacin. * @param sobrescribir * Indica si la carga se ha de realizar sobrescribiendo el ODE si * este ya existe. Valores s/n. * @return se retorna un VO con el error que se ha producido en el caso de * detectarse algun problema. * @throws Exception * */ protected ResultadoOperacionVO handlePublicarPIF(DataHandler pif, String idUsuario, String comentarios, String sobrescribir, String titulo) throws Exception { try { String idODE = String.valueOf(System.currentTimeMillis()); // creacion logger.info("Publicando PIF (de carga) utilizando identificador[" + idODE + "] idUsuario[" + idUsuario + "] y comentarios[" + comentarios + "]"); ResultadoOperacionVO res = handleCreacion(idODE, idUsuario, comentarios, titulo); if (!res.getIdResultado().equals(SIN_ERRORES)) { if (logger.isDebugEnabled()) logger.error("ERROR[" + res.getIdResultado() + "][" + res.getDescripcion() + "]:publicando PIF con fichero[" + pif != null ? pif.getName() : "null" + "] idusuario[" + idUsuario + "] comentarios[" + comentarios + "] idODE[" + res.getIdODE()); return res; } SrvLocalizadorService localizadorService = this.getSrvLocalizadorService(); LocalizadorVO localizadorNP = localizadorService.consultaLocalizador(idODE); logger.debug("Publicando PIF (de carga):Encontramos localizador con identificador[" + localizadorNP.getIdentificador() + "] usuario[" + localizadorNP.getIdUsuario() + "] MEC[" + localizadorNP.getMec() + "] path[" + localizadorNP.getPath() + "] URL[" + localizadorNP.getUrl() + "]"); // empezamos a descomprimir el pif y guardar lo que nos devuelve // en un directorio temporal String pathtemp = ""; pathtemp = localizadorNP.getPath() + getPropertyValue("carpeta.temporal") + "/" + localizadorNP.getIdentificador() + ".zip"; File ficheroZip = new File(pathtemp); (ficheroZip.getParentFile()).mkdirs(); ficheroZip.createNewFile(); ficheroZip.deleteOnExit(); FileOutputStream fos = new FileOutputStream(ficheroZip); pif.writeTo(fos); String pathtempDestino = localizadorNP.getPath(); File destinoTemporal = new File(pathtempDestino); destinoTemporal.mkdirs(); destinoTemporal.deleteOnExit(); fos.close(); if (logger.isDebugEnabled()) logger.debug("Publicando PIF (de carga):Comenzamos a descomprimir el PIF" + ficheroZip.getPath() + "" + " y guardar en:" + pathtemp + ";"); if (this.getZipDao().esZip(pathtemp)) try { this.getZipDao().descomprimir(ficheroZip.getPath(), pathtempDestino); } catch (Exception e1) { logger.error("Publicando PIF (de carga):Error descomprimiendo fichero [" + pathtemp + "], con nombre[" + pif.getName() + "]", e1); this.handleEliminar(idODE, idUsuario); return new ResultadoOperacionVO(ERROR_DESCOMPRIMIENDO_FICHERO_ZIP, getPropertyValueI18n(ERROR_DESCOMPRIMIENDO_FICHERO_ZIP), idODE, new Long(0)); } else { logger.error("Error de formato descomprimiendo fichero [" + pathtemp + "], con nombre[" + pif.getName() + "]"); this.handleEliminar(idODE, idUsuario); return new ResultadoOperacionVO(ERROR_FORMATO_ZIP, getPropertyValueI18n(ERROR_FORMATO_ZIP), idODE, new Long(0)); } // copiar los esquemas por si acaso no los trajese try { this.copiarEsquemas(pathtempDestino); } catch (Exception e1) { logger.error("Publicando PIF (de carga):No se pudieron copiar los esquemas al importar un pif: ", e1); this.handleEliminar(idODE, idUsuario); return new ResultadoOperacionVO(ERROR_COPIANDO_ESQUEMAS, getPropertyValueI18n(ERROR_COPIANDO_ESQUEMAS), idODE, new Long(0)); } // validador SrvValidadorService validadorService = this.getSrvValidadorService(); ValidaVO valid = validadorService.validarCargaOde(localizadorNP.getPath()); logger.info("Publicando PIF (de carga):Validando el ODE [" + localizadorNP.getIdentificador() + "]"); if (valid.getEsValidoManifest().booleanValue()) { // proponiendo catalogacion logger.info("Publicando PIF (de carga):Proponemos para catalogacion el ODE con identificador[" + idODE + "], idUsuario[" + idUsuario + "] y comentarios[" + comentarios + "]"); // Proponemos para catalogar, pero sin validar ya que ya lo hemos hecho this.proponerCatalogacion(idODE, idUsuario, comentarios, titulo, false); // proponer publicacion logger.info("Publicando PIF (de carga):Proponemos para publicacion el ODE con identificador[" + idODE + "], idUsuario[" + idUsuario + "] y comentarios[" + comentarios + "]"); // Proponemos para publicar, pero sin validar ya que ya lo hemos hecho this.proponerPublicacion(idODE, idUsuario, comentarios, titulo, false); // publicar // llamada a un metodo "validadorService.validarMec" que devuelve null si el mec es malo o no existe // y devuelve el valor del mec, si ste, es bueno String mec = validadorService.validarMec(localizadorNP.getPath()); if (mec == null) { mec = this.handleGeneraMEC(localizadorNP.getPath()); logger.info("Publicando PIF (de carga):MEC del ODE [" + localizadorNP.getPath() + "] invalido. Generado nuevo MEC [" + mec + "]"); } // si no comprobamos que no est repetido, en cuyo caso lanzamos una excepcin else { IdODECriteria criteria = new IdODECriteria(mec, null); if (!this.getTransicionDao().buscarEstadoPorCriterioIdODE(criteria).isEmpty()) { logger.info("Publicando PIF (de carga):El ODE [" + localizadorNP.getPath() + "] con mec[" + mec + "] ya existia en la plataforma."); if (SOBRESCRIBIR_PUBLICADOS_NO.equals(sobrescribir)) { // solo necesitamos comprobar la ltima transicin, pq el mec no cambia nunca // Eliminamos todo lo que ha producido el intento de insercion de este ODE // que al final ha resultado repetido this.handleEliminar(idODE, idUsuario); logger.warn("Publicando PIF (de carga):El ODE [" + localizadorNP.getPath() + "] con mec[" + mec + "] ya exista y no lo sobrescribimos."); return new ResultadoOperacionVO(MEC_YA_EXISTE, getPropertyValueI18n(MEC_YA_EXISTE), idODE, new Long(0)); } else if (SOBRESCRIBIR_PUBLICADOS_SI.equals(sobrescribir)) { logger.info("Publicando PIF (de carga):El ODE [" + localizadorNP.getPath() + "] con mec[" + mec + "] existe. Eliminamos rastro para sobrescribirlo."); eliminaODEPublicado(mec); } else { logger.error( "Publicando PIF (de carga):El mec ya exista y no hay criterio claro de sobrescritura[" + sobrescribir + "]"); this.handleEliminar(idODE, idUsuario); return new ResultadoOperacionVO(MEC_YA_EXISTE, getPropertyValueI18n(MEC_YA_EXISTE), idODE, new Long(0)); } } } // vamos a comprobar que el mec no existe ya EstadoVO estado = this.obtenEstadoPorIdODE(idODE, LdapUserDetailsUtils.getIdioma()); logger.info("Publicando PIF (de carga):Publicando ODE con identificador [" + idODE + "] en estado[" + estado.getClave() + "] con usuario[" + idUsuario + "] y comentarios[" + comentarios + "]."); if (estado.getClave().equals(PROPUESTO)) { // los odes que se cargan masivamente (de momento) no // tenemos que introducir informacin // de licencias ResultadoOperacionVO retorno = publicar_aux(idODE, mec, idUsuario, comentarios, null, "", "", true); if (!SIN_ERRORES.equals(retorno.getIdResultado())) { // Si la publicacion no ha ido bien, entendemos que ha tenido error y tenemos que borrar // todo lo que el intento de publicacion ha creado en la plataforma logger.error("Publicando PIF (de carga):Error intentando publicar un ODE via PIF[" + retorno.getIdResultado() + "] con id[" + idODE + "]."); this.handleEliminar(idODE, idUsuario); } else logger.info("Publicando PIF (de carga):Publicado ODE con identificador[" + idODE + "] a mec[" + mec + "] via PIF."); return retorno; } else { logger.warn("Publicando PIF (de carga):error no se ha podido continuar ya que el ODE ya [" + mec + "], est creado"); PublicarException e = new PublicarException( "ERROR el ODE[" + mec + "]ya esta creado en la plataforma"); logger.warn(e); return new ResultadoOperacionVO(ODE_YA_CREADO_EN_PLATAFORMA, getPropertyValueI18n(ODE_YA_CREADO_EN_PLATAFORMA), idODE, new Long(0)); } } // if (valid.getEsValidoManifest().booleanValue()) else { logger.error("Publicando PIF (de carga):ERROR: no se ha validado el ODE [" + localizadorNP.getPath() + "]correctamente, cdigo[" + valid.getResultadoValidacion() + "] "); this.handleEliminar(localizadorNP.getIdentificador(), idUsuario); return new ResultadoOperacionVO(SrvPublicacionServiceImpl.ERROR_DE_VALIDACION, valid.getResultadoValidacion(), idODE, new Long(0)); } } // try catch (PublicarException e) { logger.error( "Publicando PIF (de carga):Se ha producido un error al publicarPIF del tipo PublicarException", e); throw e; } catch (Exception e) { logger.error("Publicando PIF (de carga):Se ha producido un error al publicarPIF del tipo Desconocido", e); throw e; } }