List of usage examples for java.util Date toString
public String toString()
where:dow mon dd hh:mm:ss zzz yyyy
From source file:com.eucalyptus.walrus.WalrusFSManager.java
@Override public GetObjectExtendedResponseType getObjectExtended(GetObjectExtendedType request) throws WalrusException { GetObjectExtendedResponseType reply = (GetObjectExtendedResponseType) request.getReply(); Date ifModifiedSince = request.getIfModifiedSince(); Date ifUnmodifiedSince = request.getIfUnmodifiedSince(); String ifMatch = request.getIfMatch(); String ifNoneMatch = request.getIfNoneMatch(); boolean returnCompleteObjectOnFailure = request.getReturnCompleteObjectOnConditionFailure(); String bucketName = request.getBucket(); String objectKey = request.getKey(); Boolean getData = request.getGetData(); if (getData == null) { getData = false;//from ww w .ja va 2 s .co m } EntityWrapper<BucketInfo> db = EntityWrapper.get(BucketInfo.class); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.queryEscape(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null; boolean versioning = false; if (bucket.isVersioningEnabled()) { versioning = true; } EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class); ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, objectKey); List<ObjectInfo> objectInfos = dbObject.queryEscape(searchObjectInfo); if (objectInfos.size() > 0) { ObjectInfo objectInfo = objectInfos.get(0); String etag = objectInfo.getEtag(); String objectName = objectInfo.getObjectName(); Long byteRangeStart = request.getByteRangeStart(); Long byteRangeEnd = request.getByteRangeEnd(); DefaultHttpResponse httpResponse = null; if (byteRangeStart != null || byteRangeEnd != null) { httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.PARTIAL_CONTENT); } else { httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); } if (byteRangeStart == null) { byteRangeStart = 0L; } if (byteRangeEnd == null) { byteRangeEnd = -1L; } if (byteRangeEnd == -1 || (byteRangeEnd + 1) > objectInfo.getSize()) { byteRangeEnd = objectInfo.getSize() - 1; } if ((byteRangeStart > objectInfo.getSize()) || (byteRangeStart > byteRangeEnd) || (byteRangeStart < 0 || byteRangeEnd < 0)) { db.rollback(); throw new InvalidRangeException("Range: " + byteRangeStart + "-" + byteRangeEnd + "object: " + bucketName + "/" + objectKey); } if (ifMatch != null) { if (!ifMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException(objectKey + " etag: " + etag); } } if (ifNoneMatch != null) { if (ifNoneMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " ETag: " + etag); } } Date lastModified = objectInfo.getLastModified(); if (ifModifiedSince != null) { if ((ifModifiedSince.getTime() >= lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " LastModified: " + lastModified.toString()); } } if (ifUnmodifiedSince != null) { if ((ifUnmodifiedSince.getTime() < lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException( objectKey + " lastModified: " + lastModified.toString()); } } if (request.getGetMetaData()) { ArrayList<MetaDataEntry> metaData = new ArrayList<MetaDataEntry>(); List<MetaDataInfo> metaDataInfos = objectInfo.getMetaData(); for (MetaDataInfo metaDataInfo : metaDataInfos) { metaData.add(new MetaDataEntry(metaDataInfo.getName(), metaDataInfo.getValue())); } reply.setMetaData(metaData); } Long size = byteRangeEnd - byteRangeStart + 1; String contentType = objectInfo.getContentType(); String contentDisposition = objectInfo.getContentDisposition(); db.commit(); if (logData != null) { updateLogData(bucket, logData); logData.setObjectSize(size); } String versionId = null; if (versioning) { versionId = objectInfo.getVersionId() != null ? objectInfo.getVersionId() : WalrusProperties.NULL_VERSION_ID; } if (request.getGetData()) { storageManager.getObject(bucketName, objectName, reply, byteRangeStart, byteRangeEnd + 1, request.getIsCompressed()); } reply.setEtag(etag); reply.setLastModified(lastModified); reply.setSize(size); reply.setContentType(contentType); reply.setContentDisposition(contentDisposition); reply.setByteRangeStart(byteRangeStart); reply.setByteRangeEnd(byteRangeEnd); reply.setVersionId(versionId); Status status = new Status(); status.setCode(200); status.setDescription("OK"); reply.setStatus(status); return reply; } else { db.rollback(); // Fix for EUCA-2782. Different exceptions are thrown based on // the request type so that the downstream logic can // differentiate if (getData) { throw new NoSuchEntityException(objectKey); } else { throw new HeadNoSuchEntityException(objectKey); } } } else { db.rollback(); // Fix for EUCA-2782. Different exceptions are thrown based on the // request type so that the downstream logic can differentiate if (getData) { throw new NoSuchBucketException(bucketName); } else { throw new HeadNoSuchBucketException(bucketName); } } }
From source file:org.etudes.component.app.melete.ModuleDB.java
void updateCalendar(Module module1, ModuleShdates moduleshdates1, String courseId) throws Exception { if (checkCalendar() == true) { //The code below adds the start and stop dates to the Calendar boolean addtoSchedule = moduleshdates1.getAddtoSchedule().booleanValue(); Date startDate = moduleshdates1.getStartDate(); Date endDate = moduleshdates1.getEndDate(); String startEventId = moduleshdates1.getStartEventId(); String endEventId = moduleshdates1.getEndEventId(); CalendarService cService = org.sakaiproject.calendar.cover.CalendarService.getInstance(); String calendarId = cService.calendarReference(courseId, SiteService.MAIN_CONTAINER); try {//from ww w .jav a 2s.c o m org.sakaiproject.calendar.api.Calendar c = cService.getCalendar(calendarId); try { if (addtoSchedule == true) { if (startDate == null) { if (startEventId != null) { logger.debug("REMOVING start event for null start date"); deleteCalendarEvent(c, startEventId); moduleshdates1.setStartEventId(null); } } else { if (startEventId == null) { logger.debug("ADDING start event for non-null start date"); String desc = endDate != null ? "This module opens today and closes " + endDate.toString() : "This module opens today"; startEventId = createCalendarEvent(c, startDate, "Opens: " + module1.getTitle(), desc); } else { logger.debug("UPDATING start event for non-nul start date"); String desc = endDate != null ? "This module opens today and closes " + endDate.toString() : "This module opens today"; startEventId = updateCalendarEvent(c, startEventId, startDate, "Opens: " + module1.getTitle(), desc); } moduleshdates1.setStartEventId(startEventId); } if (endDate == null) { if (endEventId != null) { logger.debug("REMOVING end event for null end date"); deleteCalendarEvent(c, endEventId); moduleshdates1.setEndEventId(null); } } if (endDate != null) { if (endEventId == null) { logger.debug("ADDING end event for non-null end date"); String desc = "This module closes today"; endEventId = createCalendarEvent(c, endDate, "Closes: " + module1.getTitle(), desc); } else { logger.debug("UPDATING end event for non-null end date"); String desc = "This module closes today"; endEventId = updateCalendarEvent(c, endEventId, endDate, "Closes: " + module1.getTitle(), desc); } moduleshdates1.setEndEventId(endEventId); } } else { if (startEventId != null) { logger.debug("REMOVING start event for false flag"); deleteCalendarEvent(c, startEventId); moduleshdates1.setStartEventId(null); } if (endEventId != null) { logger.debug("REMOVING end event for false flag"); deleteCalendarEvent(c, endEventId); moduleshdates1.setEndEventId(null); } } } catch (PermissionException ee) { logger.warn("PermissionException while adding to calendar"); } catch (Exception ee) { logger.error("Some other exception while adding to calendar " + ee.getMessage()); } // try-catch } catch (Exception ex) { logger.error("Exception thrown while getting Calendar"); } updateModuleShdates((ModuleShdates) moduleshdates1); } }
From source file:com.ext.portlet.epsos.EpsosHelperService.java
private String xmlEncodeDate(Date date) { if (date == null) return ""; try {/*from ww w . ja v a2 s .c o m*/ GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance(); cal.setTime(date); XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal); return xmlCal.toXMLFormat(); } catch (Exception e) { return date.toString(); } }
From source file:edu.ucsb.eucalyptus.cloud.ws.WalrusManager.java
public GetObjectExtendedResponseType getObjectExtended(GetObjectExtendedType request) throws EucalyptusCloudException { GetObjectExtendedResponseType reply = (GetObjectExtendedResponseType) request.getReply(); Long byteRangeStart = request.getByteRangeStart(); if (byteRangeStart == null) { byteRangeStart = 0L;//from ww w . ja v a 2 s . c o m } Long byteRangeEnd = request.getByteRangeEnd(); if (byteRangeEnd == null) { byteRangeEnd = -1L; } Date ifModifiedSince = request.getIfModifiedSince(); Date ifUnmodifiedSince = request.getIfUnmodifiedSince(); String ifMatch = request.getIfMatch(); String ifNoneMatch = request.getIfNoneMatch(); boolean returnCompleteObjectOnFailure = request.getReturnCompleteObjectOnConditionFailure(); String bucketName = request.getBucket(); String objectKey = request.getKey(); String userId = request.getUserId(); Status status = new Status(); EntityWrapper<BucketInfo> db = WalrusControl.getEntityWrapper(); BucketInfo bucketInfo = new BucketInfo(bucketName); List<BucketInfo> bucketList = db.query(bucketInfo); if (bucketList.size() > 0) { BucketInfo bucket = bucketList.get(0); BucketLogData logData = bucket.getLoggingEnabled() ? request.getLogData() : null; boolean versioning = false; if (bucket.isVersioningEnabled()) versioning = true; EntityWrapper<ObjectInfo> dbObject = db.recast(ObjectInfo.class); ObjectInfo searchObjectInfo = new ObjectInfo(bucketName, objectKey); List<ObjectInfo> objectInfos = dbObject.query(searchObjectInfo); if (objectInfos.size() > 0) { ObjectInfo objectInfo = objectInfos.get(0); if (objectInfo.canRead(userId)) { String etag = objectInfo.getEtag(); String objectName = objectInfo.getObjectName(); if (byteRangeEnd == -1) byteRangeEnd = objectInfo.getSize(); if ((byteRangeStart > objectInfo.getSize()) || (byteRangeStart > byteRangeEnd) || (byteRangeEnd > objectInfo.getSize()) || (byteRangeStart < 0 || byteRangeEnd < 0)) { throw new InvalidRangeException("Range: " + byteRangeStart + "-" + byteRangeEnd + "object: " + bucketName + "/" + objectKey); } DefaultHttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); if (ifMatch != null) { if (!ifMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException(objectKey + " etag: " + etag); } } if (ifNoneMatch != null) { if (ifNoneMatch.equals(etag) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " ETag: " + etag); } } Date lastModified = objectInfo.getLastModified(); if (ifModifiedSince != null) { if ((ifModifiedSince.getTime() >= lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new NotModifiedException(objectKey + " LastModified: " + lastModified.toString()); } } if (ifUnmodifiedSince != null) { if ((ifUnmodifiedSince.getTime() < lastModified.getTime()) && !returnCompleteObjectOnFailure) { db.rollback(); throw new PreconditionFailedException( objectKey + " lastModified: " + lastModified.toString()); } } if (request.getGetMetaData()) { List<MetaDataInfo> metaDataInfos = objectInfo.getMetaData(); for (MetaDataInfo metaDataInfo : metaDataInfos) { httpResponse.addHeader(WalrusProperties.AMZ_META_HEADER_PREFIX + metaDataInfo.getName(), metaDataInfo.getValue()); } } Long size = objectInfo.getSize(); String contentType = objectInfo.getContentType(); String contentDisposition = objectInfo.getContentDisposition(); db.commit(); if (logData != null) { updateLogData(bucket, logData); logData.setObjectSize(size); } String versionId = null; if (versioning) { versionId = objectInfo.getVersionId() != null ? objectInfo.getVersionId() : WalrusProperties.NULL_VERSION_ID; } if (request.getGetData()) { if (WalrusProperties.trackUsageStatistics) { walrusStatistics.updateBytesOut(size); } storageManager.sendObject(request, httpResponse, bucketName, objectName, byteRangeStart, byteRangeEnd, size, etag, DateUtils.format(lastModified.getTime(), DateUtils.ISO8601_DATETIME_PATTERN + ".000Z"), contentType, contentDisposition, request.getIsCompressed(), versionId, logData); return null; } else { storageManager.sendHeaders(request, httpResponse, size, etag, DateUtils.format(lastModified.getTime(), DateUtils.ISO8601_DATETIME_PATTERN + ".000Z"), contentType, contentDisposition, versionId, logData); return null; } } else { db.rollback(); throw new AccessDeniedException("Key", objectKey); } } else { db.rollback(); throw new NoSuchEntityException(objectKey); } } else { db.rollback(); throw new NoSuchBucketException(bucketName); } }
From source file:org.fao.geonet.kernel.harvest.harvester.localfilesystem.LocalFsHarvesterFileVisitor.java
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (cancelMonitor.get()) { return FileVisitResult.TERMINATE; }//from w w w .j a va2s . c o m try { if (file != null && file.getFileName() != null && file.getFileName().toString() != null && (file.getFileName().toString().endsWith(".xml") || MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString()))) { result.totalMetadata++; if (LOGGER.isDebugEnabled() && result.totalMetadata % 1000 == 0) { long elapsedTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime); LOGGER.debug(result.totalMetadata + "records inserted in " + elapsedTime + " s (" + result.totalMetadata / elapsedTime + " records/s)."); } Path filePath = file.toAbsolutePath().normalize(); if (MEFLib.isValidArchiveExtensionForMEF(file.getFileName().toString())) { processMef(file, filePath); return FileVisitResult.CONTINUE; } Element xml; try { LOGGER.debug("reading file: " + filePath); xml = Xml.loadFile(file); } catch (JDOMException e) { // JDOM problem LOGGER.debug("Error loading XML from file " + filePath + ", ignoring"); if (LOGGER.isDebugEnabled()) { LOGGER.error(e); } result.badFormat++; return FileVisitResult.CONTINUE; // skip this one } catch (Throwable e) { // some other error LOGGER.debug("Error retrieving XML from file " + filePath + ", ignoring"); if (LOGGER.isDebugEnabled()) { LOGGER.error(e); } result.unretrievable++; return FileVisitResult.CONTINUE; // skip this one } // transform using importxslt if not none if (transformIt) { try { xml = Xml.transform(xml, thisXslt); } catch (Exception e) { LOGGER.debug("Cannot transform XML from file " + filePath + ", ignoring. Error was: " + e.getMessage()); result.badFormat++; return FileVisitResult.CONTINUE; // skip this one } } String schema = null; try { schema = dataMan.autodetectSchema(xml, null); } catch (Exception e) { result.unknownSchema++; } if (schema == null) { return FileVisitResult.CONTINUE; } try { params.getValidate().validate(dataMan, context, xml); } catch (Exception e) { LOGGER.debug("Cannot validate XML from file " + filePath + ", ignoring. Error was: " + e.getMessage()); result.doesNotValidate++; return FileVisitResult.CONTINUE; // skip this one } String uuid = getUuidFromFile(xml, filePath, schema); if (uuid == null || uuid.equals("")) { result.badFormat++; return FileVisitResult.CONTINUE; } String id = dataMan.getMetadataId(uuid); String changeDate = new ISODate(System.currentTimeMillis(), false).getDateAndTime(); if (id == null) { // For new record change date will be the time of metadata xml date change or the date when // the record was harvested (if can't be obtained the metadata xml date change) String createDate; // or the last modified date of the file if (params.checkFileLastModifiedForUpdate) { createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false) .getDateAndTime(); } else { try { createDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= " + uuid + " using current date for modified date"); createDate = new ISODate().toString(); } } LOGGER.debug("adding new metadata"); id = addMetadata(xml, schema, uuid, createDate); } else { // Check last modified date of the file with the record change date // to check if an update is required if (params.checkFileLastModifiedForUpdate) { Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis()); final AbstractMetadata metadata = repo.findOne(id); ISODate modified = new ISODate(); if (metadata != null && metadata.getDataInfo() != null) { modified = metadata.getDataInfo().getChangeDate(); } Date recordDate = modified.toDate(); changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime(); LOGGER.debug(" File date is: " + filePath + "filePath / record date is: " + modified); if (DateUtils.truncate(recordDate, Calendar.SECOND) .before(DateUtils.truncate(fileDate, Calendar.SECOND))) { LOGGER.debug(" Db record is older than file. Updating record with id: " + id); updateMedata(xml, id, changeDate); } else { LOGGER.debug( " Db record is not older than last modified date of file. No need for update."); result.unchangedMetadata++; } } else { id = dataMan.getMetadataId(uuid); if (id == null) { // For new record change date will be the time of metadata xml date change or the date when // the record was harvested (if can't be obtained the metadata xml date change) String createDate; // or the last modified date of the file if (params.checkFileLastModifiedForUpdate) { createDate = new ISODate(Files.getLastModifiedTime(file).toMillis(), false) .getDateAndTime(); } else { try { createDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - addMetadata - can't get metadata modified date for metadata uuid= " + uuid + ", using current date for modified date"); createDate = new ISODate().toString(); } } LOGGER.debug("adding new metadata"); id = harvester.addMetadata(xml, uuid, schema, localGroups, localCateg, createDate, aligner, false); listOfRecordsToIndex.add(Integer.valueOf(id)); result.addedMetadata++; } else { // Check last modified date of the file with the record change date // to check if an update is required if (params.checkFileLastModifiedForUpdate) { Date fileDate = new Date(Files.getLastModifiedTime(file).toMillis()); final AbstractMetadata metadata = repo.findOne(id); final ISODate modified; if (metadata != null && metadata.getDataInfo() != null) { modified = metadata.getDataInfo().getChangeDate(); } else { modified = new ISODate(); } Date recordDate = modified.toDate(); changeDate = new ISODate(fileDate.getTime(), false).getDateAndTime(); LOGGER.debug( " File date is: " + fileDate.toString() + " / record date is: " + modified); if (DateUtils.truncate(recordDate, Calendar.SECOND) .before(DateUtils.truncate(fileDate, Calendar.SECOND))) { LOGGER.debug(" Db record is older than file. Updating record with id: " + id); harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner); listOfRecordsToIndex.add(Integer.valueOf(id)); result.updatedMetadata++; } else { LOGGER.debug( " Db record is not older than last modified date of file. No need for update."); result.unchangedMetadata++; } } else { LOGGER.debug(" updating existing metadata, id is: " + id); try { changeDate = dataMan.extractDateModified(schema, xml); } catch (Exception ex) { LOGGER.error( "LocalFilesystemHarvester - updateMetadata - can't get metadata modified date for " + "metadata id= " + id + ", using current date for modified date"); changeDate = new ISODate().toString(); } harvester.updateMetadata(xml, id, localGroups, localCateg, changeDate, aligner); listOfRecordsToIndex.add(Integer.valueOf(id)); result.updatedMetadata++; } } updateMedata(xml, id, changeDate); } } listOfRecords.add(Integer.valueOf(id)); } } catch (Throwable e) { LOGGER.error("An error occurred while harvesting a local file:{}. Error is: " + e.getMessage()); } return FileVisitResult.CONTINUE; }
From source file:Sales.TabbedPaneWin.java
private void initCustom() throws Exception { ///Client/* w w w. ja va2 s . co m*/ //setting next CleientID nextClientId(); clientIdTxtF2.setText(getNextClientIdStr()); //refreshing Table try { jTable3.setModel(DbUtils.resultSetToTableModel(refreshTableClient())); } catch (ClassNotFoundException ex) { Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex); } //// ///Agreemnrt nextAgreementId(); agreementIdTxtF1.setText(getNextAgreementIdStr()); try { jTable1.setModel(DbUtils.resultSetToTableModel(OOAgreement.dispalyTableExpiary())); } catch (ClassNotFoundException ex) { Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex);//Logiing errors System.err.println(ex.getMessage()); JOptionPane.showMessageDialog(null, ex.getMessage(), "Unknown Error", JOptionPane.ERROR_MESSAGE); } /////// ///Invoice nextInvoiceId(); invoiceNoTxtF.setText(getNextInvoiceIdStr()); incrementations.nextOrderId(); clientIdTxtF1.setText(incrementations.getNextOrderIdStr()); try { selectItemsTable.setModel(DbUtils.resultSetToTableModel(refreshTableInvoice())); } catch (ClassNotFoundException ex) { Logger.getLogger(TabbedPaneWin.class.getName()).log(Level.SEVERE, null, ex); } /// jLabel45.setVisible(false); jLabel70.setVisible(false); jLabel73.setVisible(false); jLabel72.setVisible(false); jLabel18.setVisible(false); jLabel43.setVisible(false); jLabel1.setVisible(false); jLabel44.setVisible(false); jLabel71.setVisible(false); jLabel74.setVisible(false); jLabel75.setVisible(false); jLabel67.setVisible(false); jLabel74.setVisible(false); jLabel76.setVisible(false); jLabel80.setVisible(false); jLabel79.setVisible(false); jLabel82.setVisible(false); jLabel77.setVisible(false); jLabel78.setVisible(false); jLabel81.setVisible(false); jLabel83.setVisible(false); jLabel85.setVisible(false); jLabel84.setVisible(false); //Item PIe Chart DefaultPieDataset dataSet = new DefaultPieDataset(); try { Connection con = DBAccess.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "Select distinct citem.item_code,citem.`type`,Sum(Invoice_Detail.saleQty) as 'Sum QTy'\n" + "from citem,Invoice_Detail\n" + "where Invoice_Detail.itemCode = citem.item_code \n" + "group by citem.item_code,citem.`type`"); while (rs.next()) { dataSet.setValue(rs.getString("type"), rs.getInt("Sum QTy")); } } catch (SQLException e) { System.err.println(e.getMessage()); } JFreeChart chart = ChartFactory.createPieChart("Products Sold by Brand", dataSet, true, true, true); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setSize(490, 376); jPanel11.add(chartPanel); jPanel11.setVisible(true); //Year Bar chart DefaultCategoryDataset dataset2 = new DefaultCategoryDataset(); try { Connection con = DBAccess.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "select distinct DATE_FORMAT(Invoice.`date`,'%Y')as 'Year',SUM(invoice.grandTotal)\n" + "from invoice\n" + "group by DATE_FORMAT(Invoice.`date`,'%Y')\n" + ""); while (rs.next()) { if (rs.getString("Year") != null) { dataset2.setValue(rs.getInt("SUM(invoice.grandTotal)"), rs.getString("Year"), rs.getString("Year")); } } } catch (SQLException e) { System.err.println(e.getMessage()); } JFreeChart chart2 = ChartFactory.createBarChart("Yearly Sales", "Year", "Total Sales(Rs)", dataset2, PlotOrientation.VERTICAL, true, true, true); ChartPanel chartPanel2 = new ChartPanel(chart2); chartPanel2.setSize(480, 420); jPanel18.add(chartPanel2); jPanel18.setVisible(true); //Month Bar Chart DefaultCategoryDataset dataset3 = new DefaultCategoryDataset(); try { Connection con = DBAccess.getConnection(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery( "select distinct DATE_FORMAT(Invoice.`date`,'%Y-%m')as 'Month',SUM(invoice.grandTotal)\n" + "from invoice\n" + "group by DATE_FORMAT(Invoice.`date`,'%Y-%m')"); while (rs.next()) { String month = rs.getString("Month"); if (month != null) {//if no data if (String.valueOf(Calendar.getInstance().get(Calendar.YEAR)).equals(month.substring(0, 4))) { //for sum up to curet year only if ("01".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Jan", "Jan"); } else if ("02".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Feb", "Feb"); } else if ("03".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Mar", "Mar"); } else if ("04".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Apr", "Apr"); } else if ("05".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "May", "May"); } else if ("06".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Jun", "Jun"); } else if ("07".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Jul", "Jul"); } else if ("08".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Aug", "Aug"); } else if ("09".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Sep", "Sep"); } else if ("10".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Oct", "Oct"); } else if ("11".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Nov", "Nov"); } else if ("12".equals(month.substring(5, 7))) { dataset3.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Dec", "Dec"); } } } } } catch (SQLException e) { System.err.println(e.getMessage()); } JFreeChart chart3 = ChartFactory.createBarChart( "Monthly Sales of " + String.valueOf(Calendar.getInstance().get(Calendar.YEAR)), "Month", "Total Sales(Rs)", dataset3, PlotOrientation.VERTICAL, true, true, true); ChartPanel chartPanel3 = new ChartPanel(chart3); chartPanel3.setSize(480, 431); jPanel21.add(chartPanel3); jPanel21.setVisible(true); //Daily Bar Chart DefaultCategoryDataset dataset4 = new DefaultCategoryDataset(); int weekNo = 1; try { Connection con = DBAccess.getConnection(); Statement st = con.createStatement(); SimpleDateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; ResultSet rs = st.executeQuery( "select distinct DATE_FORMAT(Invoice.`date`,'%Y-%m-%d')as 'Day',SUM(invoice.grandTotal)\n" + "from invoice\n" + "group by DATE_FORMAT(Invoice.`date`,'%Y-%m-%d')"); while (rs.next()) { String day = rs.getString("Day"); if (day != null) { if (String.valueOf(Calendar.getInstance().get(Calendar.YEAR)).equals(day.substring(0, 4))) { //for sum up to curet year only date = newDateFormat.parse(day); day = date.toString().substring(0, 3); if (day.equals("Mon")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Mon", "Mon"); } else if (day.equals("Tue")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Tue", "Tue"); } else if (day.equals("Wed")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Wed", "Wed"); } else if (day.equals("Thu")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Thu", "Thu"); } else if (day.equals("Fri")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Fri", "Fri"); } else if (day.equals("Sat")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Sat", "Sat"); } else if (day.equals("Sun")) { dataset4.setValue(rs.getInt("SUM(invoice.grandTotal)"), "Sun", "Sun"); } } } } } catch (SQLException e) { System.err.println(e.getMessage()); } Calendar cal = Calendar.getInstance(); JFreeChart chart4 = ChartFactory.createBarChart( "Daily Sales of " + new SimpleDateFormat("MMM").format(cal.getTime()) + " Week " + weekNo, "Day", "Total Sales(Rs)", dataset4, PlotOrientation.VERTICAL, true, true, true); ChartPanel chartPanel4 = new ChartPanel(chart4); chartPanel4.setSize(480, 431); jPanel25.add(chartPanel4); jPanel25.setVisible(true); }
From source file:org.apache.manifoldcf.crawler.connectors.email.EmailConnector.java
/** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above.//from w w w . j a v a 2s .c o m *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { List<String> requiredMetadata = new ArrayList<String>(); for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode sn = spec.getChild(i); if (sn.getType().equals(EmailConfig.NODE_METADATA)) { String metadataAttribute = sn.getAttributeValue(EmailConfig.ATTRIBUTE_NAME); requiredMetadata.add(metadataAttribute); } } // Keep a cached set of open folders Map<String, Folder> openFolders = new HashMap<String, Folder>(); try { for (String documentIdentifier : documentIdentifiers) { String versionString = "_" + urlTemplate; // NOT empty; we need to make ManifoldCF understand that this is a document that never will change. // Check if we need to index if (!activities.checkDocumentNeedsReindexing(documentIdentifier, versionString)) continue; String compositeID = documentIdentifier; String version = versionString; String folderName = extractFolderNameFromDocumentIdentifier(compositeID); String id = extractEmailIDFromDocumentIdentifier(compositeID); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long startTime = System.currentTimeMillis(); try { try { Folder folder = openFolders.get(folderName); if (folder == null) { getSession(); OpenFolderThread oft = new OpenFolderThread(session, folderName); oft.start(); folder = oft.finishUp(); openFolders.put(folderName, folder); } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Email: Processing document identifier '" + compositeID + "'"); SearchTerm messageIDTerm = new MessageIDTerm(id); getSession(); SearchMessagesThread smt = new SearchMessagesThread(session, folder, messageIDTerm); smt.start(); Message[] message = smt.finishUp(); String msgURL = makeDocumentURI(urlTemplate, folderName, id); Message msg = null; for (Message msg2 : message) { msg = msg2; } if (msg == null) { // email was not found activities.deleteDocument(id); continue; } if (!activities.checkURLIndexable(msgURL)) { errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('" + msgURL + "')"; activities.noDocument(id, version); continue; } long fileLength = msg.getSize(); if (!activities.checkLengthIndexable(fileLength)) { errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length (" + fileLength + ")"; activities.noDocument(id, version); continue; } Date sentDate = msg.getSentDate(); if (!activities.checkDateIndexable(sentDate)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of date (" + sentDate + ")"; activities.noDocument(id, version); continue; } String mimeType = "text/plain"; if (!activities.checkMimeTypeIndexable(mimeType)) { errorCode = activities.EXCLUDED_DATE; errorDesc = "Excluded because of mime type ('" + mimeType + "')"; activities.noDocument(id, version); continue; } RepositoryDocument rd = new RepositoryDocument(); rd.setFileName(msg.getFileName()); rd.setMimeType(mimeType); rd.setCreatedDate(sentDate); rd.setModifiedDate(sentDate); String subject = StringUtils.EMPTY; for (String metadata : requiredMetadata) { if (metadata.toLowerCase().equals(EmailConfig.EMAIL_TO)) { Address[] to = msg.getRecipients(Message.RecipientType.TO); String[] toStr = new String[to.length]; int j = 0; for (Address address : to) { toStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, toStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_FROM)) { Address[] from = msg.getFrom(); String[] fromStr = new String[from.length]; int j = 0; for (Address address : from) { fromStr[j] = address.toString(); } rd.addField(EmailConfig.EMAIL_TO, fromStr); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_SUBJECT)) { subject = msg.getSubject(); rd.addField(EmailConfig.EMAIL_SUBJECT, subject); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_BODY)) { Multipart mp = (Multipart) msg.getContent(); for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition == null)) { MimeBodyPart mbp = (MimeBodyPart) part; if (mbp.isMimeType(EmailConfig.MIMETYPE_TEXT_PLAIN)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); } else if (mbp.isMimeType(EmailConfig.MIMETYPE_HTML)) { rd.addField(EmailConfig.EMAIL_BODY, mbp.getContent().toString()); //handle html accordingly. Returns content with html tags } } } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_DATE)) { rd.addField(EmailConfig.EMAIL_DATE, sentDate.toString()); } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_ENCODING)) { Multipart mp = (Multipart) msg.getContent(); if (mp != null) { String[] encoding = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { encoding[k] = part.getFileName().split("\\?")[1]; } } rd.addField(EmailConfig.ENCODING_FIELD, encoding); } } else if (metadata.toLowerCase().equals(EmailConfig.EMAIL_ATTACHMENT_MIMETYPE)) { Multipart mp = (Multipart) msg.getContent(); String[] MIMEType = new String[mp.getCount()]; for (int k = 0, n = mp.getCount(); k < n; k++) { Part part = mp.getBodyPart(k); String disposition = part.getDisposition(); if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT) || (disposition.equals(Part.INLINE))))) { MIMEType[k] = part.getContentType(); } } rd.addField(EmailConfig.MIMETYPE_FIELD, MIMEType); } } InputStream is = msg.getInputStream(); try { rd.setBinary(is, fileLength); activities.ingestDocumentWithException(id, version, msgURL, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleMessagingException(e, "processing email"); } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(e, "processing email"); throw new ManifoldCFException(e.getMessage(), e); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(startTime), EmailConfig.ACTIVITY_FETCH, fileLengthLong, documentIdentifier, errorCode, errorDesc, null); } } } finally { for (Folder f : openFolders.values()) { try { CloseFolderThread cft = new CloseFolderThread(session, f); cft.start(); cft.finishUp(); } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(), ManifoldCFException.INTERRUPTED); } catch (MessagingException e) { handleMessagingException(e, "closing folders"); } } } }
From source file:edu.harvard.iq.dvn.core.web.admin.OptionsPage.java
private String writeCSVStringQuery() { StringBuffer csvOutput = new StringBuffer(); csvOutput.append(getColumnString()); csvOutput.append("\n"); List list = (List) guestBookResponseServiceBean.findDownloadInfoAll(guestBookResponsesAllIds); Iterator iterator = list.iterator(); while (iterator.hasNext()) { StringBuffer csvCol = new StringBuffer(); Object[] gbrInfo = (Object[]) iterator.next(); String userName = (String) gbrInfo[0]; if (!(userName == null) && !userName.isEmpty()) { csvCol.append(getSafeCString(userName)); } else {/*from ww w .j av a 2 s . c o m*/ csvCol.append(getSafeCString("Anonymous - + " + gbrInfo[1])); } csvCol.append(",").append(getSafeCString((String) gbrInfo[2])); csvCol.append(",").append(getSafeCString((String) gbrInfo[3])); csvCol.append(",").append(getSafeCString((String) gbrInfo[4])); csvCol.append(",").append(getSafeCString((String) gbrInfo[5])); csvCol.append(",").append(getSafeCString((String) gbrInfo[12])); if (vdc == null) { csvCol.append(",").append(getSafeCString((String) gbrInfo[6])); } csvCol.append(",").append( getSafeCString((String) gbrInfo[7] + ":" + (String) gbrInfo[8] + "/" + (Long) gbrInfo[13])); csvCol.append(",").append(getSafeCString((String) gbrInfo[9])); csvCol.append(",").append(getSafeCString((String) gbrInfo[10])); Date responseTime = (Date) gbrInfo[11]; csvCol.append(",").append(getSafeCString(responseTime.toString())); csvCol.append(",").append(getSafeCString((String) gbrInfo[15])); csvCol.append(",").append(getSafeCString((String) gbrInfo[1])); if (!customQuestionIds.isEmpty()) { List customQuestionResponsesQueryResults = guestBookResponseServiceBean .findCustomResponsePerGuestbookResponse((Long) gbrInfo[14]); Iterator cqIterator = customQuestionResponsesQueryResults.iterator(); List<CustomQuestionResponse> cqrList = new ArrayList(); while (cqIterator.hasNext()) { Object[] cqResponse = (Object[]) cqIterator.next(); CustomQuestionResponse cqrAdd = new CustomQuestionResponse(); cqrAdd.setResponse((String) cqResponse[0]); CustomQuestion dummyQuestion = new CustomQuestion(); dummyQuestion.setId((Long) cqResponse[1]); cqrAdd.setCustomQuestion(dummyQuestion); cqrList.add(cqrAdd); } if (!cqrList.isEmpty()) { List<String> customQuestionResponseStrings = new ArrayList(customQuestionIds.size()); for (int i = 0; i < cqrList.size(); i++) { customQuestionResponseStrings.add(i, ""); } for (Long qid : customQuestionIds) { int index = customQuestionIds.indexOf(qid); for (CustomQuestionResponse cqr : cqrList) { if (cqr.getCustomQuestion().getId().equals(qid)) { customQuestionResponseStrings.set(index, cqr.getResponse()); } } } for (String response : customQuestionResponseStrings) { csvCol.append(",").append(getSafeCString(response)); } } } csvCol.append("\n"); csvOutput.append(csvCol); } return csvOutput.toString(); }
From source file:es.pode.publicacion.negocio.servicios.SrvPublicacionServiceImpl.java
/** * Este metodo elimina los ODEs en estado No Disponible que cumplen las * condiciones de los parametros que se le pasan: rango de fecha en el que * paso a no disponible, usuario al que pertenece el ODE, etc. Si la lista * de usuarios es vacia, se tendran en cuenta los ODEs no disponibles de * todo el repositorio. Si la fecha de fin es vacia, se tendra en cuenta la * fecha actual como limite temporal superior. Si la fecha de inicio es * vacia, no se tendra en cuenta limite temporal inferior. * //from ww w . j a v a2s . com * @param parametro * Parametros con las condiciones a cumplir por los ODEs a * eliminar. * @return EliminarResultadoVO[]Devuelve un array de resultados de eliminar * los ODEs que cumplen las condiciones de eliminacion. * @throws Exception * */ protected EliminarResultadoVO[] handleEliminarNoDisponibles(EliminarNoDisponiblesVO parametro) throws Exception { // Higiene en los parametros. if (parametro == null) { logger.error("Error invocando eliminacion de odes no disponibles con parametro nulo."); throw new Exception("Error invocando eliminacion de odes no disponibles con parametro nulo."); } // Comprobamos las fechas Date fechaInicio = (parametro.getFechaInicio() != null ? parametro.getFechaInicio().getTime() : null); Date fechaFin = (parametro.getFechaFin() != null ? parametro.getFechaFin().getTime() : null); if (fechaInicio == null) fechaInicio = new Date(0); // si la fecha de inicio es vacia, // cogemos 1970 como inicio. if (fechaFin == null) fechaFin = new Date(); // si la fecha de fin es vacia, utilzamos // hoy como tope. if (fechaInicio.after(fechaFin)) // hay una inconsistencia con las // fechas, no seguimos { logger.error("Error invocando la eliminacion de odes. Fechas desde[" + fechaInicio.toString() + "] y hasta[" + fechaFin.toString() + "] inconsistentes."); throw new Exception("Error invocando la eliminacion de odes. Fechas desde[" + fechaInicio.toString() + "] y hasta[" + fechaFin.toString() + "] inconsistentes."); } // Primero hay que recopilar todos los ODEs en estado no disponible por // usuario o cogerlos todos ArrayList<TransicionVO> odesNoDisponibles = new ArrayList<TransicionVO>(); if (parametro.getIdUsuarios() == null || parametro.getIdUsuarios().length == 0) {// cogemos // todos // los // ODEs // no // publicados // independientemente // del // usuario. try { EstadoDesdeHastaCriteria criterio = new EstadoDesdeHastaCriteria(); criterio.setFechaDesde(DateManager.dateToCalendar(fechaInicio)); criterio.setFechaHasta(DateManager.dateToCalendar(fechaFin)); criterio.setEstadoActual(getEstadoDao().obtenEstadoPorNombre(NO_DISPONIBLE)); criterio.setEstadoTransitado(null); if (logger.isDebugEnabled()) logger.debug("Buscamos ODEs no disponibles desde[" + criterio.getFechaDesde().toString() + "] hasta[" + criterio.getFechaHasta().toString() + "]"); List<TransicionVO> odesNoDisponiblesArray = getTransicionDao() .buscarODEsPorCriterioEstadoDesdeHasta(criterio); if (odesNoDisponiblesArray != null && odesNoDisponiblesArray.size() > 0) odesNoDisponibles.addAll(odesNoDisponiblesArray); } catch (Exception e) { logger.error("Error onteniendo la lista de ODEs No Disponibles para toda la plataforma desde[" + fechaInicio.toString() + "] hasta[" + fechaFin.toString() + "][" + e.getCause() + "]"); throw new Exception( "Error onteniendo la lista de ODEs No Disponibles para toda la plataforma desde[" + fechaInicio.toString() + "] hasta[" + fechaFin.toString() + "]", e); } } else { Estado estadoActual = getEstadoDao().obtenEstadoPorNombre(NO_DISPONIBLE); UsuarioEstadoDesdeHastaCriteria criterio = new UsuarioEstadoDesdeHastaCriteria(); criterio.setEstadoActual(estadoActual); criterio.setEstadoTransitado(null); criterio.setFechaDesde(DateManager.dateToCalendar(fechaInicio)); criterio.setFechaHasta(DateManager.dateToCalendar(fechaFin)); for (int i = 0; i < parametro.getIdUsuarios().length; i++) { try { criterio.setIdUsuarioCreacion(parametro.getIdUsuarios()[i]); if (logger.isDebugEnabled()) logger.debug("Buscamos ODEs no disponibles desde[" + criterio.getFechaDesde().toString() + "] hasta[" + criterio.getFechaHasta().toString() + "] para usuario[" + criterio.getIdUsuarioCreacion() + "]."); List<TransicionVO> odesNoDisponiblesArray = getTransicionDao() .buscarODEsPorCriterioUsuarioEstadoDesdeHasta(criterio); if (odesNoDisponiblesArray != null && odesNoDisponiblesArray.size() > 0) odesNoDisponibles.addAll(odesNoDisponiblesArray); else { if (logger.isDebugEnabled()) logger.debug("No hay ODEs en estado no disponible para el usuario[" + criterio.getIdUsuarioCreacion() + "] desde[" + criterio.getFechaDesde().toString() + "] hasta[" + criterio.getFechaHasta().toString() + "]"); } } catch (Exception e) { logger.error("Error obteniendo ODEs No Disponibles para usuario[" + parametro.getIdUsuarios()[i] + "]. Continuamos con el resto[" + e.getCause() + "]"); } } } if (odesNoDisponibles.size() == 0) {// no hay nada que hacer, no hay // ODEs no disponibles para los // usuarios seleccionados. logger.warn("No hay ODEs en estado no disponible entre las fechas [" + fechaInicio.toString() + "]->[" + fechaFin.toString() + "] para los usuarios dados[" + (parametro.getIdUsuarios() != null ? parametro.getIdUsuarios().length : 0) + "]"); return new EliminarResultadoVO[0]; } Transicion[] odesEliminablesArray = (Transicion[]) odesNoDisponibles.toArray(new Transicion[0]); EliminarResultadoVO[] retorno = new EliminarResultadoVO[odesEliminablesArray.length]; for (int i = 0; i < odesEliminablesArray.length; i++) { try { retorno[i] = new EliminarResultadoVO(); retorno[i].setIdODE(odesEliminablesArray[i].getIdODE()); retorno[i].setTitulo(odesEliminablesArray[i].getTitulo()); ResultadoOperacionVO resultado = handleEliminar(odesEliminablesArray[i].getIdODE(), odesEliminablesArray[i].getIdUsuario()); if (resultado.getIdResultado().equals(SIN_ERRORES)) { retorno[i].setCode(SIN_ERRORES); // TODO: hay que terminar de componer el texto de vuelta del // error de manera i18n retorno[i].setMensaje(getPropertyValueI18n(SIN_ERRORES)); } else { retorno[i].setCode(TRANSICION_ESTADO_INVALIDA); // TODO: hay que terminar de componer el texto de vuelta del // error de manera i18n retorno[i].setMensaje(getPropertyValueI18n(TRANSICION_ESTADO_INVALIDA)); } } catch (Exception e) { logger.error("Excepcion eliminando el ODE[" + odesEliminablesArray[i].getIdODE() + "].[" + e.getCause() + "]"); retorno[i].setCode(EXCEPCION_INESPERADA); retorno[i].setMensaje(getPropertyValueI18n(SrvPublicacionServiceImpl.EXCEPCION_INESPERADA) + "[" + e.getCause() + "]."); } } return retorno; }
From source file:com.eucalyptus.objectstorage.ObjectStorageGateway.java
@Override public CopyObjectResponseType copyObject(CopyObjectType request) throws S3Exception { logRequest(request);//from www . j a v a2 s .com String sourceBucket = request.getSourceBucket(); String sourceKey = request.getSourceObject(); String sourceVersionId = request.getSourceVersionId(); UserPrincipal requestUser = Contexts.lookup().getUser(); // Check for source bucket final Bucket srcBucket = ensureBucketExists(sourceBucket); // Check for source object final ObjectEntity srcObject; try { srcObject = ObjectMetadataManagers.getInstance().lookupObject(srcBucket, sourceKey, sourceVersionId); } catch (NoSuchElementException e) { throw new NoSuchKeyException(sourceBucket + "/" + sourceKey); } catch (Exception e) { throw new InternalErrorException(sourceBucket); } // Check authorization for GET operation on source bucket and object if (OsgAuthorizationHandler.getInstance().operationAllowed(request.getGetObjectRequest(), srcBucket, srcObject, 0)) { CopyObjectResponseType reply = request.getReply(); String destinationBucket = request.getDestinationBucket(); String destinationKey = request.getDestinationObject(); // Check for destination bucket Bucket destBucket = ensureBucketExists(destinationBucket); // Initialize entity for destination object ObjectEntity destObject; try { destObject = ObjectEntity.newInitializedForCreate(destBucket, destinationKey, srcObject.getSize(), requestUser); } catch (Exception e) { LOG.error("Error initializing entity for persisting object metadata for " + destinationBucket + "/" + destinationKey); throw new InternalErrorException(destinationBucket + "/" + destinationKey); } // Check authorization for PUT operation on destination bucket and object if (OsgAuthorizationHandler.getInstance().operationAllowed(request.getPutObjectRequest(), destBucket, destObject, srcObject.getSize())) { String metadataDirective = request.getMetadataDirective(); String copyIfMatch = request.getCopySourceIfMatch(); String copyIfNoneMatch = request.getCopySourceIfNoneMatch(); Date copyIfUnmodifiedSince = request.getCopySourceIfUnmodifiedSince(); Date copyIfModifiedSince = request.getCopySourceIfModifiedSince(); boolean updateMetadataOnly = false; // Parse metadata directive if (Strings.isNullOrEmpty(metadataDirective)) { metadataDirective = MetadataDirective.COPY.toString(); } else { try { metadataDirective = (MetadataDirective.valueOf(metadataDirective)).toString(); } catch (IllegalArgumentException e) { throw new InvalidArgumentException(ObjectStorageProperties.METADATA_DIRECTIVE, "Unknown metadata directive: " + metadataDirective); } } // If the object is copied on to itself (without version ID), metadata directive must be REPLACE if (sourceBucket.equals(destinationBucket) && sourceKey.equals(destinationKey) && Strings.isNullOrEmpty(request.getSourceVersionId())) { if (MetadataDirective.REPLACE.toString().equals(metadataDirective)) { updateMetadataOnly = true; } else { throw new InvalidRequestException(destinationBucket + "/" + destinationKey, "This copy request is illegal because it is trying to copy an object to itself without changing the " + "object's metadata, storage class, website redirect location or encryption attributes."); } } // Copy the headers either from request or from source object Map<String, String> modded = null; if (MetadataDirective.REPLACE.toString().equals(metadataDirective)) { if (request.getCopiedHeaders() != null && !request.getCopiedHeaders().isEmpty()) { modded = Maps.newHashMap(request.getCopiedHeaders()); } else { modded = Maps.newHashMap(); } } else { modded = srcObject.getStoredHeaders(); } destObject.setStoredHeaders(modded); // Check copy conditions if (copyIfMatch != null) { if (!copyIfMatch.equals(srcObject.geteTag())) { throw new PreconditionFailedException(sourceKey + " CopySourceIfMatch: " + copyIfMatch); } } if (copyIfNoneMatch != null) { if (copyIfNoneMatch.equals(srcObject.geteTag())) { throw new PreconditionFailedException( sourceKey + " CopySourceIfNoneMatch: " + copyIfNoneMatch); } } if (copyIfUnmodifiedSince != null) { if (copyIfUnmodifiedSince.getTime() < srcObject.getObjectModifiedTimestamp().getTime()) { throw new PreconditionFailedException( sourceKey + " CopySourceIfUnmodifiedSince: " + copyIfUnmodifiedSince.toString()); } } if (copyIfModifiedSince != null) { if (copyIfModifiedSince.getTime() > srcObject.getObjectModifiedTimestamp().getTime()) { throw new PreconditionFailedException( sourceKey + " CopySourceIfModifiedSince: " + copyIfModifiedSince.toString()); } } // Construct ACL for destination object try { AccessControlPolicy acp = getFullAcp(request.getAccessControlList(), requestUser, destBucket.getOwnerCanonicalId()); destObject.setAcl(acp); } catch (Exception e) { LOG.warn("Encountered an exception while constructing access control policy to set on " + destinationBucket + "/" + destinationKey, e); throw new InternalErrorException(destinationBucket + "/" + destinationKey + "?acl"); } // Fill in other details for destination object destObject.setSize(srcObject.getSize()); destObject.setStorageClass(srcObject.getStorageClass()); destObject.seteTag(srcObject.geteTag()); destObject.setIsLatest(Boolean.TRUE); // Prep the request to be sent to the backend request.setSourceObject(srcObject.getObjectUuid()); request.setSourceBucket(srcBucket.getBucketUuid()); request.setSourceVersionId(ObjectStorageProperties.NULL_VERSION_ID); request.setDestinationObject(destObject.getObjectUuid()); request.setDestinationBucket(destBucket.getBucketUuid()); try { // Fire copy object request to backend ObjectEntity objectEntity = OsgObjectFactory.getFactory().copyObject(ospClient, destObject, request, requestUser, metadataDirective); reply.setLastModified( DateFormatter.dateToListingFormattedString(objectEntity.getObjectModifiedTimestamp())); reply.setEtag(objectEntity.geteTag()); try { // send the event if we aren't doing a metadata update only if (!updateMetadataOnly) { fireObjectCreationEvent(destinationBucket, destinationKey, destObject.getVersionId(), requestUser.getUserId(), requestUser.getName(), requestUser.getAccountNumber(), destObject.getSize(), null); } } catch (Exception ex) { LOG.debug("Failed to fire reporting event for OSG COPY object operation", ex); } } catch (Exception ex) { // Wrap the error from back-end with a 500 error LOG.warn("CorrelationId: " + Contexts.lookup().getCorrelationId() + " Responding to client with 500 InternalError because of:", ex); throw new InternalErrorException( "Could not copy " + srcBucket.getBucketName() + "/" + srcObject.getObjectKey() + " to " + destBucket.getBucketName() + "/" + destObject.getObjectKey(), ex); } // Copy source version either from the request if its not null or from the source object only if its not "null" reply.setCopySourceVersionId(sourceVersionId != null ? sourceVersionId : (!srcObject.getVersionId().equals(ObjectStorageProperties.NULL_VERSION_ID) ? srcObject.getVersionId() : null)); // Copy the version if the destination object was assigned one reply.setVersionId(!destObject.getVersionId().equals(ObjectStorageProperties.NULL_VERSION_ID) ? destObject.getVersionId() : null); return reply; } else { throw new AccessDeniedException(destinationBucket + "/" + destinationKey); } } else { throw new AccessDeniedException(sourceBucket + "/" + sourceKey); } }