List of usage examples for org.apache.commons.lang ArrayUtils subarray
public static boolean[] subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive)
Produces a new boolean
array containing the elements between the start and end indices.
From source file:org.linagora.linshare.core.utils.LdapHashUtils.java
/** * get the salt from a user login if exists. * @param userPassword userPassword comes from ldap. It is base 64 encoded form with {algo} in the prefix * @return salt last four bytes/*from w ww . ja va 2 s .c om*/ */ public static byte[] getSaltFromUserPassword(String userPassword) { String pass = userPassword.substring(userPassword.indexOf("}") + 1, userPassword.length()); byte[] passBytes = Base64Utils.decode(pass); byte[] salt = ArrayUtils.subarray(passBytes, passBytes.length - 4, passBytes.length); return salt; }
From source file:org.mangelp.fakeSmtpWeb.httpServer.mvc.Dispatcher.java
/** * @param session/*from w ww. ja v a 2 s. c om*/ * @return * @throws ActionHandlerException * If no action handler is found for the detected action */ private ActionResult dispathAction(HttpGetRequest request) throws ActionHandlerException { String parts[] = StringUtils.strip(request.getRequestUri(), "/").split("/"); String actionHandlerName = "default"; String actionName = "default"; if (parts.length > 1) { actionHandlerName = parts[0]; } if (parts.length >= 2) { actionName = parts[1]; } String[] subPath = ArrayUtils.EMPTY_STRING_ARRAY; if (parts.length > 2) { subPath = (String[]) ArrayUtils.subarray(parts, 2, parts.length); } String logPrefix = String.format("Handle %s$%s:%s", actionHandlerName, actionName, StringUtils.join(subPath, "/")); Dispatcher.logger.debug(logPrefix); AbstractActionHandler actionHandler = this.findActionHandler(actionHandlerName); if (actionHandler == null) { throw new ActionHandlerException("No action handler found for " + actionHandlerName); } Actions action = this.findAction(actionName, actionHandler); if (action == null) { throw new ActionHandlerException("No action found within the action handler for " + actionName); } ActionResult result = null; try { ActionInput input = this.createActionInput(request, actionHandler, subPath); result = actionHandler.execute(action, input); } catch (Throwable t) { throw new ActionHandlerException("Failed to execute " + logPrefix, t); } return result; }
From source file:org.marketcetera.marketdata.yahoo.YahooFeedEventTranslator.java
@Override public synchronized List<Event> toEvent(Object inData, String inHandle) throws CoreException { if (!(inData instanceof String)) { throw new UnsupportedOperationException(Messages.UNEXPECTED_DATA.getText(inData.getClass().getName())); }/*from w w w . j a v a2s . c o m*/ String data = (String) inData; SLF4JLoggerProxy.debug(YahooFeedEventTranslator.class, "Received [{}] {}", //$NON-NLS-1$ inHandle, data); // split the data into the query description string and the data itself String[] components = data.split(YahooClientImpl.QUERY_SEPARATOR); // the query consists of a header and a field description, split that again to get just the field description String header = components[0]; String completeFields = header.split("&f=")[1]; //$NON-NLS-1$ // split the fields using the delimiter String[] fields = completeFields.split(YahooClientImpl.FIELD_DELIMITER); //$NON-NLS-1$ // the values are also comma-delimited String completeValues = components[1]; String symbol = completeValues.split(YahooClientImpl.FIELD_DELIMITER)[0]; //extract the field values splitting based on symbol which avoids any , as part of data could be split up properly.. StringBuilder builder = new StringBuilder(); builder.append(YahooClientImpl.DELIMITER_SYMBOL); builder.append(symbol); builder.append(YahooClientImpl.FIELD_DELIMITER); String[] values = completeValues.split(builder.toString()); //$NON-NLS-1$ values = (String[]) ArrayUtils.subarray(values, 1, values.length); if (fields.length != values.length) { String errorMsg = String.format("fields.length: %s, values.length : %s", fields.length, values.length); SLF4JLoggerProxy.warn(YahooFeedEventTranslator.class, errorMsg); throw new CoreException(Messages.UNEXPECTED_VALUE_CODE); } Map<YahooField, String> matchedData = new HashMap<YahooField, String>(); for (int i = 0; i < fields.length; i++) { YahooField field = YahooField.getFieldFor(fields[i].substring(1)); if (field == null) { Messages.UNEXPECTED_FIELD_CODE.error(YahooFeedEventTranslator.class, fields[i]); } else { matchedData.put(field, values[i]); } } return getEventsFrom(matchedData, inHandle); }
From source file:org.mrgeo.image.MrsImagePyramidMetadata.java
public void setImageMetadata(final ImageMetadata[] metadata) { // this will make sure the size of the image metadata matched the zoom, with empty levels as needed if (metadata == null) { imageData = metadata;/*from ww w . j av a 2s .c om*/ for (int i = 0; i <= maxZoomLevel; i++) { imageData = (ImageMetadata[]) ArrayUtils.add(imageData, new ImageMetadata()); } return; } // this could be the case when reading the data in, but the maxzoom comes after the imagedata // in the JSON if (maxZoomLevel <= 0) { setMaxZoomLevel(metadata.length - 1); } imageData = metadata; if ((maxZoomLevel + 1) < imageData.length) { imageData = (ImageMetadata[]) ArrayUtils.subarray(metadata, 0, maxZoomLevel + 1); } else if (maxZoomLevel > imageData.length) { for (int i = imageData.length; i <= maxZoomLevel; i++) { imageData = (ImageMetadata[]) ArrayUtils.add(imageData, new ImageMetadata()); } } }
From source file:org.mrgeo.image.MrsImagePyramidMetadata.java
@Override public void setMaxZoomLevel(final int zoomlevel) { if (imageData == null) { for (int i = 0; i <= zoomlevel; i++) { imageData = (ImageMetadata[]) ArrayUtils.add(imageData, new ImageMetadata()); }//from ww w . j ava 2 s . c om } else if (zoomlevel < maxZoomLevel) { imageData = (ImageMetadata[]) ArrayUtils.subarray(imageData, 0, zoomlevel + 1); } else if (zoomlevel > maxZoomLevel) { for (int i = maxZoomLevel + 1; i <= zoomlevel; i++) { imageData = (ImageMetadata[]) ArrayUtils.add(imageData, new ImageMetadata()); } } this.maxZoomLevel = zoomlevel; }
From source file:org.mrgeo.vector.mrsvector.MrsVectorPyramidMetadata.java
public void setMaxZoomLevel(final int zoomlevel) { if (vectorData == null) { for (int i = 0; i <= zoomlevel; i++) { vectorData = (VectorMetadata[]) ArrayUtils.add(vectorData, new VectorMetadata()); }/*from www .ja va2 s . c o m*/ } else if (zoomlevel < maxZoomLevel) { vectorData = (VectorMetadata[]) ArrayUtils.subarray(vectorData, 0, zoomlevel + 1); } else if (zoomlevel > maxZoomLevel) { for (int i = maxZoomLevel + 1; i <= zoomlevel; i++) { vectorData = (VectorMetadata[]) ArrayUtils.add(vectorData, new VectorMetadata()); } } this.maxZoomLevel = zoomlevel; }
From source file:org.mskcc.cbio.cgds.scripts.ImportTabDelimData.java
/** * Import the CNA Data./*from ww w. j a v a2s. c om*/ * * @throws IOException IO Error. * @throws DaoException Database Error. */ public void importData() throws IOException, DaoException { DaoMicroRna daoMicroRna = new DaoMicroRna(); microRnaIdSet = daoMicroRna.getEntireSet(); geneticProfile = DaoGeneticProfile.getGeneticProfileById(geneticProfileId); FileReader reader = new FileReader(mutationFile); BufferedReader buf = new BufferedReader(reader); String headerLine = buf.readLine(); String parts[] = headerLine.split("\t"); String caseIds[]; // Branch, depending on targetLine setting if (targetLine == null) { caseIds = new String[parts.length - 1]; System.arraycopy(parts, 1, caseIds, 0, parts.length - 1); } else { caseIds = new String[parts.length - 2]; System.arraycopy(parts, 2, caseIds, 0, parts.length - 2); } pMonitor.setCurrentMessage("Import tab delimited data for " + caseIds.length + " cases."); // Add Cases to the Database ArrayList<String> orderedCaseList = new ArrayList<String>(); for (int i = 0; i < caseIds.length; i++) { if (!DaoCaseProfile.caseExistsInGeneticProfile(caseIds[i], geneticProfileId)) { DaoCaseProfile.addCaseProfile(caseIds[i], geneticProfileId); } orderedCaseList.add(caseIds[i]); } DaoGeneticProfileCases daoGeneticProfileCases = new DaoGeneticProfileCases(); daoGeneticProfileCases.addGeneticProfileCases(geneticProfileId, orderedCaseList); String line = buf.readLine(); int numRecordsStored = 0; DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); DaoGeneticAlteration daoGeneticAlteration = DaoGeneticAlteration.getInstance(); DaoMicroRnaAlteration daoMicroRnaAlteration = DaoMicroRnaAlteration.getInstance(); while (line != null) { if (pMonitor != null) { pMonitor.incrementCurValue(); ConsoleUtil.showProgress(pMonitor); } // Ignore lines starting with # if (!line.startsWith("#") && line.trim().length() > 0) { parts = line.split("\t", -1); int startIndex = getStartIndex(); String values[] = (String[]) ArrayUtils.subarray(parts, startIndex, parts.length); String method = null; String geneId = null; if (targetLine != null) { method = parts[0]; geneId = parts[1]; } else { geneId = parts[0]; } if (geneId != null) { if (geneId.contains("///") || geneId.contains("---")) { // Ignore gene IDs separated by ///. This indicates that // the line contains information regarding multiple genes, and // we cannot currently handle this. // Also, ignore gene IDs that are specified as ---. This indicates // the line contains information regarding an unknown gene, and // we cannot currently handle this. logger.debug("Ignoring gene ID: " + geneId); } else { // deal with multiple symbols separate by |, use the first one int ix = geneId.indexOf("|"); if (ix > 0) { geneId = geneId.substring(0, ix); } // Assume we are dealing with Entrez Gene Ids or Symbols. List<CanonicalGene> genes = daoGene.guessGene(geneId); // If no target line is specified or we match the target, process. if (targetLine == null || method.equals(targetLine)) { if (genes.isEmpty()) { // if gene is null, we might be dealing with a micro RNA ID if (geneId.toLowerCase().contains("-mir-")) { // if (microRnaIdSet.contains(geneId)) { // storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId); // numRecordsStored++; // } else { pMonitor.logWarning("microRNA is not known to me: [" + geneId + "]. Ignoring it " + "and all tab-delimited data associated with it!"); // } } else { pMonitor.logWarning("Gene not found: [" + geneId + "]. Ignoring it " + "and all tab-delimited data associated with it!"); } } else if (genes.size() == 1) { storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0)); if (geneticProfile != null && geneticProfile .getGeneticAlterationType() == GeneticAlterationType.COPY_NUMBER_ALTERATION && geneticProfile.showProfileInAnalysisTab()) { storeCna(genes.get(0).getEntrezGeneId(), orderedCaseList, values); } numRecordsStored++; } else { for (CanonicalGene gene : genes) { if (gene.isMicroRNA()) { // for micro rna, duplicate the data storeGeneticAlterations(values, daoGeneticAlteration, gene); } } } } } } } line = buf.readLine(); } if (MySQLbulkLoader.isBulkLoad()) { daoGeneticAlteration.flushGeneticAlteration(); daoMicroRnaAlteration.flushMicroRnaAlteration(); } if (numRecordsStored == 0) { throw new DaoException("Something has gone wrong! I did not save any records" + " to the database!"); } }
From source file:org.mskcc.cbio.portal.scripts.ImportTabDelimData.java
private boolean parseLine(String line, int nrColumns, int sampleStartIndex, int hugoSymbolIndex, int entrezGeneIdIndex, int rppaGeneRefIndex, boolean rppaProfile, boolean discritizedCnaProfile, DaoGeneOptimized daoGene, List<Integer> filteredSampleIndices, List<Integer> orderedSampleList, Map<CnaEvent.Event, CnaEvent.Event> existingCnaEvents, DaoGeneticAlteration daoGeneticAlteration) throws DaoException { boolean recordStored = false; // Ignore lines starting with # if (!line.startsWith("#") && line.trim().length() > 0) { String[] parts = line.split("\t", -1); if (parts.length > nrColumns) { if (line.split("\t").length > nrColumns) { ProgressMonitor.logWarning("Ignoring line with more fields (" + parts.length + ") than specified in the headers(" + nrColumns + "): \n" + parts[0]); return false; }/*from w w w . j av a 2 s. c o m*/ } String values[] = (String[]) ArrayUtils.subarray(parts, sampleStartIndex, parts.length > nrColumns ? nrColumns : parts.length); values = filterOutNormalValues(filteredSampleIndices, values); String geneSymbol = null; if (hugoSymbolIndex != -1) { geneSymbol = parts[hugoSymbolIndex]; } //RPPA: //TODO - we should split up the RPPA scenario from this code...too many if/else because of this if (rppaGeneRefIndex != -1) { geneSymbol = parts[rppaGeneRefIndex]; } if (geneSymbol != null && geneSymbol.isEmpty()) { geneSymbol = null; } if (rppaProfile && geneSymbol == null) { ProgressMonitor.logWarning("Ignoring line with no Composite.Element.REF value"); return false; } //get entrez String entrez = null; if (entrezGeneIdIndex != -1) { entrez = parts[entrezGeneIdIndex]; } if (entrez != null) { if (entrez.isEmpty()) { entrez = null; } else if (!entrez.matches("[0-9]+")) { //TODO - would be better to give an exception in some cases, like negative Entrez values ProgressMonitor.logWarning("Ignoring line with invalid Entrez_Id " + entrez); return false; } } //If all are empty, skip line: if (geneSymbol == null && entrez == null) { ProgressMonitor.logWarning("Ignoring line with no Hugo_Symbol or Entrez_Id value"); return false; } else { if (geneSymbol != null && (geneSymbol.contains("///") || geneSymbol.contains("---"))) { // Ignore gene IDs separated by ///. This indicates that // the line contains information regarding multiple genes, and // we cannot currently handle this. // Also, ignore gene IDs that are specified as ---. This indicates // the line contains information regarding an unknown gene, and // we cannot currently handle this. ProgressMonitor.logWarning("Ignoring gene ID: " + geneSymbol); return false; } else { List<CanonicalGene> genes = null; //If rppa, parse genes from "Composite.Element.REF" column: if (rppaProfile) { genes = parseRPPAGenes(geneSymbol); if (genes == null) { //will be null when there is a parse error in this case, so we //can return here and avoid duplicated messages: return false; } } else { //try entrez: if (entrez != null) { CanonicalGene gene = daoGene.getGene(Long.parseLong(entrez)); if (gene != null) { genes = Arrays.asList(gene); } else { ProgressMonitor.logWarning("Entrez_Id " + entrez + " not found. Record will be skipped for this gene."); return false; } } //no entrez, try hugo: if (genes == null && geneSymbol != null) { // deal with multiple symbols separate by |, use the first one int ix = geneSymbol.indexOf("|"); if (ix > 0) { geneSymbol = geneSymbol.substring(0, ix); } genes = daoGene.getGene(geneSymbol, true); } } if (genes == null || genes.isEmpty()) { genes = Collections.emptyList(); } // If no target line is specified or we match the target, process. if (targetLine == null || parts[0].equals(targetLine)) { if (genes.isEmpty()) { // if gene is null, we might be dealing with a micro RNA ID if (geneSymbol != null && geneSymbol.toLowerCase().contains("-mir-")) { // if (microRnaIdSet.contains(geneId)) { // storeMicroRnaAlterations(values, daoMicroRnaAlteration, geneId); // numRecordsStored++; // } else { ProgressMonitor.logWarning("microRNA is not known to me: [" + geneSymbol + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; // } } else { String gene = (geneSymbol != null) ? geneSymbol : entrez; ProgressMonitor.logWarning("Gene not found for: [" + gene + "]. Ignoring it " + "and all tab-delimited data associated with it!"); return false; } } else if (genes.size() == 1) { List<CnaEvent> cnaEventsToAdd = new ArrayList<CnaEvent>(); if (discritizedCnaProfile) { long entrezGeneId = genes.get(0).getEntrezGeneId(); for (int i = 0; i < values.length; i++) { // temporary solution -- change partial deletion back to full deletion. if (values[i].equals(GeneticAlterationType.PARTIAL_DELETION)) { values[i] = GeneticAlterationType.HOMOZYGOUS_DELETION; } if (values[i].equals(GeneticAlterationType.AMPLIFICATION) // || values[i].equals(GeneticAlterationType.GAIN) >> skipping GAIN, ZERO, HEMIZYGOUS_DELETION to minimize size of dataset in DB // || values[i].equals(GeneticAlterationType.ZERO) // || values[i].equals(GeneticAlterationType.HEMIZYGOUS_DELETION) || values[i].equals(GeneticAlterationType.HOMOZYGOUS_DELETION)) { CnaEvent cnaEvent = new CnaEvent(orderedSampleList.get(i), geneticProfileId, entrezGeneId, Short.parseShort(values[i])); //delayed add: cnaEventsToAdd.add(cnaEvent); } } } recordStored = storeGeneticAlterations(values, daoGeneticAlteration, genes.get(0), geneSymbol); //only add extra CNA related records if the step above worked, otherwise skip: if (recordStored) { for (CnaEvent cnaEvent : cnaEventsToAdd) { if (existingCnaEvents.containsKey(cnaEvent.getEvent())) { cnaEvent.setEventId( existingCnaEvents.get(cnaEvent.getEvent()).getEventId()); DaoCnaEvent.addCaseCnaEvent(cnaEvent, false); } else { //cnaEvent.setEventId(++cnaEventId); not needed anymore, column now has AUTO_INCREMENT DaoCnaEvent.addCaseCnaEvent(cnaEvent, true); existingCnaEvents.put(cnaEvent.getEvent(), cnaEvent.getEvent()); } } } } else { //TODO - review: is this still correct? int otherCase = 0; for (CanonicalGene gene : genes) { if (gene.isMicroRNA() || rppaProfile) { // for micro rna or protein data, duplicate the data boolean result = storeGeneticAlterations(values, daoGeneticAlteration, gene, geneSymbol); if (result == true) { recordStored = true; nrExtraRecords++; } } else { otherCase++; } } if (recordStored) { //skip one, to avoid double counting: nrExtraRecords--; } if (!recordStored) { if (otherCase > 1) { //this means that genes.size() > 1 and data was not rppa or microRNA, so it is not defined how to deal with //the ambiguous alias list. Report this: ProgressMonitor.logWarning("Gene symbol " + geneSymbol + " found to be ambiguous. Record will be skipped for this gene."); } else { //should not occur: throw new RuntimeException( "Unexpected error: unable to process row with gene " + geneSymbol); } } } } } } } return recordStored; }
From source file:org.mule.module.mongo.MongoObjectStore.java
private ObjectId getObjectIdFromKey(final byte[] keyAsBytes) { // hash the key and combine the resulting 16 bytes down to 12 final byte[] md5Digest = DigestUtils.md5Digest(keyAsBytes); final byte[] id = ArrayUtils.subarray(md5Digest, 0, 12); for (int i = 0; i < 4; i++) { id[i * 3] = (byte) (id[i * 3] ^ md5Digest[12 + i]); }//from w ww.j a v a 2 s .co m final ObjectId objectId = new ObjectId(id); return objectId; }
From source file:org.mule.modules.dropbox.DropboxConnector.java
/** * Upload file to Dropbox. The payload is an InputStream containing bytes of * the data to be uploaded.//w w w . j av a 2 s. c om * * This version of the method supports streams of arbitrary length * * {@sample.xml ../../../doc/Dropbox-connector.xml.sample dropbox:upload-long-stream} * * @param fileData * file to be uploaded * @param overwrite * overwrite file in case it already exists * @param path * The destination path * @param filename * The destination file name * * @return Item with the metadata of the uploaded object * @throws Exception * exception */ @SuppressWarnings("resource") @Processor @OAuthProtected @OAuthInvalidateAccessTokenOn(exception = DropboxTokenExpiredException.class) public Item uploadLongStream(@Payload InputStream fileData, @Optional @Default("true") Boolean overwrite, String path, String filename) throws Exception { byte[] buffer = new byte[MAX_UPLOAD_BUFFER_LEN]; Long readBytesAccum = 0L; int readBytes = 0; String uploadId = null; while (readBytes >= 0) { readBytes = fileData.read(buffer); ByteArrayInputStream chunk = new ByteArrayInputStream(ArrayUtils.subarray(buffer, 0, readBytes)); if (readBytes > 0) { WebResource r = this.contentResource.path("chunked_upload"); if (uploadId != null) r = r.queryParam("upload_id", uploadId).queryParam("offset", readBytesAccum.toString()); WebResource.Builder request = r.entity(chunk).accept(MediaType.APPLICATION_JSON) .type(MediaType.APPLICATION_OCTET_STREAM); Chunk uploadedChunk = this.jerseyUtilUpload.put(request, Chunk.class, 200); // Set the uploadId after the first successful upload if (uploadId == null && uploadedChunk != null) uploadId = uploadedChunk.getUploadId(); readBytesAccum += readBytes; if (!uploadedChunk.getOffset().equals(readBytesAccum)) { throw new DropboxException("Error while uploading file. Offsets do not match"); } } } WebResource r = this.contentResource.path("commit_chunked_upload").path(ROOT_PARAM).path(path) .path(filename); try { Item file = this.list(StringUtils.join(new String[] { path, filename }, "/")); if (file != null) { r = r.queryParam("parent_rev", file.getRev()); } } catch (DropboxException e) { // file was not found } return jerseyUtil.post(r.queryParam("overwrite", overwrite.toString()).queryParam("upload_id", uploadId) .accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON), Item.class, 200); }