java.nio.charset.StandardCharsets Java Examples

The following examples show how to use java.nio.charset.StandardCharsets. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebSocketTest.java    From engine.io-server-java with MIT License 7 votes vote down vote up
@Test
public void testSend_binary() {
    final EngineIoWebSocket webSocketConnection = Mockito.mock(EngineIoWebSocket.class);
    final WebSocket webSocket = Mockito.spy(new WebSocket(webSocketConnection));

    final byte[] binaryData = "Test string".getBytes(StandardCharsets.UTF_8);
    final Packet<?> packet = new Packet<>(Packet.MESSAGE, binaryData);
    webSocket.send(new ArrayList<Packet<?>>() {{
        add(packet);
    }});

    Mockito.verify(webSocket, Mockito.times(1)).send(Mockito.anyList());

    ServerParser.encodePacket(packet, true, data -> {
        try {
            Mockito.verify(webSocketConnection, Mockito.times(1))
                    .write(Mockito.eq((byte[]) data));
        } catch (IOException ignore) {
        }
    });
}
 
Example #2
Source File: MappingJackson2HttpMessageConverterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void classLevelJsonView() throws Exception {
	MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
	JacksonViewBean bean = new JacksonViewBean();
	bean.setWithView1("with");
	bean.setWithView2("with");
	bean.setWithoutView("without");

	MappingJacksonValue jacksonValue = new MappingJacksonValue(bean);
	jacksonValue.setSerializationView(MyJacksonView3.class);
	this.converter.writeInternal(jacksonValue, null, outputMessage);

	String result = outputMessage.getBodyAsString(StandardCharsets.UTF_8);
	assertThat(result, not(containsString("\"withView1\":\"with\"")));
	assertThat(result, not(containsString("\"withView2\":\"with\"")));
	assertThat(result, containsString("\"withoutView\":\"without\""));
}
 
Example #3
Source File: OpenApiSpecGenerator.java    From flow with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the OpenAPI spec file based on the sources provided.
 *
 * @param sourcesPaths
 *            the source root to be analyzed
 * @param specOutputFile
 *            the target file to write the generation output to
 */
public void generateOpenApiSpec(Collection<Path> sourcesPaths,
        Path specOutputFile) {
    sourcesPaths.forEach(generator::addSourcePath);
    log.info("Parsing java files from {}", sourcesPaths);
    OpenAPI openAPI = generator.generateOpenApi();
    try {
        if (openAPI.getPaths().size() > 0) {
            log.info("writing file {}", specOutputFile);
            FileUtils.writeStringToFile(specOutputFile.toFile(),
                    Json.pretty(openAPI), StandardCharsets.UTF_8);
        } else {
            log.info("There are no connect endpoints to generate.");
            FileUtils.deleteQuietly(specOutputFile.toFile());
        }
    } catch (IOException e) {
        String errorMessage = String.format(
                "Error while writing OpenAPI json file at %s",
                specOutputFile.toString());
        log.error(errorMessage, specOutputFile, e);
    }
}
 
Example #4
Source File: DcosSpec.java    From bdt with Apache License 2.0 6 votes vote down vote up
/**
 * Convert jsonSchema to json
 *
 * @param jsonSchema : jsonSchema to be converted to json
 * @param envVar     : environment variable where to store json
 * @throws Exception exception     *
 */
@Given("^I convert jsonSchema '(.+?)' to json( and save it in variable '(.+?)')?( and save it in file '(.+?)')?")
public void convertJSONSchemaToJSON(String jsonSchema, String envVar, String fileName) throws Exception {
    String json = commonspec.parseJSONSchema(new JSONObject(jsonSchema)).toString();
    if (envVar != null) {
        ThreadProperty.set(envVar, json);
    }
    if (fileName != null) {
        File tempDirectory = new File(System.getProperty("user.dir") + "/target/test-classes/");
        String absolutePathFile = tempDirectory.getAbsolutePath() + "/" + fileName;
        commonspec.getLogger().debug("Creating file {} in 'target/test-classes'", absolutePathFile);
        // Note that this Writer will delete the file if it exists
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(absolutePathFile), StandardCharsets.UTF_8));
        try {
            out.write(json);
        } catch (Exception e) {
            commonspec.getLogger().error("Custom file {} hasn't been created:\n{}", absolutePathFile, e.toString());
        } finally {
            out.close();
        }
    }
}
 
Example #5
Source File: Configuration.java    From bidder with Apache License 2.0 6 votes vote down vote up
/**
 * Used to load ./database.json into Cache2k. This is used when aerospike is not
 * present. This instance will handle its own cache, and do its own win
 * processing.
 *
 * @param fname String. The file name of the database.
 * @throws Exception on file or cache2k errors.
 */
private List<String> readDatabaseIntoCache(String fname) {
	List<String> camps = new ArrayList();
	try {
		String content = new String(Files.readAllBytes(Paths.get(fname)), StandardCharsets.UTF_8);
		content = substitute(content);

		logger.info("Sample DB: {}", content);
		Database db = Database.getInstance();

		List<Campaign> list = DbTools.mapper.readValue(content,
				DbTools.mapper.getTypeFactory().constructCollectionType(List.class, Campaign.class));
		db.update(list);
		for (Campaign camp : list) {
			camps.add(camp.adId);
		}
	} catch (Exception error) {
		error.printStackTrace();
		logger.warn("Initial database {} not read, error: {}", fname, error.getMessage());
	}
	return camps;
}
 
Example #6
Source File: RestDirectoryProvider.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
private UserDirectorySearchResult search(String by, String query) {
    UserDirectorySearchRequest request = new UserDirectorySearchRequest(query);
    request.setBy(by);
    try (CloseableHttpResponse httpResponse = client.execute(RestClientUtils.post(cfg.getEndpoints().getDirectory(), request))) {
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            throw new InternalServerError("REST backend: Error: " + IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8));
        }

        UserDirectorySearchResult response = parser.parse(httpResponse, UserDirectorySearchResult.class);
        for (UserDirectorySearchResult.Result result : response.getResults()) {
            result.setUserId(MatrixID.asAcceptable(result.getUserId(), mxCfg.getDomain()).getId());
        }

        return response;
    } catch (IOException e) {
        throw new InternalServerError("REST backend: I/O error: " + e.getMessage());
    }
}
 
Example #7
Source File: TestRuntimeEL.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadResourceRestrictedFailure() throws Exception {
  exception.expect(IllegalArgumentException.class);

  Path fooFile = Paths.get(resourcesDir.getPath(), "foo.txt");
  Files.write(fooFile, "Hello\n".getBytes(StandardCharsets.UTF_8));
  Files.setPosixFilePermissions(fooFile, ImmutableSet.of(PosixFilePermission.OTHERS_READ));

  RuntimeEL.loadRuntimeConfiguration(runtimeInfo);

  try {
    RuntimeEL.loadResourceRaw("foo.txt", true);
  } finally {
    Files.deleteIfExists(fooFile);
  }
}
 
Example #8
Source File: ConfigOptionsDocGenerator.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static void generateCommonSection(String rootDir, String outputDirectory, OptionsClassLocation[] locations, String pathPrefix) throws IOException, ClassNotFoundException {
	List<OptionWithMetaInfo> commonOptions = new ArrayList<>(32);
	for (OptionsClassLocation location : locations) {
		commonOptions.addAll(findCommonOptions(rootDir, location.getModule(), location.getPackage(), pathPrefix));
	}
	commonOptions.sort((o1, o2) -> {
		int position1 = o1.field.getAnnotation(Documentation.CommonOption.class).position();
		int position2 = o2.field.getAnnotation(Documentation.CommonOption.class).position();
		if (position1 == position2) {
			return o1.option.key().compareTo(o2.option.key());
		} else {
			return Integer.compare(position1, position2);
		}
	});

	String commonHtmlTable = toHtmlTable(commonOptions);
	Files.write(Paths.get(outputDirectory, COMMON_SECTION_FILE_NAME), commonHtmlTable.getBytes(StandardCharsets.UTF_8));
}
 
Example #9
Source File: UserImportExportController.java    From fredbet with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@RequestMapping(value = "/import", method = RequestMethod.POST)
public String uploadJsonFile(UserImportExportCommand command, RedirectAttributes redirect) {
    try {
        MultipartFile myFile = command.getJsonFile();
        if (myFile == null || myFile.getBytes().length == 0) {
            messageUtil.addErrorMsg(redirect, "user.importexport.upload.msg.noFileGiven");
            return REDIRECT_SHOW_PAGE;
        }

        if (!CONTENT_TYPE_JSON.equals(myFile.getContentType())) {
            messageUtil.addErrorMsg(redirect, "user.importexport.upload.msg.noJsonFile");
            return REDIRECT_SHOW_PAGE;
        }

        int importedCount = userImportExportService.importUsers(new String(myFile.getBytes(), StandardCharsets.UTF_8));

        messageUtil.addInfoMsg(redirect, "user.importexport.upload.msg.saved",importedCount);
    } catch (IOException | ExcelReadingException e) {
        LOG.error(e.getMessage(), e);
        messageUtil.addErrorMsg(redirect, "user.importexport.upload.msg.failed", e.getMessage());
    }

    return REDIRECT_SHOW_PAGE;
}
 
Example #10
Source File: VaultManagerImpl.java    From cia with Apache License 2.0 6 votes vote down vote up
@Override
public String decryptValue(final String password, final String userId, final String value) {
	if (password != null && userId != null && value!=null) {
		try {			
			final Key buildKey = buildKey(userId, password);
			final ByteBuffer byteBuffer = ByteBuffer.wrap(Hex.decode(value.getBytes(StandardCharsets.UTF_8)));
			final int ivLength = byteBuffer.getInt();
			final byte[] iv = new byte[ivLength];
			byteBuffer.get(iv);
			final byte[] cipherText = new byte[byteBuffer.remaining()];
			byteBuffer.get(cipherText);
			
			final Cipher cipher = Cipher.getInstance(AES_GCM_NO_PADDING);
			cipher.init(Cipher.DECRYPT_MODE, buildKey, new GCMParameterSpec(TAG_BIT_LENGTH, iv));
			return new String(cipher.doFinal(cipherText),StandardCharsets.UTF_8);
		} catch (final GeneralSecurityException e) {
			LOGGER.error(DECRYPT_VALUE,e);
			return null;
		}		
	} else {
		return null;
	}

}
 
Example #11
Source File: BinaryGenerator.java    From pgadba with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Converts a Duration object to a string the database understands.
 * @param input a Duration
 * @return a string on ISO8601 format
 */
public static byte[] fromInterval(Object input) {
  if (input == null) {
    return new byte[]{};
  }

  if (input instanceof Duration) {
    Duration d = (Duration) input;

    if (d.isZero()) {
      return "0".getBytes(StandardCharsets.UTF_8);
    }

    return d.toString().getBytes(StandardCharsets.UTF_8);
  }

  throw new RuntimeException(input.getClass().getName()
      + " can't be converted to byte[] to send as a Duration to server");
}
 
Example #12
Source File: ThorntailArquillianPlugin.java    From thorntail with Apache License 2.0 6 votes vote down vote up
/**
 * Read the given stream in to a String. This method will close the stream as well.
 *
 * @param stream the input stream.
 * @return the string built out of the data available in the given stream.
 */
private static String readString(InputStream stream) throws IOException {
    if (stream == null) {
        return null;
    }
    try {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = stream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toString(StandardCharsets.UTF_8.name());
    } finally {
        stream.close();
    }
}
 
Example #13
Source File: BingSearchResults.java    From act with GNU General Public License v3.0 6 votes vote down vote up
/** This function fetches the topN Bing search results for the current instance of NameSearchResult object
 * and updates the "topSearchResults" instance variable. Existing value is overridden.
 * @param formattedName name that will be used as search query, lowercase formatted
 * @param topN number of Web results to fetch from Bing Search API
 * @return returns a set of SearchResults containing the topN Bing search results
 * @throws IOException
 */
private Set<SearchResult> fetchTopSearchResults(String formattedName, Integer topN)
    throws IOException {
  LOGGER.debug("Updating topSearchResults for name: %s.", formattedName);
  Set<SearchResult> topSearchResults = new HashSet<>();
  final String queryTerm = URLEncoder.encode(formattedName, StandardCharsets.UTF_8.name());
  // The Bing search API cannot return more than 100 results at once, but it is possible to iterate
  // through the results.
  // For example, if we need topN = 230 results, we will issue the following queries
  // (count and offset are URL parameters)
  // QUERY 1: count = 100, offset = 0
  // QUERY 2: count = 100, offset = 100
  // QUERY 3: count = 30, offset = 200
  Integer iterations = topN / MAX_RESULTS_PER_CALL;
  Integer remainder = topN % MAX_RESULTS_PER_CALL;
  for (int i = 0; i < iterations; i++) {
    topSearchResults.addAll(fetchSearchResults(queryTerm, MAX_RESULTS_PER_CALL, MAX_RESULTS_PER_CALL * i));
  }
  if (remainder > 0) {
    topSearchResults.addAll(fetchSearchResults(queryTerm, remainder, MAX_RESULTS_PER_CALL * iterations));
  }
  return topSearchResults;
}
 
Example #14
Source File: Word2VecTests.java    From deeplearning4j with Apache License 2.0 6 votes vote down vote up
public static List<String> firstNLines(File f, int n){
    List<String> lines = new ArrayList<>();
    try(InputStream is = new BufferedInputStream(new FileInputStream(f))){
        LineIterator lineIter = IOUtils.lineIterator(is, StandardCharsets.UTF_8);
        try{
            for( int i=0; i<n && lineIter.hasNext(); i++ ){
                lines.add(lineIter.next());
            }
        } finally {
            lineIter.close();
        }
        return lines;
    } catch (IOException e){
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: DeferredSettlementTest.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
private Delivery sendMessageToClient(String deliveryTag, int messageBody)
{
    byte[] tag = deliveryTag.getBytes(StandardCharsets.UTF_8);

    Message m = Proton.message();
    m.setBody(new AmqpValue(messageBody));

    byte[] encoded = new byte[BUFFER_SIZE];
    int len = m.encode(encoded, 0, BUFFER_SIZE);

    assertTrue("given array was too small", len < BUFFER_SIZE);

    Sender serverSender = getServer().getSender();
    Delivery serverDelivery = serverSender.delivery(tag);
    int sent = serverSender.send(encoded, 0, len);

    assertEquals("sender unable to send all data at once as assumed for simplicity", len, sent);

    boolean senderAdvanced = serverSender.advance();
    assertTrue("sender has not advanced", senderAdvanced);

    return serverDelivery;
}
 
Example #16
Source File: ProtocolBufferMessageBodyProvider.java    From dropwizard-protobuf with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(
    final Message m,
    final Class<?> type,
    final Type genericType,
    final Annotation[] annotations,
    final MediaType mediaType,
    final MultivaluedMap<String, Object> httpHeaders,
    final OutputStream entityStream)
    throws IOException {

  if (mediaType.getSubtype().contains("text-format")) {
    entityStream.write(m.toString().getBytes(StandardCharsets.UTF_8));
  } else if (mediaType.getSubtype().contains("json-format")) {
    final String formatted = JsonFormat.printer().omittingInsignificantWhitespace().print(m);
    entityStream.write(formatted.getBytes(StandardCharsets.UTF_8));
  } else {
    m.writeTo(entityStream);
  }
}
 
Example #17
Source File: ResourceExplorerTopComponent.java    From syncope with Apache License 2.0 6 votes vote down vote up
private void openScriptEditor(final String name, final String type) throws IOException {
    ImplementationTO node = implementationManagerService.read(type, name);
    String groovyScriptsDirName = System.getProperty("java.io.tmpdir") + "/Groovy/" + node.getType() + '/';
    File groovyScriptsDir = new File(groovyScriptsDirName);
    if (!groovyScriptsDir.exists()) {
        groovyScriptsDir.mkdirs();
    }
    File file = new File(groovyScriptsDirName + name + ".groovy");
    FileWriter fw = new FileWriter(file, StandardCharsets.UTF_8);
    fw.write(node.getBody());
    fw.flush();
    FileObject fob = FileUtil.toFileObject(file.getAbsoluteFile());
    DataObject data = DataObject.find(fob);
    data.getLookup().lookup(OpenCookie.class).open();
    data.addPropertyChangeListener(event -> {
        if (DataObject.PROP_MODIFIED.equals(event.getPropertyName())) {
            //save item remotely
            LOG.info(String.format("Saving Groovy template [%s]", name));
            saveContent();
        }
    });
}
 
Example #18
Source File: ReportServiceLogger.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
private String extractPayload(HttpHeaders headers, @Nullable HttpContent content) {
  StringBuilder messageBuilder = new StringBuilder();
  if (headers != null) {
    appendMapAsString(messageBuilder, headers);
  }
  if (content != null) {
    messageBuilder.append(String.format("%nContent:%n"));
    if (content instanceof UrlEncodedContent) {
      UrlEncodedContent encodedContent = (UrlEncodedContent) content;
      appendMapAsString(messageBuilder, Data.mapOf(encodedContent.getData()));
    } else if (content != null) {
      ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
      try {
        content.writeTo(byteStream);
        messageBuilder.append(byteStream.toString(StandardCharsets.UTF_8.name()));
      } catch (IOException e) {
        messageBuilder.append("Unable to read request content due to exception: " + e);
      }
    }
  }
  return messageBuilder.toString();
}
 
Example #19
Source File: AbstractCommandHandler.java    From jumbune with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected String getStringFromStream(InputStream inputStream){
	StringBuilder response = new StringBuilder();	     
	try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
		for (String line = br.readLine(); br != null && line != null; line = br.readLine()) {
			response.append(line).append(System.lineSeparator());
			}
		}catch (IOException e) {
		LOGGER.error(e.getMessage(), e);
	}
	return response.toString();
}
 
Example #20
Source File: SdkPublishersTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void envelopeWrappedPublisher() {
    FakePublisher<ByteBuffer> fakePublisher = new FakePublisher<>();
    Publisher<ByteBuffer> wrappedPublisher =
        SdkPublishers.envelopeWrappedPublisher(fakePublisher, "prefix:", ":suffix");

    FakeByteBufferSubscriber fakeSubscriber = new FakeByteBufferSubscriber();
    wrappedPublisher.subscribe(fakeSubscriber);
    fakePublisher.publish(ByteBuffer.wrap("content".getBytes(StandardCharsets.UTF_8)));
    fakePublisher.complete();

    assertThat(fakeSubscriber.recordedEvents()).containsExactly("prefix:content", ":suffix");
}
 
Example #21
Source File: BlockDiskCacheUnitTestAbstract.java    From commons-jcs with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that the block disk cache can handle utf encoded strings.
 * <p>
 *
 * @throws Exception
 */
public void testUTF8ByteArray() throws Exception
{
    String string = "IÒtÎrn‚tiÙn‡lizÊti¯n";
    StringBuilder sb = new StringBuilder();
    sb.append(string);
    for (int i = 0; i < 4; i++)
    {
        sb.append(sb.toString()); // big string
    }
    string = sb.toString();
    // System.out.println( "The string contains " + string.length() + " characters" );
    byte[] bytes = string.getBytes(StandardCharsets.UTF_8);

    String cacheName = "testUTF8ByteArray";

    BlockDiskCacheAttributes cattr = getCacheAttributes();
    cattr.setCacheName(cacheName);
    cattr.setMaxKeySize(100);
    cattr.setBlockSizeBytes(200);
    cattr.setDiskPath("target/test-sandbox/BlockDiskCacheUnitTest");
    BlockDiskCache<String, byte[]> diskCache = new BlockDiskCache<>(cattr);

    // DO WORK
    diskCache.update(new CacheElement<>(cacheName, "x", bytes));

    // VERIFY
    assertNotNull(diskCache.get("x"));
    Thread.sleep(1000);
    ICacheElement<String, byte[]> afterElement = diskCache.get("x");
    assertNotNull(afterElement);
    // System.out.println( "afterElement = " + afterElement );
    byte[] after = afterElement.getVal();

    assertNotNull(after);
    assertEquals("wrong bytes after retrieval", bytes.length, after.length);
    // assertEquals( "wrong bytes after retrieval", bytes, after );
    // assertEquals( "wrong bytes after retrieval", string, new String( after, StandardCharsets.UTF_8 ) );

}
 
Example #22
Source File: ComputationExceptionBuilderTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void logsFromString() throws IOException {
    ComputationException computationException = new ComputationExceptionBuilder()
            .addOutLog("out", "outLog")
            .addErrLog("err", "errLog")
            .build();
    assertEquals("outLog", computationException.getOutLogs().get("out"));
    assertEquals("errLog", computationException.getErrLogs().get("err"));

    byte[] bytes = computationException.toZipBytes();
    IOUtils.copy(new ByteArrayInputStream(bytes), Files.newOutputStream(workingDir.resolve("test.zip")));
    ZipFile zip = new ZipFile(workingDir.resolve("test.zip"));
    assertEquals("outLog", IOUtils.toString(Objects.requireNonNull(zip.getInputStream("out")), StandardCharsets.UTF_8));
    assertEquals("errLog", IOUtils.toString(Objects.requireNonNull(zip.getInputStream("err")), StandardCharsets.UTF_8));
}
 
Example #23
Source File: BlockIndex.java    From julongchain with Apache License 2.0 5 votes vote down vote up
private byte[] constructBlockNumTranNumKey(long blockNum, long txNum) {
    byte[] blkNumBytes = Util.longToBytes(blockNum, BlockFileManager.PEEK_BYTES_LEN);
    byte[] txNumBytes = Util.longToBytes(txNum, BlockFileManager.PEEK_BYTES_LEN);
    byte[] result = new byte[0];
    result = ArrayUtils.addAll(result, BLOCK_NUM_TRAN_NUM_IDX_KEY_PREFIX.getBytes(StandardCharsets.UTF_8));
    result = ArrayUtils.addAll(result, blkNumBytes);
    result = ArrayUtils.addAll(result, txNumBytes);
    return result;
}
 
Example #24
Source File: Launcher.java    From knox with Apache License 2.0 5 votes vote down vote up
private static File calcLauncherDir( URL libUrl ) throws UnsupportedEncodingException {
  String libPath = URLDecoder.decode(libUrl.getFile(), StandardCharsets.UTF_8.name());
  File libFile = new File( libPath );
  File dir;
  if( libFile.isDirectory() ) {
    dir = libFile;
  } else {
    dir = libFile.getParentFile();
  }
  return dir;
}
 
Example #25
Source File: GetMailboxesMethodTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void getMailboxesShouldReturnCorrectTotalMessagesCount() throws Exception {
    MailboxPath mailboxPath = MailboxPath.forUser(USERNAME, "name");
    MailboxSession mailboxSession = mailboxManager.createSystemSession(USERNAME);
    mailboxManager.createMailbox(mailboxPath, mailboxSession);
    MessageManager messageManager = mailboxManager.getMailbox(mailboxPath, mailboxSession);
    messageManager.appendMessage(MessageManager.AppendCommand.from(
        Message.Builder.of()
            .setSubject("test")
            .setBody("testmail", StandardCharsets.UTF_8)), mailboxSession);
    messageManager.appendMessage(MessageManager.AppendCommand.from(
        Message.Builder.of()
            .setSubject("test2")
            .setBody("testmail", StandardCharsets.UTF_8)), mailboxSession);

    GetMailboxesRequest getMailboxesRequest = GetMailboxesRequest.builder()
            .build();

    List<JmapResponse> getMailboxesResponse = getMailboxesMethod.processToStream(getMailboxesRequest, methodCallId, mailboxSession).collect(Collectors.toList());

    assertThat(getMailboxesResponse)
            .hasSize(1)
            .extracting(JmapResponse::getResponse)
            .hasOnlyElementsOfType(GetMailboxesResponse.class)
            .extracting(GetMailboxesResponse.class::cast)
            .flatExtracting(GetMailboxesResponse::getList)
            .extracting(Mailbox::getTotalMessages)
            .containsExactly(Number.fromLong(2L));
}
 
Example #26
Source File: Utils.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static Object fromJSON(InputStream is, Function<JSONParser, ObjectBuilder> objBuilderProvider) {
  try {
    return objBuilderProvider.apply(getJSONParser((new InputStreamReader(is, StandardCharsets.UTF_8)))).getValStrict();
  } catch (IOException e) {
    throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Parse error", e);
  }
}
 
Example #27
Source File: JsonLoader.java    From calcite with Apache License 2.0 5 votes vote down vote up
void loadClasspathResource(String location) throws IOException {
  Objects.requireNonNull(location, "location");
  InputStream is = getClass().getResourceAsStream(location);
  if (is == null) {
    throw new IllegalArgumentException("Resource " + location + " not found in the classpath");
  }

  load(new InputStreamReader(is, StandardCharsets.UTF_8));
}
 
Example #28
Source File: AwsProxyHttpServletRequestTest.java    From aws-serverless-java-container with Apache License 2.0 5 votes vote down vote up
@Test
public void contentType_duplicateCase_expectSingleContentTypeHeader() {
    AwsProxyRequestBuilder proxyRequest = getRequestWithHeaders();
    HttpServletRequest request = getRequest(proxyRequest, null, null);

    try {
        request.setCharacterEncoding(StandardCharsets.ISO_8859_1.name());
        assertNotNull(request.getHeader(HttpHeaders.CONTENT_TYPE));
        assertNotNull(request.getHeader(HttpHeaders.CONTENT_TYPE.toLowerCase(Locale.getDefault())));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        fail("Unsupported encoding");
    }
}
 
Example #29
Source File: PersistenceUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static boolean assertStartsWith(InputStream in, String starting) {
    assertNotNull(in);
    byte[] buf = new byte[starting.length()];
    try {
        in.read(buf, 0, buf.length);
        assertEquals(starting, new String(buf, StandardCharsets.UTF_8));
        in.close();
        return true;
    } catch (IOException e) {
        // ignore
    }
    return false;
}
 
Example #30
Source File: WebPlayerView.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
private String decodeUrl(String input) {
    StringBuilder source = new StringBuilder(input);
    for (int a = 0; a < source.length(); a++) {
        char c = source.charAt(a);
        char lower = Character.toLowerCase(c);
        source.setCharAt(a, c == lower ? Character.toUpperCase(c) : lower);
    }
    try {
        return new String(Base64.decode(source.toString(), Base64.DEFAULT), StandardCharsets.UTF_8);
    } catch (Exception ignore) {
        return null;
    }
}