Пример #1
1
  public static RestxConfig parse(String origin, InputSupplier<InputStreamReader> readerSupplier)
      throws IOException {
    List<ConfigElement> elements = new ArrayList<>();
    StringBuilder doc = new StringBuilder();
    int lineCount = 0;
    for (String line : CharStreams.readLines(readerSupplier)) {
      lineCount++;
      if (line.startsWith("#")) {
        doc.append(line.substring(1).trim()).append("\n");
      } else if (!line.trim().isEmpty()) {
        int index = line.indexOf('=');
        if (index == -1) {
          throw new IOException(
              "invalid config "
                  + origin
                  + " at line "
                  + lineCount
                  + ":"
                  + " line does not contain the equals sign '='");
        }
        String key = line.substring(0, index).trim();
        String value = line.substring(index + 1).trim();

        elements.add(ConfigElement.of(origin, doc.toString().trim(), key, value));
        doc.setLength(0);
      }
    }

    return new StdRestxConfig(elements);
  }
Пример #2
0
 static {
   InputStream vertStream =
       Shader.class
           .getClassLoader()
           .getResourceAsStream("org/terasology/include/globalFunctionsVertIncl.glsl");
   InputStream fragStream =
       Shader.class
           .getClassLoader()
           .getResourceAsStream("org/terasology/include/globalFunctionsFragIncl.glsl");
   try {
     IncludedFunctionsVertex = CharStreams.toString(new InputStreamReader(vertStream));
     IncludedFunctionsFragment = CharStreams.toString(new InputStreamReader(fragStream));
   } catch (IOException e) {
     Logger.getLogger(Shader.class.getName()).severe("Failed to load Include shader resources");
   } finally {
     // JAVA7: Clean up
     try {
       vertStream.close();
     } catch (IOException e) {
       Logger.getLogger(Shader.class.getName())
           .severe("Failed to close globalFunctionsVertIncl.glsl stream");
     }
     try {
       fragStream.close();
     } catch (IOException e) {
       Logger.getLogger(Shader.class.getName())
           .severe("Failed to close globalFunctionsFragIncl.glsl stream");
     }
   }
 }
Пример #3
0
 public void setupLoadOnly(String deobfFileName, boolean loadAll) {
   try {
     File mapData = new File(deobfFileName);
     LZMAInputSupplier zis = new LZMAInputSupplier(new FileInputStream(mapData));
     InputSupplier<InputStreamReader> srgSupplier =
         CharStreams.newReaderSupplier(zis, Charsets.UTF_8);
     List<String> srgList = CharStreams.readLines(srgSupplier);
     rawMethodMaps = Maps.newHashMap();
     rawFieldMaps = Maps.newHashMap();
     Builder<String, String> builder = ImmutableBiMap.<String, String>builder();
     Builder<String, String> mcpBuilder = ImmutableBiMap.<String, String>builder();
     Splitter splitter = Splitter.on(CharMatcher.anyOf(": ")).omitEmptyStrings().trimResults();
     for (String line : srgList) {
       String[] parts = Iterables.toArray(splitter.split(line), String.class);
       String typ = parts[0];
       if ("CL".equals(typ)) {
         parseClass(builder, parts);
         parseMCPClass(mcpBuilder, parts);
       } else if ("MD".equals(typ) && loadAll) {
         parseMethod(parts);
       } else if ("FD".equals(typ) && loadAll) {
         parseField(parts);
       }
     }
     classNameBiMap = builder.build();
     mcpNameBiMap = mcpBuilder.build();
   } catch (IOException ioe) {
     FMLRelaunchLog.log(Level.ERROR, "An error occurred loading the deobfuscation map data", ioe);
   }
   methodNameMaps = Maps.newHashMapWithExpectedSize(rawMethodMaps.size());
   fieldNameMaps = Maps.newHashMapWithExpectedSize(rawFieldMaps.size());
 }
 static {
   try {
     // 读取resource下文件使用下面代码,能够在IDE里面使用,也能在打成jar包后,单独使用
     InputStream mainStream = DictTools.class.getClassLoader().getResourceAsStream("main.txt");
     String main = CharStreams.toString(new InputStreamReader(mainStream, "UTF-8"));
     InputStream assitStream = DictTools.class.getClassLoader().getResourceAsStream("assist.txt");
     String assist = CharStreams.toString(new InputStreamReader(assitStream, "UTF-8"));
     main_kws = buildModelList(main.split("\n"));
     assist_kws = Lists.newArrayList(assist.split("\n"));
   } catch (Exception e) {
     LOG.error("初始化词典错误!", e);
   }
 }
Пример #5
0
  private List<ServiceDescriptor> getServiceInventory(SlotStatus slotStatus) {
    Assignment assignment = slotStatus.getAssignment();
    if (assignment == null) {
      return null;
    }

    String config = assignment.getConfig();

    File cacheFile = getCacheFile(config);
    if (cacheFile.canRead()) {
      try {
        String json = CharStreams.toString(Files.newReaderSupplier(cacheFile, Charsets.UTF_8));
        List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json);
        invalidServiceInventory.remove(config);
        return descriptors;
      } catch (Exception ignored) {
        // delete the bad cache file
        cacheFile.delete();
      }
    }

    InputSupplier<? extends InputStream> configFile =
        ConfigUtils.newConfigEntrySupplier(repository, config, "airship-service-inventory.json");
    if (configFile == null) {
      return null;
    }

    try {
      String json;
      try {
        json = CharStreams.toString(CharStreams.newReaderSupplier(configFile, Charsets.UTF_8));
      } catch (FileNotFoundException e) {
        // no service inventory in the config, so replace with json null so caching works
        json = "null";
      }
      invalidServiceInventory.remove(config);

      // cache json
      cacheFile.getParentFile().mkdirs();
      Files.write(json, cacheFile, Charsets.UTF_8);

      List<ServiceDescriptor> descriptors = descriptorsJsonCodec.fromJson(json);
      return descriptors;
    } catch (Exception e) {
      if (invalidServiceInventory.add(config)) {
        log.error(e, "Unable to read service inventory for %s" + config);
      }
    }
    return null;
  }
  @BeforeClass
  public static void createJavaProjects() throws IOException {
    JavaProjectClient.createJavaProject(PROJECT_NAME_1);

    final String content =
        CharStreams.toString(
            CharStreams.newReaderSupplier(new PMDConfigurationSupplier(), Charsets.UTF_8));
    JavaProjectClient.createFileInProject(PROJECT_NAME_1, PMD_XML, content);

    JavaProjectClient.createJavaProject(PROJECT_NAME_2);

    rules = File.createTempFile(PMDConfigurationsTest.class.getSimpleName() + "-", ".xml");
    Files.copy(new PMDConfigurationSupplier(), rules);
  }
Пример #7
0
 private String tryGetVersion() {
   try {
     InputSupplier<? extends InputStream> versionFileSupplier =
         new InputSupplier<InputStream>() {
           @Override
           public InputStream getInput() throws IOException {
             return VersionCommand.class.getClassLoader().getResourceAsStream("VERSION");
           }
         };
     return CharStreams.toString(
         CharStreams.newReaderSupplier(versionFileSupplier, Charsets.UTF_8));
   } catch (IOException e) {
     throw Throwables.propagate(e);
   }
 }
Пример #8
0
 private static FullHttpResponse newHttpResponseWithStackTrace(
     Exception e, HttpResponseStatus status, @Nullable String simplifiedMessage) {
   StringWriter sw = new StringWriter();
   e.printStackTrace(new PrintWriter(sw));
   StringBuilder sb = new StringBuilder();
   try {
     JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
     jg.writeStartObject();
     String message;
     if (simplifiedMessage == null) {
       Throwable cause = e;
       Throwable childCause = cause.getCause();
       while (childCause != null) {
         cause = childCause;
         childCause = cause.getCause();
       }
       message = cause.getMessage();
     } else {
       message = simplifiedMessage;
     }
     jg.writeStringField("message", message);
     jg.writeStringField("stackTrace", sw.toString());
     jg.writeEndObject();
     jg.close();
     return HttpServices.createJsonResponse(sb.toString(), status);
   } catch (IOException f) {
     logger.error(f.getMessage(), f);
     return new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
   }
 }
Пример #9
0
  @Test(groups = {"functional", "real_server"})
  public void testGetIndex() throws IOException {
    File index = new File(this.documentRoot, "index.html");
    index.createNewFile();
    final int fileSize = 100;
    String content = TestUtils.generateFileContent(fileSize);
    Files.write(content, index, Charsets.UTF_8);

    // Open a client socket and send a simple request
    final Socket socket = new Socket("localhost", this.port);
    OutputStream out = socket.getOutputStream();
    out.write("GET / HTTP/1.1\r\n".getBytes());
    out.write(("Host: localhost:" + this.port + "\r\n").getBytes());
    // this is necessary so we can get the response and not wait for timeout
    out.write("Connection: close\r\n".getBytes());
    out.write("\r\n".getBytes());
    out.flush();

    InputStream in = socket.getInputStream();
    String response = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
    System.out.println(this.documentRoot.getAbsolutePath());
    System.out.println("response=" + response);
    // Assert.assertTrue(response.indexOf("200 OK") > 0);
    Assert.assertEquals(response.substring(0, 15), "HTTP/1.1 200 OK");
    Assert.assertTrue(response.contains(content));
  }
Пример #10
0
  @Test(groups = {"functional", "real_server"})
  public void test404withIndex() throws IOException {
    String filePath = "newDir-" + System.currentTimeMillis();
    final File newDir = new File(documentRoot, filePath);
    newDir.mkdir(); // this should be empty

    // create adn write an index file
    File index = new File(newDir, "index.html");
    index.createNewFile();

    filePath = filePath + "/doesntexist";

    // Open a client socket and send a simple request
    final Socket socket = new Socket("localhost", this.port);
    OutputStream out = socket.getOutputStream();
    out.write(("GET /" + filePath + " HTTP/1.1\r\n").getBytes());
    out.write("Host: localhost\r\n".getBytes());
    out.write("Connection: close\r\n".getBytes());
    out.write("\r\n".getBytes());
    out.flush();

    InputStream in = socket.getInputStream();
    String response = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
    System.out.println("response=" + response);
    Assert.assertEquals(response.substring(0, 12), "HTTP/1.1 404");
  }
Пример #11
0
  private String getSourceMapContentsAt(String urlString) throws IOException {
    URL url = new URL(urlString);

    URLConnection connection = url.openConnection();

    return CharStreams.toString(new InputStreamReader(connection.getInputStream()));
  }
Пример #12
0
 private void testEmailWithEmbeddedImage(SendEmail sendEmail) throws IOException {
   Message mimeMessage = sendEmail.getMimeMessage();
   Assertions.assertThat(mimeMessage.getMimeType()).isEqualTo("multipart/alternative");
   Body mainBody = mimeMessage.getBody();
   Assertions.assertThat(mainBody).isInstanceOf(Multipart.class);
   Multipart multipart = (Multipart) mainBody;
   Assertions.assertThat(multipart.getCount()).isEqualTo(2);
   Entity textPlain = multipart.getBodyParts().get(0);
   Entity secondPart = multipart.getBodyParts().get(1);
   Assertions.assertThat(textPlain.getMimeType()).isEqualTo("text/plain");
   Assertions.assertThat(secondPart.getMimeType()).isEqualTo("multipart/relative");
   Multipart multipartRelative = (Multipart) secondPart.getBody();
   Assertions.assertThat(multipartRelative.getCount()).isEqualTo(2);
   Entity htmlPart = multipartRelative.getBodyParts().get(0);
   Entity imagePart = multipartRelative.getBodyParts().get(1);
   Assertions.assertThat(htmlPart.getMimeType()).isEqualTo("text/html");
   Assertions.assertThat(imagePart.getMimeType()).isEqualTo("image/png");
   TextBody htmlTextBody = (TextBody) htmlPart.getBody();
   String htmlText = Joiner.on('\n').join(CharStreams.readLines(htmlTextBody.getReader()));
   Assertions.assertThat(htmlText)
       .contains("Galaxy S II")
       .contains("img src=\"cid:[email protected]\"");
   String contentId = imagePart.getHeader().getFields("content-id").get(0).getBody();
   Assertions.assertThat(contentId).isEqualTo("*****@*****.**");
 }
Пример #13
0
  @Override
  public void performAction(CmdLineParser parser) throws CommandException {
    if (!configStdIn && null == configFile) {
      throw new ExitWithCodeException(1, "Policy configuration must be provided", true);
    }

    // read configuration from STDIN or file
    String policyConfig;
    try (InputStream is = (configStdIn ? System.in : Files.newInputStream(configFile))) {
      policyConfig = CharStreams.toString(new InputStreamReader(is));

    } catch (IOException e) {
      throw new CommandException(e);
    }

    LOGGER.debug(
        "Adding policy '{}' to API '{}' with configuration: {}",
        () -> policyName,
        this::getModelName,
        () -> policyConfig);

    final ApiPolicy apiPolicy = new ApiPolicy(policyName);
    apiPolicy.setDefinitionId(policyName);

    ManagementApiUtil.invokeAndCheckResponse(
        () ->
            buildServerApiClient(VersionAgnosticApi.class, serverVersion)
                .addPolicy(orgName, name, version, apiPolicy));
  }
Пример #14
0
 @Test
 public void getLocalFileFromFtp() throws IOException {
   assumeTrue(runningOsIsWindows());
   File localFile = fsFtp.getLocalFile(fsFtpRoot.resolveFile("/temp/file2.txt"));
   List<String> lines = CharStreams.readLines(new FileReader(localFile));
   assertThat(lines.get(0)).isEqualTo("this is the file content");
 }
Пример #15
0
  @GET("/backend/aggregate/points")
  String getPoints(String content) throws IOException {
    logger.debug("getPoints(): content={}", content);
    PointsRequest request = ObjectMappers.readRequiredValue(mapper, content, PointsRequest.class);
    List<AggregatePoint> points = aggregateDao.readAggregates(request.getFrom(), request.getTo());

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeArrayFieldStart("points");
    for (AggregatePoint point : points) {
      jg.writeStartArray();
      jg.writeNumber(point.getCaptureTime());
      long durationAverage;
      if (point.getTraceCount() == 0) {
        durationAverage = 0;
      } else {
        durationAverage = point.getDurationTotal() / point.getTraceCount();
      }
      jg.writeNumber(durationAverage / 1000000000.0);
      jg.writeNumber(point.getTraceCount());
      jg.writeEndArray();
    }
    jg.writeEndArray();
    jg.writeNumberField("fixedAggregateIntervalSeconds", fixedAggregateIntervalSeconds);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
  }
Пример #16
0
  public static String load(Class<? extends Template> type) {
    com.vercer.leaf.annotation.Template annotation =
        type.getAnnotation(com.vercer.leaf.annotation.Template.class);
    String name;
    if (annotation != null) {
      name = annotation.value();
    } else {
      name = type.getSimpleName() + ".html";
    }

    InputStream stream = type.getResourceAsStream(name);
    if (stream == null) {
      return null;
    }

    String text;
    try {
      text = CharStreams.toString(new InputStreamReader(stream));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    try {
      stream.close();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // remove windows carriage returns
    text = text.replaceAll("\r", "");

    return text;
  }
 static String loadTextResource(Class<?> clazz, String path) {
   try {
     return CharStreams.toString(new InputStreamReader(clazz.getResourceAsStream(path), UTF_8));
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Пример #18
0
  public List<Child> getAllChildren() throws IOException {
    HttpResponse response = fluentRequest.context(context).path("/children").get();

    String childrenJson =
        CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
    return convertToChildRecords(childrenJson);
  }
  @Override
  public SlackPersona.SlackPresence getPresence(SlackPersona persona) {
    HttpClient client = getHttpClient();
    HttpPost request = new HttpPost("https://slack.com/api/users.getPresence");
    List<NameValuePair> nameValuePairList = new ArrayList<>();
    nameValuePairList.add(new BasicNameValuePair("token", authToken));
    nameValuePairList.add(new BasicNameValuePair("user", persona.getId()));
    try {
      request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
      HttpResponse response = client.execute(request);
      String jsonResponse =
          CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
      LOGGER.debug("PostMessage return: " + jsonResponse);
      JSONObject resultObject = parseObject(jsonResponse);
      // quite hacky need to refactor this
      SlackUserPresenceReply reply =
          (SlackUserPresenceReply) SlackJSONReplyParser.decode(resultObject, this);
      if (!reply.isOk()) {
        return SlackPersona.SlackPresence.UNKNOWN;
      }
      String presence = (String) resultObject.get("presence");

      if ("active".equals(presence)) {
        return SlackPersona.SlackPresence.ACTIVE;
      }
      if ("away".equals(presence)) {
        return SlackPersona.SlackPresence.AWAY;
      }
    } catch (Exception e) {
      // TODO : improve exception handling
      e.printStackTrace();
    }
    return SlackPersona.SlackPresence.UNKNOWN;
  }
 /**
  * Create CDMI data object with InputStream value
  *
  * @param value InputSteam
  * @param charset character set of input stream InputSteam is converted to a String value with
  *     charset UTF_8
  * @return CreateDataObjectOptions
  */
 public CreateDataObjectOptions value(InputStream value, Charset charset) throws IOException {
   jsonObjectBody.addProperty(
       "value",
       (value == null) ? "" : CharStreams.toString(new InputStreamReader(value, charset)));
   this.payload = jsonObjectBody.toString();
   return this;
 }
  private void connectImpl() throws IOException, ClientProtocolException, ConnectException {
    LOGGER.info("connecting to slack");
    lastPingSent = 0;
    lastPingAck = 0;
    HttpClient httpClient = getHttpClient();
    HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken);
    HttpResponse response;
    response = httpClient.execute(request);
    LOGGER.debug(response.getStatusLine().toString());
    String jsonResponse =
        CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
    SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse);
    try {
      sessionParser.parse();
    } catch (ParseException e1) {
      LOGGER.error(e1.toString());
    }
    if (sessionParser.getError() != null) {
      LOGGER.error("Error during authentication : " + sessionParser.getError());
      throw new ConnectException(sessionParser.getError());
    }
    users = sessionParser.getUsers();
    channels = sessionParser.getChannels();
    sessionPersona = sessionParser.getSessionPersona();
    team = sessionParser.getTeam();
    LOGGER.info("Team " + team.getId() + " : " + team.getName());
    LOGGER.info("Self " + sessionPersona.getId() + " : " + sessionPersona.getUserName());
    LOGGER.info(users.size() + " users found on this session");
    LOGGER.info(channels.size() + " channels found on this session");
    String wssurl = sessionParser.getWebSocketURL();

    LOGGER.debug("retrieved websocket URL : " + wssurl);
    ClientManager client = ClientManager.createClient();
    if (proxyAddress != null) {
      client
          .getProperties()
          .put(ClientProperties.PROXY_URI, "http://" + proxyAddress + ":" + proxyPort);
    }
    final MessageHandler handler = this;
    LOGGER.debug("initiating connection to websocket");
    try {
      websocketSession =
          client.connectToServer(
              new Endpoint() {
                @Override
                public void onOpen(Session session, EndpointConfig config) {
                  session.addMessageHandler(handler);
                }
              },
              URI.create(wssurl));
    } catch (DeploymentException e) {
      LOGGER.error(e.toString());
    }
    if (websocketSession != null) {
      SlackConnectedImpl slackConnectedImpl = new SlackConnectedImpl(sessionPersona);
      dispatcher.dispatch(slackConnectedImpl);
      LOGGER.debug("websocket connection established");
      LOGGER.info("slack session ready");
    }
  }
 @Override
 public SlackMessageHandle<GenericSlackReply> postGenericSlackCommand(
     Map<String, String> params, String command) {
   HttpClient client = getHttpClient();
   HttpPost request = new HttpPost(SLACK_API_HTTPS_ROOT + command);
   List<NameValuePair> nameValuePairList = new ArrayList<>();
   for (Map.Entry<String, String> arg : params.entrySet()) {
     if (!"token".equals(arg.getKey())) {
       nameValuePairList.add(new BasicNameValuePair(arg.getKey(), arg.getValue()));
     }
   }
   nameValuePairList.add(new BasicNameValuePair("token", authToken));
   try {
     SlackMessageHandleImpl<GenericSlackReply> handle =
         new SlackMessageHandleImpl<>(getNextMessageId());
     request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
     HttpResponse response = client.execute(request);
     String jsonResponse =
         CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
     LOGGER.debug("PostMessage return: " + jsonResponse);
     GenericSlackReplyImpl reply = new GenericSlackReplyImpl(parseObject(jsonResponse));
     handle.setReply(reply);
     return handle;
   } catch (Exception e) {
     // TODO : improve exception handling
     e.printStackTrace();
   }
   return null;
 }
 private static String getBodyForError(Response response) {
   try {
     return CharStreams.toString(new InputStreamReader(response.getInputStream(), Charsets.UTF_8));
   } catch (IOException e) {
     return "(error getting body)";
   }
 }
Пример #24
0
 public static String toStringAndClose(InputStream input) throws IOException {
   checkNotNull(input, "input");
   try {
     return CharStreams.toString(new InputStreamReader(input, Charsets.UTF_8));
   } finally {
     closeQuietly(input);
   }
 }
 private String readFileAsString(String resourcePath) throws IOException {
   InputStream stream = ConquesoClientTest.class.getResourceAsStream(resourcePath);
   try {
     return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
   } finally {
     stream.close();
   }
 }
Пример #26
0
 public static List<byte[]> parseMessages(final InputStream is) throws IOException {
   Preconditions.checkNotNull(is);
   try (InputStreamReader isr = new InputStreamReader(is, "UTF-8")) {
     return parseMessages(CharStreams.toString(isr));
   } finally {
     is.close();
   }
 }
Пример #27
0
 private static String exec(final String command) {
   try {
     final Process process = Runtime.getRuntime().exec(command);
     return CharStreams.toString(new InputStreamReader(process.getInputStream(), UTF_8));
   } catch (IOException e) {
     throw propagate(e);
   }
 }
Пример #28
0
 private String httpGet(int port, String path) throws IOException {
   URL url = new URL("http://localhost:" + port + path);
   URLConnection conn = url.openConnection();
   Reader reader = new InputStreamReader(conn.getInputStream());
   String response = CharStreams.toString(reader);
   reader.close();
   return response;
 }
Пример #29
0
 public static String getHtml(HttpEntity entity) throws IOException {
   String html = null;
   if (entity != null) {
     InputStream in = entity.getContent();
     html = CharStreams.toString(new InputStreamReader(in, Charsets.UTF_8));
     if (in != null) in.close();
   }
   return html;
 }
Пример #30
0
 public String streamTOString(InputStream stream) {
   String string = null;
   try {
     string = CharStreams.toString(new InputStreamReader(stream, "UTF-8"));
   } catch (IOException e) {
     e.printStackTrace();
   }
   return string;
 }