List of usage examples for java.util Arrays copyOfRange
public static boolean[] copyOfRange(boolean[] original, int from, int to)
From source file:com.asakusafw.runtime.io.text.directio.AbstractTextStreamFormatTest.java
/** * input - w/ splitter./*from w w w.j a va 2 s . c o m*/ * @throws Exception if failed */ @Test public void input_splitter_trim_trail() throws Exception { MockFormat format = format(3).withInputSplitter(InputSplitters.byLineFeed()); String[][] data = { { "A", "B", "C", }, { "D", "E", "F", }, { "G", "H", "I", }, }; try (ModelInput<String[]> in = format.createInput(String[].class, "dummy", input(data), 0, 6)) { String[][] result = collect(3, in); assertThat(result, is(Arrays.copyOfRange(data, 0, 2))); } }
From source file:eu.stratosphere.myriad.driver.MyriadDriverFrontend.java
/** * @param args//from w ww . jav a2 s .c o m * @return */ private ParsedOptions parseOptions(String[] args) throws ParseException { ParsedOptions parsedOptions = new ParsedOptions(); if (args.length < 1) { throw new ParseException("Missing dgen-install-dir argument"); } parsedOptions.setFile("dgen-install-dir", new File(args[0])); // parse the command line arguments CommandLineParser parser = new PosixParser(); CommandLine line = parser.parse(this.options, Arrays.copyOfRange(args, 1, args.length)); if (line.hasOption('x')) { parsedOptions.setStringArray("execute-stage", line.getOptionValues('x')); } else { parsedOptions.setErrorMessage("execute-stage", "You should provide at least one data generator stage to be executed"); } try { parsedOptions.setFloat("scaling-factor", Float.parseFloat(line.getOptionValue('s', "1.0"))); } catch (NumberFormatException e) { parsedOptions.setErrorMessage("scaling-factor", e.getMessage()); } try { parsedOptions.setShort("node-count", Short.parseShort(line.getOptionValue('N', "1"))); } catch (NumberFormatException e) { parsedOptions.setErrorMessage("node-count", e.getMessage()); } parsedOptions.setString("dataset-id", line.getOptionValue('m', "default-dataset")); parsedOptions.setFile("output-base", new File(line.getOptionValue('o', "/tmp"))); return parsedOptions; }
From source file:dk.au.cs.karibu.backend.standard.StandardServerRequestHandler.java
@Override public boolean receive(byte[] bytes) { // result of the processing - assumed to succeed boolean processingSuccess = true; // Retrieve producer code producerCode = new String(Arrays.copyOfRange(bytes, 0, PRODUCER_CODE_LENGTH)); // assume that the collectionName will be identical to the producer code collectionName = producerCode;/*w w w . j a v a 2s . co m*/ byte payload[] = Arrays.copyOfRange(bytes, PRODUCER_CODE_LENGTH, bytes.length); // Collect statistics statisticHandler.notifyReceive(producerCode, bytes.length); Deserializer deserializer = null; // Get the deserializer, optimize by caching the reference deserializer = mapCode2Deserializer.get(producerCode); if (deserializer == null) { deserializer = factory.createDeserializer(producerCode); if (deserializer != null) { mapCode2Deserializer.put(producerCode, deserializer); log.info("Caching the deserializer (" + deserializer + ")"); } } BasicDBObject dbo = null; // If the deserializer is null, then we have encountered // an unknown producer - store the raw payload in // a collection named DEADLETTER_CODE and suffixed with // the producer code. if (deserializer == null) { collectionName = StandardServerRequestHandler.DEADLETTER_COLLECTION_NAME_PREFIX + producerCode; log.info("DeadLetter: Unknown producer code (" + producerCode + ")," + " stored binary in collection " + collectionName); deserializer = new DeadLetterDeserializer(); } // Try to create the DBO. Our Mongo JSON parser may throw // a runtime exception if the format is wrong! If the // format is wrong we will store the message in a // special collection try { dbo = deserializer.buildDocumentFromByteArray(payload); } catch (com.mongodb.util.JSONParseException parseException) { String theTrace = ExceptionUtils.getStackTrace(parseException); collectionName = WRONG_FORMAT_COLLECTION_NAME_PREFIX + producerCode; log.info("Illformed JSON received from producer " + producerCode + ", will store in collection " + collectionName + ". " + theTrace); // we can reuse the serializer used for dead letters deserializer = new DeadLetterDeserializer(); dbo = deserializer.buildDocumentFromByteArray(payload); } catch (RuntimeException otherException) { String theTrace = ExceptionUtils.getStackTrace(otherException); log.error("Unhandled runtime exception during deserialization. " + theTrace); } // if another runtime exception happened, the dbo may still be null if (dbo != null) { try { storage.process(collectionName, dbo); } catch (MongoInternalException mie) { processingSuccess = false; String theTrace = ExceptionUtils.getStackTrace(mie); String theMessage = mie.getMessage(); if (theMessage != null && theMessage.contains("is over Max BSON size")) { log.error("Mongo Internal exception during storage on producer code: " + producerCode + " / Message size is over MongoDB limit - the message will be dropped!"); processingSuccess = true; } else { log.error("Mongo Internal exception during storage on producer code: " + producerCode + " / " + theTrace); } } catch (MongoException mongoexc) { processingSuccess = false; String theTrace = ExceptionUtils.getStackTrace(mongoexc); log.error("Mongo exception during storage on producer code: " + producerCode + " / " + theTrace); } catch (Exception me) { processingSuccess = false; String theTrace = ExceptionUtils.getStackTrace(me); log.error("Unhandled runtime exception during storage on producer code: " + producerCode + " / " + theTrace); } } else { // dbo == null thus deserialization failed... // WHY SETTTING IT TO TRUE? processingSuccess = true; // EXPLANATION: Otherwise the message will not // be acknowledged to the MQ and thus pushed back // which means we end in an infinte loop trying // to process it... // If deserialization fails it is programmers mistake // that must be caught during early testing, not caught // in production! } return processingSuccess; }
From source file:de.mylifesucks.oss.ncsimulator.protocol.SerialComm.java
/** * * @param event//from www . ja v a 2s. c o m * @see http://www.mikrokopter.de/ucwiki/en/SerialProtocol */ public void serialEvent(SerialPortEvent event) { //"0x1B,0x1B,0x55,0xAA,0x00" byte[] pattern = new byte[] { 27, 27, 85, (byte) 170, 0 }; switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: try { while (inputStream.available() > 0) { Arrays.fill(readBuffer, (byte) 0); int numBytes = inputStream.read(readBuffer); byte[] data = Arrays.copyOfRange(readBuffer, 0, numBytes); // System.out.println(Hex.encodeHexString(readBuffer)); // System.out.println(Hex.encodeHexString(data)); HandleInputData(data); } } catch (IOException ex) { } break; } }
From source file:com.thinkbiganalytics.spark.datavalidator.Validator.java
static CommandLineParams parseRemainingParameters(String[] args, int from) { CommandLineParams params = new CommandLineParams(); new JCommander(params, Arrays.copyOfRange(args, from, args.length)); return params; }
From source file:alluxio.cli.AlluxioShell.java
/** * Handles the specified shell command request, displaying usage if the command format is invalid. * * @param argv [] Array of arguments given by the user's input from the terminal * @return 0 if command is successful, -1 if an error occurred *//*from w ww . j a v a2 s. c om*/ public int run(String... argv) { if (argv.length == 0) { printUsage(); return -1; } // Sanity check on the number of arguments String cmd = argv[0]; ShellCommand command = mCommands.get(cmd); if (command == null) { // Unknown command (we didn't find the cmd in our dict) String[] replacementCmd = getReplacementCmd(cmd); if (replacementCmd == null) { System.out.println(cmd + " is an unknown command.\n"); printUsage(); return -1; } // Handle command alias, and print out WARNING message for deprecated cmd. String deprecatedMsg = "WARNING: " + cmd + " is deprecated. Please use " + StringUtils.join(replacementCmd, " ") + " instead."; System.out.println(deprecatedMsg); LOG.warn(deprecatedMsg); String[] replacementArgv = (String[]) ArrayUtils.addAll(replacementCmd, ArrayUtils.subarray(argv, 1, argv.length)); return run(replacementArgv); } String[] args = Arrays.copyOfRange(argv, 1, argv.length); CommandLine cmdline = command.parseAndValidateArgs(args); if (cmdline == null) { printUsage(); return -1; } // Handle the command try { return command.run(cmdline); } catch (Exception e) { System.out.println(e.getMessage()); LOG.error("Error running " + StringUtils.join(argv, " "), e); return -1; } }
From source file:com.monitor.baseservice.utils.XCodeUtil.java
/** * 1?xcode?//w ww. j a v a 2s . c o m * 2?base64? * 3?????CRCCRC?8 * 4?CRC * 5??????JSON * * @param xCode * @return * @throws LogicalException */ @SuppressWarnings("unchecked") public static Map<String, Object> xDecode(String xCode) throws LogicalException { // 1 String real = xCode.substring(PREFIX_LENGTH); byte[] rst = Base64.decodeBase64(real); byte[] data = Arrays.copyOf(rst, rst.length - (Long.SIZE / Byte.SIZE)); byte[] crc = Arrays.copyOfRange(rst, data.length, rst.length); // 4 long value = byteArrayToLong(crc); byte[] realCrc = crcUnsigned(data, CRC_KEY.getBytes()); long realValue = byteArrayToLong(realCrc); if (!(value == realValue)) { System.out.println("license verify failed."); throw new LogicalException(RetStat.ERR_BAD_PARAMS, null); } xorCode(data, XOR_KEY); String info = new String(data); return JSONObject.parseObject(info, Map.class); }
From source file:my.adam.smo.common.SymmetricEncryptionBox.java
public byte[] getMessageWithoutSeed(byte[] cryptogram) { return Arrays.copyOfRange(cryptogram, seedLength, cryptogram.length); }
From source file:uk.ac.ebi.eva.pipeline.io.writers.VepAnnotationMongoWriterTest.java
/** * Test that every VariantAnnotation gets written, even if the same variant receives different annotation from * different batches./*from w ww .j a va 2s. com*/ * @throws Exception if the annotationWriter.write fails, or the DBs cleaning fails */ @Test public void shouldWriteAllFieldsIntoMongoDbMultipleSetsAnnotations() throws Exception { String dbName = jobOptions.getDbName(); String dbCollectionVariantsName = jobOptions.getPipelineOptions().getString("db.collections.variants.name"); JobTestUtils.cleanDBs(dbName); List<VariantAnnotation> annotations = new ArrayList<>(); for (String annotLine : vepOutputContent.split("\n")) { annotations.add(AnnotationLineMapper.mapLine(annotLine, 0)); } DBCollection variants = mongoClient.getDB(dbName).getCollection(dbCollectionVariantsName); // first do a mock of a "variants" collection, with just the _id writeIdsIntoMongo(annotations, variants); //prepare annotation sets List<VariantAnnotation> annotationSet1 = new ArrayList<>(); List<VariantAnnotation> annotationSet2 = new ArrayList<>(); List<VariantAnnotation> annotationSet3 = new ArrayList<>(); String[] vepOutputLines = vepOutputContent.split("\n"); for (String annotLine : Arrays.copyOfRange(vepOutputLines, 0, 2)) { annotationSet1.add(AnnotationLineMapper.mapLine(annotLine, 0)); } for (String annotLine : Arrays.copyOfRange(vepOutputLines, 2, 4)) { annotationSet2.add(AnnotationLineMapper.mapLine(annotLine, 0)); } for (String annotLine : Arrays.copyOfRange(vepOutputLines, 4, 7)) { annotationSet3.add(AnnotationLineMapper.mapLine(annotLine, 0)); } // now, load the annotation String collections = jobOptions.getPipelineOptions().getString("db.collections.variants.name"); annotationWriter = new VepAnnotationMongoWriter(mongoOperations, collections); annotationWriter.write(annotationSet1); annotationWriter.write(annotationSet2); annotationWriter.write(annotationSet3); // and finally check that documents in DB have the correct number of annotation DBCursor cursor = variants.find(); while (cursor.hasNext()) { DBObject dbObject = cursor.next(); String id = dbObject.get("_id").toString(); VariantAnnotation annot = converter.convertToDataModelType((DBObject) dbObject.get("annot")); if (id.equals("20_63360_C_T") || id.equals("20_63399_G_A") || id.equals("20_63426_G_T")) { assertEquals(2, annot.getConsequenceTypes().size()); assertEquals(4, annot.getXrefs().size()); } } }
From source file:edu.msu.cme.rdp.readseq.utils.SequenceTrimmer.java
public static String trimMetaSeq(String seq, int trimStart, int trimStop) { int modelPos = 0; char[] bases = seq.toCharArray(); int start = 0, stop = 0; char b;/*from ww w.j a v a 2 s .c om*/ for (int index = 0; index < bases.length; index++) { b = bases[index]; if (b == '.' || b == '~') { continue; } if (modelPos == trimStart) { start = index; } if (modelPos == trimStop) { stop = index; } modelPos++; } if (stop == 0) { stop = bases.length; } return new String(Arrays.copyOfRange(bases, start, stop)); }