List of usage examples for java.lang Long compareTo
public int compareTo(Long anotherLong)
From source file:org.opendatakit.common.android.provider.impl.FormsDiscoveryRunnable.java
/** * Scan the given formDir and update the Forms database. If it is the * formsFolder, then any 'framework' forms should be forbidden. If it is not * the/*from ww w . ja v a 2 s. c o m*/ * formsFolder, only 'framework' forms should be allowed * * @param mediaPath * -- full formDir * @param isFormsFolder * @param baseStaleMediaPath * -- path prefix to the stale forms/framework directory. */ private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) { String formDirectoryPath = formDir.getAbsolutePath(); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath); boolean needUpdate = true; FormInfo fi = null; Uri uri = null; Cursor c = null; try { File formDef = new File(formDir, ODKFileUtils.FORMDEF_JSON_FILENAME); String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?"; String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, formDir) }; c = context.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null, selection, selectionArgs, null); if (c == null) { Log.w(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!"); return; } if (c.getCount() > 1) { c.close(); Log.w(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " multiple records from cursor -- delete all and restore!"); // we have multiple records for this one directory. // Rename the directory. Delete the records, and move the // directory back. File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath); context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); FileUtils.moveDirectory(tempMediaPath, formDir); // we don't know which of the above records was correct, so // reparse this to get ground truth... fi = new FormInfo(context, appName, formDef); } else if (c.getCount() == 1) { c.moveToFirst(); String id = c.getString(c.getColumnIndex(FormsColumns.FORM_ID)); uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id); Long lastModificationDate = c.getLong(c.getColumnIndex(FormsColumns.DATE)); Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir); if (lastModificationDate.compareTo(formDefModified) == 0) { Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " formDef unchanged"); fi = new FormInfo(appName, c, false); needUpdate = false; } else { Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " formDef revised"); fi = new FormInfo(context, appName, formDef); needUpdate = true; } } else if (c.getCount() == 0) { // it should be new, try to parse it... fi = new FormInfo(context, appName, formDef); } // Enforce that a formId == FormsColumns.COMMON_BASE_FORM_ID can only be // in the Framework directory // and that no other formIds can be in that directory. If this is not the // case, ensure that // this record is moved to the stale directory. if (fi.formId.equals(FormsColumns.COMMON_BASE_FORM_ID)) { if (isFormsFolder) { // we have a 'framework' form in the forms directory. // Move it to the stale directory. // Delete all records referring to this directory. moveToStaleDirectory(formDir, baseStaleMediaPath); context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); return; } } else { if (!isFormsFolder) { // we have a non-'framework' form in the framework directory. // Move it to the stale directory. // Delete all records referring to this directory. moveToStaleDirectory(formDir, baseStaleMediaPath); context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); return; } } } catch (SQLiteException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IOException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IllegalArgumentException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); try { FileUtils.deleteDirectory(formDir); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " Removing -- unable to parse formDef file: " + e.toString()); } catch (IOException e1) { e1.printStackTrace(); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " Removing -- unable to delete form directory: " + formDir.getName() + " error: " + e.toString()); } return; } finally { if (c != null && !c.isClosed()) { c.close(); } } // Delete any entries matching this FORM_ID, but not the same directory and // which have a version that is equal to or older than this version. String selection; String[] selectionArgs; if (fi.formVersion == null) { selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND " + FormsColumns.FORM_VERSION + " IS NULL"; String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId }; selectionArgs = temp; } else { selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND " + "( " + FormsColumns.FORM_VERSION + " IS NULL" + " OR " + FormsColumns.FORM_VERSION + " <=?" + " )"; String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion }; selectionArgs = temp; } try { context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection, selectionArgs); } catch (SQLiteException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (Exception e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } // See if we have any newer versions already present... if (fi.formVersion == null) { selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND " + FormsColumns.FORM_VERSION + " IS NOT NULL"; String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId }; selectionArgs = temp; } else { selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND " + FormsColumns.FORM_VERSION + " >?"; String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion }; selectionArgs = temp; } try { Uri uriApp = Uri.withAppendedPath(formsProviderContentUri, appName); c = context.getContentResolver().query(uriApp, null, selection, selectionArgs, null); if (c == null) { Log.w(t, "[" + instanceCounter + "] updateFormDir: " + uriApp.toString() + " null cursor -- cannot update!"); return; } if (c.moveToFirst()) { // the directory we are processing is stale -- move it to stale // directory moveToStaleDirectory(formDir, baseStaleMediaPath); return; } } catch (SQLiteException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } catch (IOException e) { e.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + e.toString()); return; } finally { if (c != null && !c.isClosed()) { c.close(); } } if (!needUpdate) { // no change... return; } try { // Now insert or update the record... ContentValues v = new ContentValues(); String[] values = fi.asRowValues(FormsColumns.formsDataColumnNames); for (int i = 0; i < values.length; ++i) { v.put(FormsColumns.formsDataColumnNames[i], values[i]); } if (uri != null) { int count = context.getContentResolver().update(uri, v, null, null); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " " + count + " records successfully updated"); } else { context.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v); Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " one record successfully inserted"); } } catch (SQLiteException ex) { ex.printStackTrace(); Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: " + ex.toString()); return; } }
From source file:org.flockdata.search.dao.EntityChangeWriterEs.java
@Override public EntitySearchChange handle(EntitySearchChange searchChange) throws IOException { String source = getJsonToIndex(searchChange); if (searchChange.getSearchKey() == null || searchChange.getSearchKey().equals("")) { searchChange.setSearchKey(/*from w w w .jav a2s.c om*/ (searchChange.getCode() == null ? searchChange.getKey() : searchChange.getCode())); logger.debug("No search key, creating as a new document [{}]", searchChange.getKey()); return save(searchChange, source); } try { logger.debug("Update request for searchKey [{}], key[{}]", searchChange.getSearchKey(), searchChange.getKey()); GetRequestBuilder request = elasticSearchClient.prepareGet(searchChange.getIndexName(), searchChange.getDocumentType(), searchChange.getSearchKey()); // if (searchChange.getParent() != null) { // request.setRouting(searchChange.getParent().getCode()); // } GetResponse response = request.execute().actionGet(); logger.debug("executed get request for {}", searchChange.toString()); if (response.isExists() && !response.isSourceEmpty()) { logger.debug("Document exists!"); // Messages can be received out of sequence // Check to ensure we don't accidentally overwrite a more current // document with an older one. We assume the calling fortress understands // what the most recent doc is. Object o = response.getSource().get(SearchSchema.UPDATED); // fortress view of UPDATED, not FlockDatas! if (o != null) { Long existingWhen = Long.decode(o.toString()); logger.debug("Comparing searchChange when {} with stored when {}", searchChange.getUpdatedDate(), existingWhen); if (!searchChange.isForceReindex()) { if (existingWhen.compareTo(searchChange.getUpdatedDate().getTime()) > 0) { logger.debug( "ignoring a request to update as the existing document dated [{}] is newer than the searchChange document dated [{}]", new Date(existingWhen), searchChange.getUpdatedDate()); return searchChange; // Don't overwrite the most current doc! } else if (searchChange.getUpdatedDate().getTime() == 0L && !searchChange.isReplyRequired()) { // Meta Change - not indexed in FD, so ignore something we already have. // Likely scenario is a batch is being reprocessed return searchChange; } logger.debug("Document is more recent. Proceeding with update"); } else { logger.debug("Forcing an update of the document."); } } } else { // No response, to a search key we expect to exist. Create a new one // Likely to be in response to rebuilding an ES index from Graph data. logger.debug("About to create in response to an update request for {}", searchChange.toString()); return save(searchChange, source); } // Update the existing document with the searchChange change IndexRequestBuilder update = elasticSearchClient.prepareIndex(searchChange.getIndexName(), searchChange.getDocumentType(), searchChange.getSearchKey()); //.setRouting(searchChange.getKey()); ListenableActionFuture<IndexResponse> ur = update.setSource(source).execute(); if (logger.isDebugEnabled()) { IndexResponse indexResponse = ur.actionGet(); logger.debug("Updated [{}] logId=[{}] for [{}] to version [{}]", searchChange.getSearchKey(), searchChange.getLogId(), searchChange, indexResponse.getVersion()); } // } catch (IndexMissingException e) { // administrator must have deleted it, but we think it still exists // logger.info("Attempt to update non-existent index [{}]. Creating it..", searchChange.getIndexName()); // purgeCache(); // return save(searchChange, source); } catch (NoShardAvailableActionException e) { return save(searchChange, source); } return searchChange; }
From source file:org.protempa.backend.dsb.relationaldb.AbstractSQLGenerator.java
private List<Set<Filter>> constructPartitions(EntitySpec entitySpec, Set<Filter> filtersCopy) { PositionFilter positionFilter = null; for (Filter filter : filtersCopy) { if (filter instanceof PositionFilter) { positionFilter = (PositionFilter) filter; break; }//from w w w .j ava 2 s . co m } Unit partitionBy = entitySpec.getPartitionBy(); List<Set<Filter>> filterList = new ArrayList<>(); if (partitionBy == null || positionFilter == null || positionFilter.getStart() == null || positionFilter.getFinish() == null || !positionFilter.getStartSide().equals(positionFilter.getFinishSide())) { filterList.add(filtersCopy); } else { Long start = positionFilter.getStart(); Long actualFinish = positionFilter.getFinish(); Granularity startGran = positionFilter.getStartGranularity(); Granularity finishGran = positionFilter.getFinishGranularity(); Unit finishUnit = finishGran != null ? finishGran.getCorrespondingUnit() : null; boolean doLoop = true; while (doLoop) { Set<Filter> newFiltersCopy = new HashSet<>(filtersCopy); newFiltersCopy.remove(positionFilter); Long nextStart = partitionBy.addToPosition(start, 1); Long finish = finishUnit != null ? finishUnit.addToPosition(nextStart, -1) : -1; if (finish.compareTo(actualFinish) >= 0) { finish = actualFinish; doLoop = false; } PositionFilter newPositionFilter = new PositionFilter(positionFilter.getPropositionIds(), start, startGran, finish, finishGran, positionFilter.getStartSide(), positionFilter.getFinishSide()); newFiltersCopy.add(newPositionFilter); filterList.add(newFiltersCopy); start = nextStart; } } return filterList; }
From source file:org.uhp.portlets.news.web.ItemEditController.java
@Override protected Map<String, Object> referenceData(PortletRequest request, Object command, Errors errors, int page) throws Exception { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ItemEditController: entering method referenceData..."); }//from w w w . ja v a2 s. c om ItemForm itemForm = (ItemForm) command; Map<String, Object> model = new HashMap<String, Object>(); if (page == 0) { final Long cId = itemForm.getItem().getCategoryId(); final Long tId = PortletRequestUtils.getLongParameter(request, Constants.ATT_TOPIC_ID); if (tId != null) { ctxTopicId = tId; } final String uid = request.getRemoteUser(); int perm = 0; if (ctxTopicId != null) { model.put(Constants.ATT_TOPIC_ID, ctxTopicId); model.put(Constants.OBJ_TOPIC, this.tm.getTopicById(ctxTopicId)); perm = RolePerm.valueOf(this.um.getUserRoleInCtx(ctxTopicId, NewsConstants.CTX_T, uid)).getMask(); } if (cId != null) { final Category category = this.cm.getCategoryById(cId); model.put(Constants.OBJ_CATEGORY, category); model.put(Constants.OBJ_ENTITY, this.em.getEntityById(category.getEntityId())); model.put(Constants.ATT_NB_DAYS, this.im.getNbDays()); int permTmp = RolePerm.valueOf(this.um.getUserRoleInCtx(cId, NewsConstants.CTX_C, uid)).getMask(); if (perm < permTmp) { perm = permTmp; } model.put(Constants.ATT_T_LIST, this.tm.getTopicListForCategoryByUser(cId, uid)); } model.put(Constants.ATT_A_LIST, itemForm.getAttachments()); model.put(Constants.ATT_USER_ID, request.getRemoteUser()); model.put(Constants.ATT_PM, perm); return model; } else if (page == 1 || page == 3) { // External File or update an attachment final Long cId = itemForm.getItem().getCategoryId(); final Long tId = ctxTopicId; final String userUid = request.getRemoteUser(); int perm = 0; if (cId != null && cId != -1) { Category category = this.cm.getCategoryById(cId); model.put(Constants.OBJ_CATEGORY, category); perm = RolePerm.valueOf(this.um.getUserRoleInCtx(cId, NewsConstants.CTX_C, userUid)).getMask(); } if (tId != null && tId != -1) { model.put(Constants.OBJ_TOPIC, this.tm.getTopicById(tId)); int permTmp = RolePerm.valueOf(this.um.getUserRoleInCtx(tId, NewsConstants.CTX_T, userUid)) .getMask(); if (perm < permTmp) { perm = permTmp; } } model.put(Constants.ATT_USER_ID, userUid); model.put(Constants.ATT_PM, perm); File directory = new File(this.getPortletContext().getRealPath(temporaryStoragePath)); String prefix = itemForm.getItem().getItemId() + "_"; File[] listFiles = directory.listFiles(new PrefixFilter(prefix)); String filesNames = ""; for (File file : listFiles) { String filename = file.getName(); filename = filename.substring(prefix.length(), filename.lastIndexOf(".")); filesNames += filename + ","; } model.put("existingFileNames", filesNames); return model; } else if (page == 2) { // Internal File final Long cId = itemForm.getItem().getCategoryId(); final Long tId = ctxTopicId; final String userUid = request.getRemoteUser(); Long entityId = (long) -1; int perm = 0; if (cId != null && cId != -1) { Category category = this.cm.getCategoryById(cId); entityId = category.getEntityId(); model.put(Constants.OBJ_CATEGORY, category); perm = RolePerm.valueOf(this.um.getUserRoleInCtx(cId, NewsConstants.CTX_C, userUid)).getMask(); } if (tId != null && tId != -1) { model.put(Constants.OBJ_TOPIC, this.tm.getTopicById(tId)); int permTmp = RolePerm.valueOf(this.um.getUserRoleInCtx(tId, NewsConstants.CTX_T, userUid)) .getMask(); if (perm < permTmp) { perm = permTmp; } } model.put(Constants.ATT_USER_ID, userUid); model.put(Constants.ATT_PM, perm); Long categoryId = itemForm.getCategoryId(); Long topicId = itemForm.getTopicId(); Long selectedItemId = itemForm.getItemId(); if (selectedItemId != null && selectedItemId != -1) { // Attachments list Item selectedItem = im.getItemById(selectedItemId); Topic selectedTopic = tm.getTopicById(topicId); Category selectedCat = cm.getCategoryById(selectedTopic.getCategoryId()); // existing attachments List<Attachment> attachments = itemForm.getAttachments(); Map<String, String> mapIds = new HashMap<String, String>(); for (Attachment existingAtt : attachments) { if (StringUtils.isNotEmpty(existingAtt.getId())) { mapIds.put(existingAtt.getId(), existingAtt.getId()); } } model.put("existingIdsMap", mapIds); List<org.cmis.portlets.news.domain.Attachment> attachmentsListByItem = am .getAttachmentsListByItem(selectedItem.getItemId()); model.put("attachments", attachmentsListByItem); // For breadcrumb model.put("selectedCategory", selectedCat); model.put("selectedTopic", selectedTopic); model.put("selectedItem", selectedItem); } else if (topicId != null && topicId != -1) { // Items list List<Item> items = im.getItemsWithAttachmentsByTopic(topicId); Topic selectedTopic = tm.getTopicById(topicId); Category selectedCat = cm.getCategoryById(selectedTopic.getCategoryId()); List<Item> itemsList = new ArrayList<Item>(); if (RolePerm.valueOf(this.um.getUserRoleInCtx(topicId, NewsConstants.CTX_T, userUid)) .getMask() > 0) { Long currentItemId = itemForm.getItem().getItemId(); for (Item item : items) { Long itemId = item.getItemId(); if (itemId.compareTo(currentItemId) != 0) { itemsList.add(item); } } } model.put("items", itemsList); // For breadcrumb model.put("selectedCategory", selectedCat); model.put("selectedTopic", selectedTopic); } else if (categoryId != null && categoryId != -1) { // Retrieve the topics list for the selected category List<Topic> topics = tm.getTopicListByCategory(categoryId); Category selectedCat = cm.getCategoryById(categoryId); String[] currenttopicIds = itemForm.getTopicIds(); List<Topic> topicsList = new ArrayList<Topic>(); for (Topic topic : topics) { Long id = topic.getTopicId(); if (RolePerm.valueOf(this.um.getUserRoleInCtx(id, NewsConstants.CTX_T, userUid)) .getMask() > 0) { int nb = im.countItemsWithAttachmentByTopic(id); for (String currentTopicId : currenttopicIds) { if (currentTopicId.equalsIgnoreCase(Long.toString(id))) { // remove one item for this topic if (nb > 0) { nb = nb - 1; } } } topic.setCount(nb); topicsList.add(topic); } } model.put("topics", topicsList); // For breadcrumb model.put("selectedCategory", selectedCat); } else { // Category list List<Category> categories = cm.getListCategoryOfEntityByUser(userUid, entityId); List<Category> categoriesList = new ArrayList<Category>(); for (Category category : categories) { Long id = category.getCategoryId(); if (RolePerm.valueOf(this.um.getUserRoleInCtx(id, NewsConstants.CTX_C, userUid)) .getMask() > 0) { categoriesList.add(category); } } model.put("categories", categoriesList); } return model; } return model; }
From source file:org.alfresco.repo.usage.RepoUsageComponentImpl.java
/** * Build the usage component. Protect with a read lock, transaction check and authentication check. *//* w ww. j a v a 2 s. co m*/ private RepoUsage getUsageImpl() { // Fetch persisted usage data Long lastUpdateUsers = (Long) attributeService.getAttribute(KEY_USAGE_ROOT, KEY_USAGE_CURRENT, KEY_USAGE_LAST_UPDATE_USERS); Long users = (Long) attributeService.getAttribute(KEY_USAGE_ROOT, KEY_USAGE_CURRENT, KEY_USAGE_USERS); Long lastUpdateDocuments = (Long) attributeService.getAttribute(KEY_USAGE_ROOT, KEY_USAGE_CURRENT, KEY_USAGE_LAST_UPDATE_DOCUMENTS); Long documents = (Long) attributeService.getAttribute(KEY_USAGE_ROOT, KEY_USAGE_CURRENT, KEY_USAGE_DOCUMENTS); final Long lastUpdate; if (lastUpdateUsers == null) { lastUpdate = lastUpdateDocuments; } else if (lastUpdateDocuments == null) { lastUpdate = lastUpdateUsers; } else if (lastUpdateDocuments.compareTo(lastUpdateUsers) > 0) { lastUpdate = lastUpdateDocuments; } else { lastUpdate = lastUpdateUsers; } // Combine with current restrictions RepoUsage usage = new RepoUsage(lastUpdate, users, documents, restrictions.getLicenseMode(), restrictions.getLicenseExpiryDate(), transactionService.getAllowWrite() == false); return usage; }
From source file:org.asqatasun.service.command.AuditCommandImpl.java
/** * //from w ww .j a v a 2 s . com * @param audit */ private void cleanUpTestData(Audit audit) { LOGGER.info("Cleaning-up data for " + audit.getSubject().getURL()); Long i = (long) 0; Long webResourceId = audit.getSubject().getId(); Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK); while (i.compareTo(nbOfContent) < 0) { Collection<Content> contentList = contentDataService .getSSPWithRelatedContentFromWebResource(webResourceId, i, processingTreatmentWindow, true); for (Content content : contentList) { if (content instanceof SSP) { for (RelatedContent rc : ((SSP) content).getRelatedContentSet()) { contentDataService.delete(rc.getId()); } } } i = i + processingTreatmentWindow; } for (ProcessResult pr : processResultDataService.getIndefiniteResultFromAudit(audit)) { processResultDataService.delete(pr.getId()); } for (PreProcessResult ppr : preProcessResultDataService.getPreProcessResultFromAudit(audit)) { preProcessResultDataService.delete(ppr.getId()); } LOGGER.info("Data cleaned-up for " + audit.getSubject().getURL()); }
From source file:org.lockss.daemon.ConfigParamDescr.java
public Object getValueOfType(String val) throws InvalidFormatException { Object ret_val = null; switch (type) { case TYPE_INT: try {//from w w w .j av a2s . c o m ret_val = Integer.valueOf(val); } catch (NumberFormatException nfe) { throw new InvalidFormatException("Invalid Int: " + val); } break; case TYPE_POS_INT: try { ret_val = Integer.valueOf(val); if (((Integer) ret_val).intValue() < 0) { throw new InvalidFormatException("Invalid Positive Int: " + val); } } catch (NumberFormatException nfe) { throw new InvalidFormatException("Invalid Positive Int: " + val); } break; case TYPE_LONG: try { ret_val = Long.valueOf(val); } catch (NumberFormatException nfe) { throw new InvalidFormatException("Invalid Long: " + val); } break; case TYPE_TIME_INTERVAL: try { ret_val = StringUtil.parseTimeInterval(val); } catch (NumberFormatException nfe) { throw new InvalidFormatException("Invalid time interval: " + val); } break; case TYPE_STRING: if (!StringUtil.isNullString(val)) { ret_val = val; } else { throw new InvalidFormatException("Invalid String: " + val); } break; case TYPE_URL: try { ret_val = new URL(val); } catch (MalformedURLException ex) { throw new InvalidFormatException("Invalid URL: " + val, ex); } break; case TYPE_YEAR: if (val.length() == 4 || "0".equals(val)) { try { int i_val = Integer.parseInt(val); if (i_val >= 0) { ret_val = Integer.valueOf(val); } } catch (NumberFormatException fe) { // Defer to the throw statement below } } if (ret_val == null) { throw new InvalidFormatException("Invalid Year: " + val); } break; case TYPE_BOOLEAN: if (val.equalsIgnoreCase("true") || val.equalsIgnoreCase("yes") || val.equalsIgnoreCase("on") || val.equalsIgnoreCase("1")) { ret_val = Boolean.TRUE; } else if (val.equalsIgnoreCase("false") || val.equalsIgnoreCase("no") || val.equalsIgnoreCase("off") || val.equalsIgnoreCase("0")) { ret_val = Boolean.FALSE; } else throw new InvalidFormatException("Invalid Boolean: " + val); break; case TYPE_USER_PASSWD: if (!StringUtil.isNullString(val)) { List<String> lst = StringUtil.breakAt(val, ':', -1, true, false); if (lst.size() != 2) { throw new InvalidFormatException( "User:Passwd must consist of two" + "strings separated by a colon: " + val); } ret_val = val; } else { throw new InvalidFormatException("Invalid String: " + val); } break; case TYPE_RANGE: { // case block ret_val = StringUtil.breakAt(val, '-', 2, true, true); String s_min = (String) ((Vector) ret_val).firstElement(); String s_max = (String) ((Vector) ret_val).lastElement(); if (!(s_min.compareTo(s_max) <= 0)) { throw new InvalidFormatException("Invalid Range: " + val); } break; } // end case block case TYPE_NUM_RANGE: { // case block ret_val = StringUtil.breakAt(val, '-', 2, true, true); String s_min = (String) ((Vector) ret_val).firstElement(); String s_max = (String) ((Vector) ret_val).lastElement(); try { /* * Caution: org.apache.commons.lang.math.NumberUtils.createLong(String) * (which returns Long) throws NumberFormatException, whereas * org.apache.commons.lang.math.NumberUtils.toLong(String) * (which returns long) returns 0L when parsing fails. */ Long l_min = NumberUtils.createLong(s_min); Long l_max = NumberUtils.createLong(s_max); if (l_min.compareTo(l_max) <= 0) { ((Vector) ret_val).setElementAt(l_min, 0); ((Vector) ret_val).setElementAt(l_max, 1); break; } } catch (NumberFormatException ex1) { if (s_min.compareTo(s_max) <= 0) { break; } } throw new InvalidFormatException("Invalid Numeric Range: " + val); } // end case block case TYPE_SET: ret_val = expandSetMacros(val); break; default: throw new InvalidFormatException("Unknown type: " + type); } return ret_val; }
From source file:org.opens.tanaguru.service.command.AuditCommandImpl.java
/** * /*from w w w . j a v a2 s.co m*/ * @param audit */ private void cleanUpTestData(Audit audit) { LOGGER.info("Cleaning-up data for " + audit.getSubject().getURL()); Long i = Long.valueOf(0); Long webResourceId = audit.getSubject().getId(); Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK); while (i.compareTo(nbOfContent) < 0) { List<Content> contentList = retrieveContentList(webResourceId, i, processingTreatmentWindow, Calendar.getInstance().getTime(), true, true); for (Content content : contentList) { if (content instanceof SSP) { for (RelatedContent rc : ((SSP) content).getRelatedContentSet()) { contentDataService.delete(rc.getId()); } } } i = i + processingTreatmentWindow; } for (ProcessResult pr : processResultDataService.getIndefiniteResultFromAudit(audit)) { processResultDataService.delete(pr.getId()); } for (PreProcessResult ppr : preProcessResultDataService.getPreProcessResultFromAudit(audit)) { preProcessResultDataService.delete(ppr.getId()); } LOGGER.info("Data cleaned-up for " + audit.getSubject().getURL()); }
From source file:org.mskcc.cbio.portal.servlet.PatientView.java
private void sortSampleIds(int cancerStudyId, int patientId, List<String> sampleIds) { if (sampleIds.size() == 1) { return;/*from ww w. ja va2 s .c o m*/ } try { Collections.sort(sampleIds); if (DaoClinicalEvent.timeEventsExistForPatient(patientId)) { List<ClinicalEvent> events = DaoClinicalEvent.getClinicalEvent(patientId, "SPECIMEN"); if (events != null) { final Map<String, Long> sampleTimes = new HashMap<String, Long>(); // TODO: event data should only use SAMPLE_ID, this allows // all variations currently in the db while transitioning String[] sampleIdsInEventData = { "SpecimenReferenceNumber", "SPECIMEN_REFERENCE_NUMBER", "SAMPLE_ID" }; for (ClinicalEvent event : events) { String specRefNum = null; for (String s : sampleIdsInEventData) { specRefNum = event.getEventData().get(s); if (specRefNum != null) { break; } } sampleTimes.put(specRefNum, event.getStartDate()); } Collections.sort(sampleIds, new Comparator<String>() { @Override public int compare(String s1, String s2) { Long l1 = sampleTimes.get(s1); if (l1 == null) l1 = Long.MAX_VALUE; Long l2 = sampleTimes.get(s2); if (l2 == null) l2 = Long.MAX_VALUE; return l1.compareTo(l2); } }); } } ClinicalAttribute attr = DaoClinicalAttribute.getDatum("SAMPLE_TYPE"); if (attr != null) { List<ClinicalData> data = DaoClinicalData.getSampleData(cancerStudyId, sampleIds, attr); if (!data.isEmpty()) { final Map<String, String> sampleTypes = new HashMap<String, String>(); for (ClinicalData datum : data) { sampleTypes.put(datum.getStableId(), datum.getAttrVal().toLowerCase()); } Collections.sort(sampleIds, new Comparator<String>() { @Override public int compare(String s1, String s2) { int t1 = getOrderOfType(sampleTypes.get(s1)); int t2 = getOrderOfType(sampleTypes.get(s2)); return t1 - t2; } }); } } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.asqatasun.service.command.AuditCommandImpl.java
@Override public void process() { audit = auditDataService.getAuditWithTest(audit.getId()); if (!audit.getStatus().equals(AuditStatus.PROCESSING)) { LOGGER.warn(/*from w w w . j a va2s. c o m*/ new StringBuilder(AUDIT_STATUS_IS_LOGGER_STR).append(audit.getStatus()).append(WHILE_LOGGER_STR) .append(AuditStatus.PROCESSING).append(WAS_REQUIRED_LOGGER_STR).toString()); return; } if (LOGGER.isInfoEnabled()) { LOGGER.info("Processing " + audit.getSubject().getURL()); } // debug tools Date beginProcessDate = null; Date endProcessDate = null; Date endPersistDate; Long persistenceDuration = (long) 0; Long i = (long) 0; Long webResourceId = audit.getSubject().getId(); Long nbOfContent = contentDataService.getNumberOfSSPFromWebResource(audit.getSubject(), HttpStatus.SC_OK); Set<ProcessResult> processResultSet = new HashSet<>(); while (i.compareTo(nbOfContent) < 0) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Processing from ").append(i).append(TO_LOGGER_STR) .append(i + processingTreatmentWindow).append("for ").append(audit.getSubject().getURL()) .toString()); beginProcessDate = Calendar.getInstance().getTime(); } Collection<Content> contentList = contentDataService .getSSPWithRelatedContentFromWebResource(webResourceId, i, processingTreatmentWindow, false); processResultSet.clear(); processResultSet.addAll(processorService.process(contentList, audit.getTestList())); for (ProcessResult processResult : processResultSet) { processResult.setGrossResultAudit(audit); } if (LOGGER.isDebugEnabled()) { endProcessDate = Calendar.getInstance().getTime(); LOGGER.debug(new StringBuilder("Processing of ").append(processingTreatmentWindow) .append(" elements took ").append(endProcessDate.getTime() - beginProcessDate.getTime()) .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString()); } if (LOGGER.isDebugEnabled()) { for (Content content : contentList) { LOGGER.debug("Persisting result for page " + content.getURI()); } } processResultDataService.saveOrUpdate(processResultSet); if (LOGGER.isDebugEnabled()) { endPersistDate = Calendar.getInstance().getTime(); LOGGER.debug(new StringBuilder("Persist processing of ").append(processingTreatmentWindow) .append(" elements took ").append(endPersistDate.getTime() - endProcessDate.getTime()) .append(MS_LOGGER_STR).append("for ").append(audit.getSubject().getURL()).toString()); persistenceDuration = persistenceDuration + (endPersistDate.getTime() - endProcessDate.getTime()); } i = i + processingTreatmentWindow; System.gc(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug(new StringBuilder("Application spent ").append(persistenceDuration) .append(" ms to write in Disk while processing").toString()); } if (processResultDataService.getNumberOfGrossResultFromAudit(audit) > 0) { setStatusToAudit(AuditStatus.CONSOLIDATION); } else { LOGGER.error("Audit has no gross result"); setStatusToAudit(AuditStatus.ERROR); } if (LOGGER.isInfoEnabled()) { LOGGER.info(audit.getSubject().getURL() + " has been processed"); } }