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:gov.nih.nci.caarray.domain.MultiPartBlob.java
/** * Writes data to the blob. If writeAll is false, this method only writes out data that fills the max blob size. Any * remaining unwritten data is returned. * /*from w w w.j a v a 2 s .co m*/ * @param data the data to write the blob * @param writeAll whether to write out all the data * @param blobPartSize the maximum size of a single blob * @return array of any unwritten data */ private byte[] writeData(byte[] data, int blobPartSize, boolean writeAll) { if (data == null) { return new byte[0]; } int index = 0; while (data.length - index >= blobPartSize) { addBlob(ArrayUtils.subarray(data, index, index + blobPartSize)); index += blobPartSize; } final byte[] unwritten = ArrayUtils.subarray(data, index, data.length); if (writeAll && !ArrayUtils.isEmpty(unwritten)) { addBlob(unwritten); return new byte[0]; } else { return unwritten; } }
From source file:de.codesourcery.jasm16.ide.AssemblyProject.java
protected String getNameWithoutSuffix(IResource resource) { String name;//from www.j a v a 2s . co m if (resource instanceof FileResource) { FileResource file = (FileResource) resource; name = file.getFile().getName(); } else { name = resource.getIdentifier(); } // get base name final String[] components = name.split("[" + Pattern.quote("\\/") + "]"); if (components.length == 1) { name = components[0]; } else { name = components[components.length - 1]; } if (!name.contains(".")) { return name; } final String[] dots = name.split("\\."); return StringUtils.join(ArrayUtils.subarray(dots, 0, dots.length - 1)); }
From source file:net.bible.android.control.page.PageControl.java
/** * Get page title including info about current doc * Return it in 1 or 2 parts allowing it to be split over 2 lines * /* w w w .jav a 2 s . c o m*/ * @return */ public String[] getCurrentDocumentTitleParts() { String title = ""; CurrentPage currentPage = CurrentPageManager.getInstance().getCurrentPage(); if (currentPage != null) { if (currentPage.getCurrentDocument() != null) { title = currentPage.getCurrentDocument().getInitials(); } } String[] parts = titleSplitter.split(title); if (parts.length > 2) { // skip first element which is often the language or book type e.g. GerNeUe, StrongsRealGreek parts = ArrayUtils.subarray(parts, 1, 3); } return parts; }
From source file:com.baidu.terminator.plugin.signer.customized.app.FromAppToDrAPIHttpRequestSigner.java
private String decryptRequest(byte[] content) { byte[] body = ArrayUtils.subarray(content, 8, content.length); String unGipString = ""; try {/*w w w . j a va2 s .com*/ byte[] gzipBytes = RSAUtil.decryptByPrivateKey(body, PRIVATE_KEY); unGipString = GZipUtil.unGzipString(gzipBytes); } catch (UnsupportedEncodingException e) { e.printStackTrace(); logger.error(e); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); logger.error(e); } catch (InvalidKeySpecException e) { e.printStackTrace(); logger.error(e); } catch (InvalidKeyException e) { e.printStackTrace(); logger.error(e); } catch (SignatureException e) { e.printStackTrace(); logger.error(e); } catch (NoSuchPaddingException e) { e.printStackTrace(); logger.error(e); } catch (IllegalBlockSizeException e) { e.printStackTrace(); logger.error(e); } catch (BadPaddingException e) { e.printStackTrace(); logger.error(e); } catch (ShortBufferException e) { e.printStackTrace(); logger.error(e); } catch (IOException e) { e.printStackTrace(); logger.error(e); } return unGipString; }
From source file:io.undertow.server.security.SpnegoAuthenticationTestCase.java
@Test public void testSpnegoSuccess() throws Exception { final TestHttpClient client = new TestHttpClient(); HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL()); HttpResponse result = client.execute(get); assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode()); Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString()); String header = getAuthHeader(NEGOTIATE, values); assertEquals(NEGOTIATE.toString(), header); HttpClientUtils.readResponse(result); Subject clientSubject = login("jduke", "theduke".toCharArray()); Subject.doAs(clientSubject, new PrivilegedExceptionAction<Void>() { @Override//w ww.j av a 2 s. co m public Void run() throws Exception { GSSManager gssManager = GSSManager.getInstance(); GSSName serverName = gssManager .createName("HTTP/" + DefaultServer.getDefaultServerAddress().getHostString(), null); GSSContext context = gssManager.createContext(serverName, SPNEGO, null, GSSContext.DEFAULT_LIFETIME); byte[] token = new byte[0]; boolean gotOur200 = false; while (!context.isEstablished()) { token = context.initSecContext(token, 0, token.length); if (token != null && token.length > 0) { HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL()); get.addHeader(AUTHORIZATION.toString(), NEGOTIATE + " " + FlexBase64.encodeString(token, false)); HttpResponse result = client.execute(get); Header[] headers = result.getHeaders(WWW_AUTHENTICATE.toString()); if (headers.length > 0) { String header = getAuthHeader(NEGOTIATE, headers); byte[] headerBytes = header.getBytes(StandardCharsets.US_ASCII); // FlexBase64.decode() returns byte buffer, which can contain backend array of greater size. // when on such ByteBuffer is called array(), it returns the underlying byte array including the 0 bytes // at the end, which makes the token invalid. => using Base64 mime decoder, which returnes directly properly sized byte[]. token = Base64.getMimeDecoder().decode(ArrayUtils.subarray(headerBytes, NEGOTIATE.toString().length() + 1, headerBytes.length)); } if (result.getStatusLine().getStatusCode() == StatusCodes.OK) { Header[] values = result.getHeaders("ProcessedBy"); assertEquals(1, values.length); assertEquals("ResponseHandler", values[0].getValue()); HttpClientUtils.readResponse(result); assertSingleNotificationType(EventType.AUTHENTICATED); gotOur200 = true; } else if (result.getStatusLine().getStatusCode() == StatusCodes.UNAUTHORIZED) { assertTrue("We did get a header.", headers.length > 0); HttpClientUtils.readResponse(result); } else { fail(String.format("Unexpected status code %d", result.getStatusLine().getStatusCode())); } } } assertTrue(gotOur200); assertTrue(context.isEstablished()); return null; } }); }
From source file:mitm.common.util.AutoDetectUnicodeReader.java
private void detect() throws IOException { if (reader != null) { return;//from w ww . ja va 2 s .c o m } if (encoding == null) { int n = detectBOM(); /* * if n == -1, the a EOF was detected during BOM detection */ if (encoding == null && n != -1) { /* * No BOM found so auto detect charset */ CharsetDetector detector = new CharsetDetector(); byte[] detectionBuffer = new byte[AUTO_DETECT_BYTES]; int read = pushback.read(detectionBuffer); if (read == -1) { throw new IOException("EOF during detection."); } byte[] detectionBytes = ArrayUtils.subarray(detectionBuffer, 0, read); /* * need to push back the bytes read for detection */ pushback.unread(detectionBytes); detector.setText(detectionBytes); CharsetMatch[] matches = detector.detectAll(); if (matches != null) { /* * There might be multiple encodings. Find the first valid one. */ for (CharsetMatch match : matches) { if (match == null) { continue; } if (Charset.isSupported(match.getName())) { encoding = match.getName(); confidence = match.getConfidence(); break; } } } } if (encoding == null) { /* * fallback to ASCII if no encoding is found. */ encoding = CharacterEncoding.US_ASCII; } } reader = new InputStreamReader(pushback, encoding); }
From source file:alluxio.shell.AlluxioShell.java
/** * Method which determines how to handle the user's request, will display usage help to the user * if command format is incorrect./*from w w w . j a v a 2s .c o m*/ * * @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 */ 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 { command.run(cmdline); return 0; } catch (IOException e) { System.out.println(e.getMessage()); LOG.error("Error running " + StringUtils.join(argv, " "), e); return -1; } }
From source file:edu.utdallas.bigsecret.crypter.CrypterMode3.java
/** * {@inheritDoc}//from w w w. j a v a2s . c o m */ public byte[] unwrapFamily(byte[] row, byte[] family, byte[] qualifier, long ts, byte[] value) throws Exception { if (qualifier == null || qualifier.length == 0) throw new Exception("Qualifier data null or no data"); byte[] completeData = m_keyCipher.decrypt(qualifier); int rowSize = Bytes.toInt(completeData, 0, 4); int famSize = Bytes.toInt(completeData, 4, 4); return ArrayUtils.subarray(completeData, 12 + rowSize, 12 + rowSize + famSize); }
From source file:marytts.unitselection.analysis.ProsodyAnalyzer.java
/** * Assign predicted F0 values to the phones by parsing the XML Document * /* w w w .j a v a2s . c o m*/ * @throws Exception * if the Document cannot be accessed */ private void insertTargetF0Values() throws Exception { NodeList phoneNodes; try { phoneNodes = getPhoneNodes(); } catch (Exception e) { throw new Exception("Could not get the phone Nodes from the Document", e); } // count the number of Datagrams we need, which is the number of F0 target values the ProsodyElementHandler will return: int totalNumberOfFrames = getNumberOfFrames(); // this method hinges on the F0 attribute parsing done in modules.acoustic ProsodyElementHandler elementHandler = new ProsodyElementHandler(); double[] f0Targets = elementHandler.getF0Contour(phoneNodes, totalNumberOfFrames); int f0TargetStartIndex = 0; for (Phone phone : phones) { int numberOfLeftUnitFrames = phone.getNumberOfLeftUnitFrames(); int f0TargetMidIndex = f0TargetStartIndex + numberOfLeftUnitFrames; double[] leftF0Targets = ArrayUtils.subarray(f0Targets, f0TargetStartIndex, f0TargetMidIndex); phone.setLeftTargetF0Values(leftF0Targets); int numberOfRightUnitFrames = phone.getNumberOfRightUnitFrames(); int f0TargetEndIndex = f0TargetMidIndex + numberOfRightUnitFrames; double[] rightF0Targets = ArrayUtils.subarray(f0Targets, f0TargetMidIndex, f0TargetEndIndex); phone.setRightTargetF0Values(rightF0Targets); f0TargetStartIndex = f0TargetEndIndex; } return; }
From source file:ee.ria.xroad.signer.console.Utils.java
static ClientId createClientId(String string) throws Exception { String[] parts = string.split(" "); if (parts.length < CLIENT_ID_PARTS) { throw new Exception("Must specify all parts for ClientId"); }/* w ww . jav a 2 s . c o m*/ if (parts.length > CLIENT_ID_PARTS) { String subsystem = parts.length > CLIENT_ID_PARTS ? parts[parts.length - 1] : null; String code = StringUtils.join(ArrayUtils.subarray(parts, 2, parts.length - 1), " "); return ClientId.create(parts[0], parts[1], code, subsystem); } else { return ClientId.create(parts[0], parts[1], parts[2], null); } }