/** * Encode ticket. * * @param ticket the ticket * @return the ticket */ protected Ticket encodeTicket(final Ticket ticket) { if (this.cipherExecutor == null) { logger.trace("Ticket encryption is not enabled. Falling back to default behavior"); return ticket; } if (ticket == null) { return ticket; } logger.info("Encoding [{}]", ticket); final byte[] encodedTicketObject = CompressionUtils.serializeAndEncodeObject( this.cipherExecutor, ticket); final String encodedTicketId = encodeTicketId(ticket.getId()); final Ticket encodedTicket = new EncodedTicket( ByteSource.wrap(encodedTicketObject), encodedTicketId); logger.info("Created [{}]", encodedTicket); return encodedTicket; }
@Override public ByteSource getGraphics(final String username) { try { final GraphicalUserAuthenticationProperties gua = casProperties.getAuthn().getGua(); final Response<SearchResult> response = searchForId(username); if (LdapUtils.containsResultEntry(response)) { final LdapEntry entry = response.getResult().getEntry(); final LdapAttribute attribute = entry.getAttribute(gua.getLdap().getImageAttribute()); if (attribute != null && attribute.isBinary()) { return ByteSource.wrap(attribute.getBinaryValue()); } } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return ByteSource.empty(); }
/** * Encode ticket. * * @param ticket the ticket * @return the ticket */ protected Ticket encodeTicket(final Ticket ticket) { if (!isCipherExecutorEnabled()) { LOGGER.trace(MESSAGE); return ticket; } if (ticket == null) { LOGGER.debug("Ticket passed is null and cannot be encoded"); return null; } LOGGER.debug("Encoding ticket [{}]", ticket); final byte[] encodedTicketObject = SerializationUtils.serializeAndEncodeObject(this.cipherExecutor, ticket); final String encodedTicketId = encodeTicketId(ticket.getId()); final Ticket encodedTicket = new EncodedTicket(ByteSource.wrap(encodedTicketObject), encodedTicketId); LOGGER.debug("Created encoded ticket [{}]", encodedTicket); return encodedTicket; }
public void testGet_io() throws IOException { assertEquals(-1, ArbitraryInstances.get(InputStream.class).read()); assertEquals(-1, ArbitraryInstances.get(ByteArrayInputStream.class).read()); assertEquals(-1, ArbitraryInstances.get(Readable.class).read(CharBuffer.allocate(1))); assertEquals(-1, ArbitraryInstances.get(Reader.class).read()); assertEquals(-1, ArbitraryInstances.get(StringReader.class).read()); assertEquals(0, ArbitraryInstances.get(Buffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(CharBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(ByteBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(ShortBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(IntBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(LongBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(FloatBuffer.class).capacity()); assertEquals(0, ArbitraryInstances.get(DoubleBuffer.class).capacity()); ArbitraryInstances.get(PrintStream.class).println("test"); ArbitraryInstances.get(PrintWriter.class).println("test"); assertNotNull(ArbitraryInstances.get(File.class)); assertFreshInstanceReturned( ByteArrayOutputStream.class, OutputStream.class, Writer.class, StringWriter.class, PrintStream.class, PrintWriter.class); assertEquals(ByteSource.empty(), ArbitraryInstances.get(ByteSource.class)); assertEquals(CharSource.empty(), ArbitraryInstances.get(CharSource.class)); assertNotNull(ArbitraryInstances.get(ByteSink.class)); assertNotNull(ArbitraryInstances.get(CharSink.class)); }
protected void saveFiles(final ItemId itemId, File filesDir) throws IOException { ObjectNode files = itemRequests.listFiles(itemId); ArrayNode fileList = files.withArray("files"); if( fileList.size() > 0 ) { filesDir.mkdirs(); for( JsonNode file : fileList ) { final String name = file.get("name").asText(); ByteSource src = new ByteSource() { @Override public InputStream openStream() throws IOException { return itemRequests.file(itemRequests.successfulRequest(), itemId, name).body().asInputStream(); } }; File destFile = new File(filesDir, name); destFile.getParentFile().mkdirs(); src.copyTo(Files.asByteSink(destFile)); } } }
@Override public SnapshotManager getSnapshotManager() { SnapshotManager snapshotManager = super.getSnapshotManager(); snapshotManager.setCreateSnapshotConsumer(createSnapshotProcedure); snapshotManager.setSnapshotCohort(new RaftActorSnapshotCohort() { @Override public State deserializeSnapshot(final ByteSource snapshotBytes) throws IOException { return ByteState.of(snapshotBytes.read()); } @Override public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) { } @Override public void applySnapshot(final State snapshotState) { } }); return snapshotManager; }
void setSnapshotBytes(final ByteSource snapshotBytes) throws IOException { if (this.snapshotBytes != null) { return; } snapshotSize = snapshotBytes.size(); snapshotInputStream = snapshotBytes.openStream(); this.snapshotBytes = snapshotBytes; totalChunks = (int) (snapshotSize / snapshotChunkSize + (snapshotSize % snapshotChunkSize > 0 ? 1 : 0)); LOG.debug("{}: Snapshot {} bytes, total chunks to send: {}", logName, snapshotSize, totalChunks); replyReceivedForOffset = -1; chunkIndex = FIRST_CHUNK_INDEX; }
@Test public void testGetExistingYangTextSchemaSource() throws Exception { String source = "Test source."; YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource( ID, ByteSource.wrap(source.getBytes())); Mockito.when(mockedLocalRepository.getSchemaSource(ID, YangTextSchemaSource.class)).thenReturn( Futures.immediateCheckedFuture(schemaSource)); Future<YangTextSchemaSourceSerializationProxy> retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID); assertTrue(retrievedSourceFuture.isCompleted()); YangTextSchemaSource resultSchemaSource = Await.result(retrievedSourceFuture, Duration.Zero()).getRepresentation(); assertEquals(resultSchemaSource.getIdentifier(), schemaSource.getIdentifier()); assertArrayEquals(resultSchemaSource.read(), schemaSource.read()); }
/** * Read the contents of the source into a byte array. * @param source the byte array source * @return the byte[] read from the source or null */ private byte[] consumeByteSourceOrNull(final ByteSource source) { try { if (source == null || source.isEmpty()) { return null; } return source.read(); } catch (final IOException e) { logger.warn("Could not consume the byte array source", e); return null; } }
/** * Get salt. * * @return the byte[] for the salt or null */ @JsonIgnore public byte[] getSalt() { try { return ByteSource.wrap(convertSaltToByteArray()).read(); } catch (final IOException e) { LOGGER.warn("Salt cannot be read because the byte array from source could not be consumed"); } return null; }
/** * Creates a new encoded ticket using the given encoder to encode the given * source ticket. * * @param encodedTicket the encoded ticket * @param encodedTicketId the encoded ticket id */ public EncodedTicket(final ByteSource encodedTicket, final String encodedTicketId) { try { this.id = encodedTicketId; this.encodedTicket = encodedTicket.read(); } catch (final IOException e) { throw new RuntimeException(e); } }
/** * Checks if is token ntlm. * * @param tokenSource the token * @return true, if token ntlm */ private boolean isTokenNtlm(final ByteSource tokenSource) { final byte[] token = consumeByteSourceOrNull(tokenSource); if (token == null || token.length < NTLM_TOKEN_MAX_LENGTH) { return false; } for (int i = 0; i < NTLM_TOKEN_MAX_LENGTH; i++) { if (NTLMSSP_SIGNATURE[i].byteValue() != token[i]) { return false; } } return true; }
/** * Get salt. * * @return the byte[] for the salt or null */ public byte[] getSalt() { try { return ByteSource.wrap(this.salt).read(); } catch (final IOException e) { LOGGER.warn("Salt cannot be read because the byte array from source could not be consumed"); } return null; }
/** * Decorates a map using the provided algorithms. * <p>Takes a salt and secretKey so that it can work with a distributed cache. * * @param decoratedMap the map to decorate. CANNOT be NULL. * @param hashAlgorithm the algorithm to use for hashing. CANNOT BE NULL. * @param salt the salt, as a String. Gets converted to bytes. CANNOT be NULL. * @param secretKeyAlgorithm the encryption algorithm. CANNOT BE NULL. * @param secretKey the secret to use. CANNOT be NULL. * @throws RuntimeException if the algorithm cannot be found or the iv size cant be determined. */ public EncryptedMapDecorator(final Map<String, String> decoratedMap, final String hashAlgorithm, final byte[] salt, final String secretKeyAlgorithm, final Key secretKey) { try { this.decoratedMap = decoratedMap; this.key = secretKey; this.salt = ByteSource.wrap(salt); this.secretKeyAlgorithm = secretKeyAlgorithm; this.messageDigest = MessageDigest.getInstance(hashAlgorithm); this.ivSize = getIvSize(); } catch (final Exception e) { throw new RuntimeException(e); } }
private static Object reAssembleMessage(final AssembledMessageState state) throws MessageSliceException { try { final ByteSource assembledBytes = state.getAssembledBytes(); try (ObjectInputStream in = new ObjectInputStream(assembledBytes.openStream())) { return in.readObject(); } } catch (IOException | ClassNotFoundException e) { throw new MessageSliceException(String.format("Error re-assembling bytes for identifier %s", state.getIdentifier()), e); } }
@Override protected Event doExecute(final RequestContext requestContext) throws Exception { final String username = requestContext.getRequestParameters().get("username"); if (StringUtils.isBlank(username)) { throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY); } final ByteSource graphics = repository.getGraphics(username); if (graphics == null || graphics.isEmpty()) { throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE, StringUtils.EMPTY); } final byte[] image = EncodingUtils.encodeBase64ToByteArray(graphics.read()); requestContext.getFlowScope().put("guaUsername", username); requestContext.getFlowScope().put("guaUserImage", new String(image, StandardCharsets.UTF_8)); return success(); }
@Override public ByteSource getGraphics(final String username) { try { final GraphicalUserAuthenticationProperties gua = casProperties.getAuthn().getGua(); final Resource resource = resourceLoader.getResource(gua.getResource().getLocation()); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(resource.getInputStream(), bos); return ByteSource.wrap(bos.toByteArray()); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return ByteSource.empty(); }
@Override public Snapshot.State deserializeSnapshot(final ByteSource snapshotBytes) { try { return (Snapshot.State) SerializationUtils.deserialize(snapshotBytes.read()); } catch (IOException e) { throw new RuntimeException("Error deserializing state", e); } }
/** * Read the contents of the source into a byte array. * @param source the byte array source * @return the byte[] read from the source or null */ private static byte[] consumeByteSourceOrNull(final ByteSource source) { try { if (source == null || source.isEmpty()) { return null; } return source.read(); } catch (final IOException e) { LOGGER.warn("Could not consume the byte array source", e); return null; } }
/** * Get salt. * * @return the byte[] for the salt or null */ @JsonIgnore public byte[] getSalt() { try { return ByteSource.wrap(this.salt.getBytes(Charset.defaultCharset())).read(); } catch (final IOException e) { LOGGER.warn("Salt cannot be read because the byte array from source could not be consumed"); } return null; }
/** * Creates a new encoded ticket using the given encoder to encode the given * source ticket. * * @param encodedTicket the encoded ticket * @param encodedTicketId the encoded ticket id */ public EncodedTicket(final ByteSource encodedTicket, final String encodedTicketId) { try { this.id = encodedTicketId; this.encodedTicket = encodedTicket.read(); } catch (final IOException e) { throw Throwables.propagate(e); } }
public static QuoteFilter loadFrom(ByteSource source) throws IOException { final ImmutableList<String> input = source.asCharSource(Charsets.UTF_8).readLines(); if (input.isEmpty()) { throw new IOException("Attempted to load QuoteFilter from empty file"); } final int numEntries = Integer.parseInt(input.get(0)); final int expectedLines = 2 * numEntries + 1; if (input.size() != expectedLines) { throw new IOException(String.format( "Invalid number of lines when loading QuoteFiler. Expected %d, got %d", expectedLines, input.size())); } final ImmutableMap.Builder<Symbol, ImmutableRangeSet<Integer>> ret = ImmutableMap.builder(); int curLine = 1; for (int i = 0; i < numEntries; ++i) { final Symbol docid = Symbol.from(input.get(curLine++)); final ImmutableRangeSet.Builder<Integer> ranges = ImmutableRangeSet.builder(); for (final String part : StringUtils.OnSpaces.split(input.get(curLine++))) { final List<String> endPointStrings = DASH_SPLITTER.splitToList(part); if (endPointStrings.size() != 2) { throw new IOException(String.format("Invalid range serialization %s", part)); } ranges.add(Range.closed(Integer.parseInt(endPointStrings.get(0)), Integer.parseInt(endPointStrings.get(1)))); } ret.put(docid, ranges.build()); } return QuoteFilter.createFromBannedRegions(ret.build()); }
@Test public void testSerialization() throws IOException { final QuoteFilter reference = QuoteFilter.createFromBannedRegions( ImmutableMap.of( Symbol.from("dummy"), ImmutableRangeSet.<Integer>builder().add(Range.closed(4, 60)).add(Range.closed(67, 88)) .build(), Symbol.from("dummy2"), ImmutableRangeSet.of(Range.closed(0, 20)))); final ByteArraySink sink = new ByteArraySink(); reference.saveTo(sink); final ByteSource source = ByteSource.wrap(sink.toByteArray()); final Object restored = QuoteFilter.loadFrom(source); assertEquals(reference, restored); }
public static InputStream resource(String path) throws IOException { try { URL url = Resources.getResource(path); ByteSource source = Resources.asByteSource(url); return source.openStream(); } catch (IllegalArgumentException ex) { throw new MissingObject("template", path); } }
private static synchronized List<EnvFileFullReport> getFileFullReports(CharSequence charSequence) { List<EnvFileFullReport> fileReports = new ArrayList<>(); try { InputStream virtualFile = IOUtils.toInputStream(charSequence, "UTF-8"); String md5Hash = ByteSource.wrap(ByteStreams.toByteArray(virtualFile)).hash(Hashing.md5()).toString(); fileReports = fileReportCache.getIfPresent(md5Hash); virtualFile.reset(); if (fileReports == null && JNomadInspection.jnomad != null) { //no cache; load file from disk fileReports = new ArrayList<>(); QueryLiteralExtractor.isDisabled = false; SourceCodeExtract extract = JNomadInspection.jnomad.scanSingleFile(virtualFile); if (extract.getQueryLiteralExtractor().getQueryFound()) { List<SourceCodeExtract> scanList = Collections.singletonList(extract); queryParser.run(scanList); for (JNomadPluginConfiguration.DBEnvironment env : pluginConfiguration.getEnvironmentList()) { for (JNomadPluginConfiguration.DBConnection conn : env.getConnectionList()) { EnvFileFullReport envReport = new EnvFileFullReport(null, JNomadInspection.jnomad, conn.getDataType(), queryParser.getAliasMap(), scanList, conn.toConnection()); envReport.setEnvironment(env); fileReports.add(envReport); } } fileReportCache.put(md5Hash, fileReports); } } } catch (Exception e) { e.printStackTrace(); } return fileReports; }
private Response videoPartResponse(File file, String rangeHeader) { Range range = calculateRange(file, rangeHeader); ByteSource filePart = sliceFile(file, range); StreamingOutput stream = createStream(filePart); return Response.status(PARTIAL_CONTENT) .entity(stream) .header("Accept-Ranges", "bytes") .header("Content-Range", toContentRange(range, file.length())) .header("Content-Length",range.getLength()) .header("Last-Modified", new Date(file.lastModified())) .build(); }
private StreamingOutput createStream(final ByteSource filePart) { return outputStream -> { try (InputStream inputStream = filePart.openBufferedStream()) { ByteStreams.copy(inputStream, outputStream); } }; }
private static Supplier<InputStream> getStream(ByteSource byteSource) { return () -> { try { return byteSource.openStream(); } catch (IOException e) { throw new RuntimeException("Could not open stream", e); } }; }
@Test public void itThrowsIllegalArgumentIfTheSubmittedMessageSizeIsLargerThanTheMaximum() { session.parseEhloResponse(EHLO_DOMAIN, Lists.newArrayList("SIZE 1024")); MessageContent largeMessage = MessageContent.of(ByteSource.wrap(new byte[1025])); assertThatThrownBy(() -> session.send(largeMessage)) .isInstanceOf(MessageTooLargeException.class) .hasMessage("[unidentified-connection] This message is too large to be sent (max size: 1024)"); }
@Test public void getExistingYangTextSchemaSource() throws IOException, SchemaSourceException { String source = "Test"; YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource( ID, ByteSource.wrap(source.getBytes())); YangTextSchemaSourceSerializationProxy sourceProxy = new YangTextSchemaSourceSerializationProxy(schemaSource); Mockito.when(mockedRemoteSchemaRepository.getYangTextSchemaSource(ID)) .thenReturn(Futures.successful(sourceProxy)); YangTextSchemaSource providedSource = remoteSchemaProvider.getSource(ID).checkedGet(); assertEquals(providedSource.getIdentifier(), ID); assertArrayEquals(providedSource.read(), schemaSource.read()); }