List of usage examples for java.util Arrays copyOfRange
public static boolean[] copyOfRange(boolean[] original, int from, int to)
From source file:org.brunocvcunha.instagram4j.requests.internal.InstagramUploadVideoJobRequest.java
@Override public StatusResult execute() throws ClientProtocolException, IOException { String url = getUrl();//w w w . jav a 2s. c om log.info("URL Upload: " + url); HttpPost post = new HttpPost(url); post.addHeader("X-IG-Capabilities", "3Q4="); post.addHeader("X-IG-Connection-Type", "WIFI"); post.addHeader("Cookie2", "$Version=1"); post.addHeader("Accept-Language", "en-US"); post.addHeader("Accept-Encoding", "gzip, deflate"); post.addHeader("Content-Type", "application/octet-stream"); post.addHeader("Session-ID", uploadId); post.addHeader("Connection", "keep-alive"); post.addHeader("Content-Disposition", "attachment; filename=\"video.mp4\""); post.addHeader("job", uploadJob); post.addHeader("Host", "upload.instagram.com"); post.addHeader("User-Agent", InstagramConstants.USER_AGENT); log.info("User-Agent: " + InstagramConstants.USER_AGENT); try (FileInputStream is = new FileInputStream(videoFile)) { byte[] videoData = MyStreamUtils.readContentBytes(is); //TODO: long ranges? need to handle? int requestSize = (int) Math.floor(videoData.length / 4.0); int lastRequestExtra = (int) (videoData.length - (requestSize * 3)); for (int i = 0; i < 4; i++) { int start = i * requestSize; int end; if (i == 3) { end = i * requestSize + lastRequestExtra; } else { end = (i + 1) * requestSize; } int actualLength = (i == 3 ? lastRequestExtra : requestSize); String contentRange = String.format("bytes %s-%s/%s", start, end - 1, videoData.length); //post.setHeader("Content-Length", String.valueOf(end - start)); post.setHeader("Content-Range", contentRange); byte[] range = Arrays.copyOfRange(videoData, start, start + actualLength); log.info("Total is " + videoData.length + ", sending " + actualLength + " (starting from " + start + ") -- " + range.length + " bytes."); post.setEntity(EntityBuilder.create().setBinary(range).build()); try (CloseableHttpResponse response = api.getClient().execute(post)) { int resultCode = response.getStatusLine().getStatusCode(); String content = EntityUtils.toString(response.getEntity()); log.info("Result of part " + i + ": " + content); post.releaseConnection(); response.close(); if (resultCode != 200 && resultCode != 201) { throw new IllegalStateException("Failed uploading video (" + resultCode + "): " + content); } } } return new StatusResult("ok"); } }
From source file:eu.bittrade.libs.steemj.protocol.PublicKey.java
/** * Create a new public key by providing an address as String. * //from w ww . j av a 2s. co m * @param address * The address in its String representation. * <p> * Example: <br> * STM5jYVokmZHdEpwo5oCG3ES2Ca4VYzy6tM8pWWkGdgVnwo2mFLFq * </p> * @throws AddressFormatException * If the input is not base 58 or the checksum does not * validate. */ @JsonCreator public PublicKey(String address) { // As this method is also used for parsing different operations where // the field could be empty we sadly have to handle "null" cases here. if (address != null && !"".equals(address)) { if (address.length() != 53) { LOGGER.warn("The provided address '{}' has an invalid length and will not be set.", address); this.setPublicKey(null); } else { // We expect the first three chars to be the prefix (STM). The // rest // of the String contains the base58 encoded public key and its // checksum. this.prefix = address.substring(0, 3); byte[] decodedAddress = Base58.decode(address.substring(3, address.length())); // As sha256 is used for Bitcoin and ripemd160 for Steem, we // can't // use Bitcoinjs Base58.decodeChecked here and have to do all // stuff // on our own. byte[] potentialPublicKey = Arrays.copyOfRange(decodedAddress, 0, decodedAddress.length - CHECKSUM_BYTES); byte[] expectedChecksum = Arrays.copyOfRange(decodedAddress, decodedAddress.length - CHECKSUM_BYTES, decodedAddress.length); byte[] actualChecksum = calculateChecksum(potentialPublicKey); // And compare them. for (int i = 0; i < expectedChecksum.length; i++) { if (expectedChecksum[i] != actualChecksum[i]) { throw new AddressFormatException("Checksum does not match."); } } this.setPublicKey(ECKey.fromPublicOnly(potentialPublicKey)); } } else { LOGGER.warn( "An empty address has been provided. This can cause some problems if you plan to broadcast this key."); this.setPublicKey(null); } }
From source file:morphy.timeseal.TimesealCoder.java
public byte[] encode(byte stringToWriteBytes[], long timestamp) { byte[] buffer = new byte[10000]; int bytesInLength = stringToWriteBytes.length; System.arraycopy(stringToWriteBytes, 0, buffer, 0, stringToWriteBytes.length); buffer[bytesInLength++] = 24; // \u0024 byte abyte1[] = Long.toString(timestamp).getBytes(); System.arraycopy(abyte1, 0, buffer, bytesInLength, abyte1.length); bytesInLength += abyte1.length;//from w w w . j av a2 s.c o m buffer[bytesInLength++] = 25; // \u0025 int j = bytesInLength; for (bytesInLength += 12 - bytesInLength % 12; j < bytesInLength;) { buffer[j++] = 49; } for (int k = 0; k < bytesInLength; k++) { buffer[k] |= 0x80; // 128 } for (int i1 = 0; i1 < bytesInLength; i1 += 12) { byte byte0 = buffer[i1 + 11]; buffer[i1 + 11] = buffer[i1]; buffer[i1] = byte0; byte0 = buffer[i1 + 9]; buffer[i1 + 9] = buffer[i1 + 2]; buffer[i1 + 2] = byte0; byte0 = buffer[i1 + 7]; buffer[i1 + 7] = buffer[i1 + 4]; buffer[i1 + 4] = byte0; } int l1 = 0; for (int j1 = 0; j1 < bytesInLength; j1++) { buffer[j1] ^= timesealKey[l1]; l1 = (l1 + 1) % timesealKey.length; } for (int k1 = 0; k1 < bytesInLength; k1++) { buffer[k1] -= 32; } buffer[bytesInLength++] = -0x80; // -128 buffer[bytesInLength++] = 10; buffer = Arrays.copyOfRange(buffer, 0, bytesInLength); return buffer; }
From source file:com.walmartlabs.mupd8.application.Config.java
public static Object getScopedValue(JSONObject object, String[] path) { if (path == null) { throw new NullPointerException("path parameter to getScopedValue may not be null"); }/*from www . ja v a 2s. co m*/ if (path.length == 0) { return object; } String key = path[0]; if (!object.containsKey(key)) { // TODO ...or return new JSONObject()? return null; } if (path.length == 1) { return object.get(key); // not necessarily JSONObject } return getScopedValue((JSONObject) object.get(key), Arrays.copyOfRange(path, 1, path.length)); }
From source file:com.joyent.manta.client.multipart.EncryptedServerSideMultipartManagerSerializationIT.java
public final void canResumeUploadWithByteArrayAndMultipleParts() throws Exception { final SupportedCipherDetails cipherDetails = SupportedCiphersLookupMap.INSTANCE .get(config.getEncryptionAlgorithm()); final SecretKey secretKey = SecretKeyUtils.loadKey(config.getEncryptionPrivateKeyBytes(), cipherDetails); final EncryptedMultipartUploaSerializationHelper<ServerSideMultipartUpload> helper = new EncryptedMultipartUploaSerializationHelper<>( kryo, secretKey, cipherDetails, ServerSideMultipartUpload.class); final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; final byte[] content = RandomUtils.nextBytes(FIVE_MB + 1024); final byte[] content1 = Arrays.copyOfRange(content, 0, FIVE_MB + 1); final byte[] content2 = Arrays.copyOfRange(content, FIVE_MB + 1, FIVE_MB + 1024); String contentType = "application/something-never-seen-before; charset=UTF-8"; MantaHttpHeaders headers = new MantaHttpHeaders(); headers.setContentType(contentType); EncryptedMultipartUpload<ServerSideMultipartUpload> upload = multipart.initiateUpload(path, null, headers); MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, content1); Provider provider = upload.getEncryptionState().getEncryptionContext().getCipher().getProvider(); LOGGER.info("Testing serialization with encryption provider: {}", provider.getInfo()); final byte[] serializedEncryptionState = helper.serialize(upload); EncryptedMultipartUpload<ServerSideMultipartUpload> deserializedUpload = helper .deserialize(serializedEncryptionState); MantaMultipartUploadPart part2 = multipart.uploadPart(deserializedUpload, 2, content2); MantaMultipartUploadTuple[] parts = new MantaMultipartUploadTuple[] { part1, part2 }; Stream<MantaMultipartUploadTuple> partsStream = Arrays.stream(parts); multipart.complete(deserializedUpload, partsStream); try (MantaObjectInputStream in = mantaClient.getAsInputStream(path)) { Assert.assertEquals(in.getContentType(), contentType, "Set content-type doesn't match actual content type"); int b;// w w w. j a va2 s. com int i = 0; while ((b = in.read()) != -1) { final byte expected = content[i++]; Assert.assertEquals((byte) b, expected, "Byte [" + (char) b + "] not matched at position: " + (i - 1)); } if (i + 1 < content.length) { fail("Missing " + (content.length - i + 1) + " bytes from Manta stream"); } } }
From source file:coyote.commons.network.http.SSLServerSocketFactoryTest.java
@Test public void createPassesTheProtocolsToServerSocket() throws IOException { // first find the supported protocols SecureServerSocketFactory secureServerSocketFactory = new SecureServerSocketFactory( HTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), null); SSLServerSocket socket = (SSLServerSocket) secureServerSocketFactory.create(); String[] protocols = socket.getSupportedProtocols(); // remove one element from supported protocols if (protocols.length > 0) { protocols = Arrays.copyOfRange(protocols, 0, protocols.length - 1); }/*from ww w . j a v a2s .c om*/ // test secureServerSocketFactory = new SecureServerSocketFactory( HTTPD.makeSSLSocketFactory("/keystore.jks", "password".toCharArray()), protocols); socket = (SSLServerSocket) secureServerSocketFactory.create(); Assert.assertArrayEquals("Enabled protocols specified in the factory were not set to the socket.", protocols, socket.getEnabledProtocols()); }
From source file:edu.umass.cs.nio.JSONPacket.java
/** * @param bytes// w ww .j a v a 2 s. co m * @param offset * @return True if this {@code bytes} could be possibly (but not * necessarily) be in JSON format assuming the default * {@link MessageExtractor} encoding. */ public static final boolean couldBeJSON(byte[] bytes, int offset) { String str; try { str = MessageExtractor.decode(Arrays.copyOfRange(bytes, offset, offset + 4)); return str.startsWith("{") || str.startsWith("["); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return bytes[offset] == '{' || bytes[offset] == '['; }
From source file:com.joyent.manta.client.crypto.SecretKeyUtilsTest.java
@Test(expectedExceptions = Exception.class) public void writeKeyWithNullOutStream() throws IOException { SupportedCipherDetails cipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT; byte[] keyBytes = SecretKeyUtils.generate(cipherDetails).getEncoded(); SecretKey key = SecretKeyUtils.loadKey(Arrays.copyOfRange(keyBytes, 2, 10), cipherDetails); SecretKeyUtils.writeKey(key, null);/* w ww . ja va 2 s . c om*/ }
From source file:bachelorthesis.captchabuilder.builder.BackgroundParser.java
private static CaptchaBuilder parseBackgroundProducer(BackgroundProducerType backgroundProducerType, String[] backgroundProducerOptions, CaptchaBuilder builder) throws ParseException { BackgroundProducerBuilder backgroundProducerBuilder = new BackgroundProducerBuilder(backgroundProducerType); if (backgroundProducerOptions.length == 0) { //return builder.addBackground(backgroundProducerBuilder.create()); builder.addBuildSequence(backgroundProducerBuilder); return builder; }//ww w . j a v a 2s .c o m if (backgroundProducerOptions.length > BackgroundProducerOptions.values().length) { throw new ParseException("BackgroundProducer takes a max of " + BackgroundProducerOptions.values().length + " arguments"); } for (String backgroundProducerOption : backgroundProducerOptions) { if (!backgroundProducerOption.isEmpty()) { try { String[] optionArgs = backgroundProducerOption.split(CaptchaConstants.buildSequencelvl4Delim); BackgroundProducerOptions backgroundProducerOptionType = BackgroundProducerOptions .valueOf(optionArgs[0]); String[] backgroundProducerOptionArgs = Arrays.copyOfRange(optionArgs, 1, optionArgs.length); backgroundProducerBuilder = parseBackgroundProducerOption(backgroundProducerOptionType, backgroundProducerOptionArgs, backgroundProducerBuilder); } catch (IllegalArgumentException e) { throw new ParseException(e.getMessage()); } } } //return builder.addBackground(backgroundProducerBuilder.create()); builder.addBuildSequence(backgroundProducerBuilder); return builder; }
From source file:com.opengamma.analytics.financial.model.finitedifference.CoupledFiniteDifference.java
public PDEResults1D[] solve(final CoupledPDEDataBundle pdeData1, final CoupledPDEDataBundle pdeData2) { Validate.notNull(pdeData1, "pde1 data"); Validate.notNull(pdeData2, "pde2 data"); final PDEGrid1D grid = pdeData1.getGrid(); ArgumentChecker.isTrue(grid == pdeData2.getGrid(), "grids must be same object"); final ConvectionDiffusionPDE1DCoupledCoefficients coeff1 = pdeData1.getCoefficients(); final ConvectionDiffusionPDE1DCoupledCoefficients coeff2 = pdeData2.getCoefficients(); final double[] initalCond1 = pdeData1.getInitialCondition(); final double[] initalCond2 = pdeData2.getInitialCondition(); final BoundaryCondition lower1 = pdeData1.getLowerBoundary(); final BoundaryCondition lower2 = pdeData2.getLowerBoundary(); final BoundaryCondition upper1 = pdeData1.getUpperBoundary(); final BoundaryCondition upper2 = pdeData2.getUpperBoundary(); final double lambda1 = coeff1.getLambda(); final double lambda2 = coeff2.getLambda(); final int tNodes = grid.getNumTimeNodes(); final int xNodes = grid.getNumSpaceNodes(); double[] f = new double[2 * xNodes]; double[][] full1 = null; double[][] full2 = null; if (_showFullResults) { full1 = new double[tNodes][xNodes]; full2 = new double[tNodes][xNodes]; }//from w ww .j av a 2 s .com final double[] q = new double[2 * xNodes]; final double[][] m = new double[2 * xNodes][2 * xNodes]; double[][] a1 = new double[2][xNodes - 2]; final double[][] a2 = new double[2][xNodes - 2]; double[][] b1 = new double[2][xNodes - 2]; final double[][] b2 = new double[2][xNodes - 2]; double[][] c1 = new double[2][xNodes - 2]; final double[][] c2 = new double[2][xNodes - 2]; // final double omega = 1.5; // final int oldCount = 0; // final boolean omegaIncrease = false; double dt, t1, t2, x; double[] x1st, x2nd; System.arraycopy(initalCond1, 0, f, 0, xNodes); System.arraycopy(initalCond2, 0, f, xNodes, xNodes); if (_showFullResults) { if (full1 != null && full2 != null) { full1[0] = Arrays.copyOfRange(f, 0, xNodes); full2[0] = Arrays.copyOfRange(f, xNodes, 2 * xNodes); } } for (int i = 0; i < xNodes - 2; i++) { x = grid.getSpaceNode(i + 1); a1[0][i] = coeff1.getA(0, x); b1[0][i] = coeff1.getB(0, x); c1[0][i] = coeff1.getC(0, x); a1[1][i] = coeff2.getA(0, x); b1[1][i] = coeff2.getB(0, x); c1[1][i] = coeff2.getC(0, x); } final boolean first = true; DecompositionResult decompRes = null; for (int n = 1; n < tNodes; n++) { t1 = grid.getTimeNode(n - 1); t2 = grid.getTimeNode(n); dt = grid.getTimeStep(n - 1); for (int i = 1; i < xNodes - 1; i++) { x = grid.getSpaceNode(i); x1st = grid.getFirstDerivativeCoefficients(i); x2nd = grid.getSecondDerivativeCoefficients(i); q[i] = f[i]; q[i] -= (1 - _theta) * dt * (x2nd[0] * a1[0][i - 1] + x1st[0] * b1[0][i - 1]) * f[i - 1]; q[i] -= (1 - _theta) * dt * (x2nd[1] * a1[0][i - 1] + x1st[1] * b1[0][i - 1] + c1[0][i - 1]) * f[i]; q[i] -= (1 - _theta) * dt * (x2nd[2] * a1[0][i - 1] + x1st[2] * b1[0][i - 1]) * f[i + 1]; q[i] -= (1 - _theta) * dt * lambda1 * f[i + xNodes]; q[xNodes + i] = f[xNodes + i]; q[xNodes + i] -= (1 - _theta) * dt * (x2nd[0] * a1[1][i - 1] + x1st[0] * b1[1][i - 1]) * f[xNodes + i - 1]; q[xNodes + i] -= (1 - _theta) * dt * (x2nd[1] * a1[1][i - 1] + x1st[1] * b1[1][i - 1] + c1[1][i - 1]) * f[xNodes + i]; q[xNodes + i] -= (1 - _theta) * dt * (x2nd[2] * a1[1][i - 1] + x1st[2] * b1[1][i - 1]) * f[xNodes + i + 1]; q[xNodes + i] -= (1 - _theta) * dt * lambda2 * f[i]; a2[0][i - 1] = coeff1.getA(t2, x); b2[0][i - 1] = coeff1.getB(t2, x); c2[0][i - 1] = coeff1.getC(t2, x); a2[1][i - 1] = coeff2.getA(t2, x); b2[1][i - 1] = coeff2.getB(t2, x); c2[1][i - 1] = coeff2.getC(t2, x); m[i][i - 1] = _theta * dt * (x2nd[0] * a2[0][i - 1] + x1st[0] * b2[0][i - 1]); m[i][i] = 1 + _theta * dt * (x2nd[1] * a2[0][i - 1] + x1st[1] * b2[0][i - 1] + c2[0][i - 1]); m[i][i + 1] = _theta * dt * (x2nd[2] * a2[0][i - 1] + x1st[2] * b2[0][i - 1]); m[i][i + xNodes] = dt * _theta * lambda1; m[xNodes + i][xNodes + i - 1] = _theta * dt * (x2nd[0] * a2[1][i - 1] + x1st[0] * b2[1][i - 1]); m[xNodes + i][xNodes + i] = 1 + _theta * dt * (x2nd[1] * a2[1][i - 1] + x1st[1] * b2[1][i - 1] + c2[1][i - 1]); m[xNodes + i][xNodes + i + 1] = _theta * dt * (x2nd[2] * a2[1][i - 1] + x1st[2] * b2[1][i - 1]); m[xNodes + i][i] = dt * _theta * lambda2; } double[] temp = lower1.getLeftMatrixCondition(pdeData1.getCoefficients(), grid, t2); for (int k = 0; k < temp.length; k++) { m[0][k] = temp[k]; } temp = upper1.getLeftMatrixCondition(pdeData1.getCoefficients(), grid, t2); for (int k = 0; k < temp.length; k++) { m[xNodes - 1][xNodes - temp.length + k] = temp[k]; } temp = lower2.getLeftMatrixCondition(pdeData2.getCoefficients(), grid, t2); for (int k = 0; k < temp.length; k++) { m[xNodes][xNodes + k] = temp[k]; } temp = upper2.getLeftMatrixCondition(pdeData2.getCoefficients(), grid, t2); for (int k = 0; k < temp.length; k++) { m[2 * xNodes - 1][2 * xNodes - temp.length + k] = temp[k]; } temp = lower1.getRightMatrixCondition(pdeData1.getCoefficients(), grid, t1); double sum = 0; for (int k = 0; k < temp.length; k++) { sum += temp[k] * f[k]; } q[0] = sum + lower1.getConstant(pdeData1.getCoefficients(), t2); temp = upper1.getRightMatrixCondition(pdeData1.getCoefficients(), grid, t1); sum = 0; for (int k = 0; k < temp.length; k++) { sum += temp[k] * f[xNodes - 1 - k]; } q[xNodes - 1] = sum + upper1.getConstant(pdeData1.getCoefficients(), t2); temp = lower2.getRightMatrixCondition(pdeData2.getCoefficients(), grid, t1); sum = 0; for (int k = 0; k < temp.length; k++) { sum += temp[k] * f[k]; } q[xNodes] = sum + lower2.getConstant(pdeData2.getCoefficients(), t2); temp = upper2.getRightMatrixCondition(pdeData2.getCoefficients(), grid, t1); sum = 0; for (int k = 0; k < temp.length; k++) { sum += temp[k] * f[xNodes - 1 - k]; } q[2 * xNodes - 1] = sum + upper2.getConstant(pdeData2.getCoefficients(), t2); //TODO work out why SOR does not converge here // final DoubleMatrix2D mM = new DoubleMatrix2D(m); // final DecompositionResult res = DCOMP.evaluate(mM); // f = res.solve(q); // // SOR // // int count = sor(omega, grid, freeBoundary, xNodes, f, q, m, t2); // if (oldCount > 0) { // if ((omegaIncrease && count > oldCount) || (!omegaIncrease && count < oldCount)) { // omega = Math.max(1.0, omega * 0.9); // omegaIncrease = false; // } else { // omega = Math.min(1.99, 1.1 * omega); // omegaIncrease = true; // } // } // oldCount = count; if (first) { final DoubleMatrix2D mM = new DoubleMatrix2D(m); decompRes = DCOMP.evaluate(mM); // first = false; } f = decompRes.solve(q); a1 = a2; b1 = b2; c1 = c2; if (_showFullResults) { if (full1 != null && full2 != null) { full1[n] = Arrays.copyOfRange(f, 0, xNodes); full2[n] = Arrays.copyOfRange(f, xNodes, 2 * xNodes); } } } final PDEResults1D[] res = new PDEResults1D[2]; if (_showFullResults) { res[0] = new PDEFullResults1D(grid, full1); res[1] = new PDEFullResults1D(grid, full2); } else { final double[] res1 = Arrays.copyOfRange(f, 0, xNodes); final double[] res2 = Arrays.copyOfRange(f, xNodes, 2 * xNodes); res[0] = new PDETerminalResults1D(grid, res1); res[1] = new PDETerminalResults1D(grid, res2); } return res; }