Esempio n. 1
0
  public static String runHttpPostCommand(String url, String jsonBody) throws IOException {
    String return_;
    DefaultHttpClient client = new DefaultHttpClient();
    InputStream isStream = null;
    try {
      HttpParams httpParameters = new BasicHttpParams();
      int timeoutConnection = 1000;
      int timeoutSocket = 1000;
      HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
      HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
      client.setParams(httpParameters);

      HttpPost postRequest = new HttpPost(url);
      if (StringUtils.isNotEmpty(jsonBody))
        postRequest.setEntity(new StringEntity(jsonBody, StandardCharsets.UTF_8));
      postRequest.setHeader("Content-type", "application/json");

      HttpResponse resp = client.execute(postRequest);

      if (resp == null || resp.getEntity() == null) {
        throw new ESHttpException(
            "Unable to execute POST URL ("
                + url
                + ") Exception Message: < Null Response or Null HttpEntity >");
      }

      isStream = resp.getEntity().getContent();

      if (resp.getStatusLine().getStatusCode() != 200) {

        throw new ESHttpException(
            "Unable to execute POST URL ("
                + url
                + ") Exception Message: ("
                + IOUtils.toString(isStream, StandardCharsets.UTF_8.toString())
                + ")");
      }

      return_ = IOUtils.toString(isStream, StandardCharsets.UTF_8.toString());
      logger.debug("POST URL API: {} with JSONBody {} returns: {}", url, jsonBody, return_);
    } catch (Exception e) {
      throw new ESHttpException(
          "Caught an exception during execution of URL ("
              + url
              + ")Exception Message: ("
              + e
              + ")");
    } finally {
      if (isStream != null) isStream.close();
    }
    return return_;
  }
 private String urlEncode(final String input) {
   try {
     return URLEncoder.encode(input, StandardCharsets.UTF_8.toString());
   } catch (final UnsupportedEncodingException e) {
     throw new RuntimeException("Unable to encode search term, UTF-8 is unsupported", e);
   }
 }
 @Override
 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   resp.setCharacterEncoding(StandardCharsets.UTF_8.toString());
   resp.setContentType(PLAIN_TEXT_UTF_8);
   Resources.asCharSource(Resources.getResource("assets/banner.txt"), StandardCharsets.UTF_8)
       .copyTo(resp.getWriter());
 }
  @Test
  public void testParse() throws Exception {
    String inputHtml =
        new Scanner(
                this.getClass().getResourceAsStream("Motel6_1.json"),
                StandardCharsets.UTF_8.toString())
            .useDelimiter("\\Z")
            .next();

    ArrayList<RoomInfo> roomInfos =
        parser.parse(
            inputHtml,
            new RoomPhotoDownloader() {
              @Override
              public Path download(String url) {
                return NetworkUtils.srcImageToSavePath(url, Paths.get(""));
              }
            });

    Iterator<RoomInfo> iter = roomInfos.iterator();

    // 1.
    assertTrue(iter.hasNext());
    {
      RoomInfo roomInfo = iter.next();
      // assertEquals("m6_0000_single1.jpg", roomInfo.roomPhotoPath);
      assertEquals("43.99USD", roomInfo.rate);
      assertEquals(
          "32\" LCD TV WITH AV CONNECTIONS FOR GAMING, WOOD-EFFECT FLOORS, BATHROOM WITH GRANITE COUNTERTOPS AND A RAISED WASH BASIN.",
          roomInfo.description);
      assertEquals("1 QUEEN BED |", roomInfo.amenities);
    }

    // 2.
    assertTrue(iter.hasNext());
    {
      RoomInfo roomInfo = iter.next();
      // assertEquals("m6_0000_double2.jpg", roomInfo.roomPhotoPath);
      assertEquals("43.99USD", roomInfo.rate);
      assertEquals(
          "32\" LCD TV WITH AV CONNECTIONS FOR GAMING, WOOD-EFFECT FLOORS, BATHROOM WITH GRANITE COUNTERTOPS AND A RAISED WASH BASIN.",
          roomInfo.description);
      assertEquals("2 FULL BEDS |", roomInfo.amenities);
    }

    // 3.
    assertTrue(iter.hasNext());
    {
      RoomInfo roomInfo = iter.next();
      // assertEquals("m6_0000_double2.jpg", roomInfo.roomPhotoPath);
      assertEquals("43.99USD", roomInfo.rate);
      assertEquals(
          "32\" LCD TV WITH AV CONNECTIONS FOR GAMING, WOOD-EFFECT FLOORS, BATHROOM WITH GRANITE COUNTERTOPS AND A RAISED WASH BASIN.",
          roomInfo.description);
      assertEquals("1 FULL BED | ADA ACCESSIBLE", roomInfo.amenities);
    }
  }
Esempio n. 5
0
 public static void parse(
     XMLInputFactory xmlInputFactory,
     Path source,
     FullyQualifiedName fileKey,
     FullyQualifiedName.Factory fqnFactory,
     KeyValueConsumer<DataKey, DataResource> overwritingConsumer,
     KeyValueConsumer<DataKey, DataResource> combiningConsumer)
     throws IOException, XMLStreamException {
   ImmutableSet.Builder<String> newIds = ImmutableSet.builder();
   try (BufferedInputStream inStream = new BufferedInputStream(Files.newInputStream(source))) {
     XMLEventReader eventReader =
         xmlInputFactory.createXMLEventReader(inStream, StandardCharsets.UTF_8.toString());
     // Go through every start tag and look at the values of all attributes (the attribute does
     // not need to be android:id, e.g., android:layout_above="@+id/UpcomingView").
     // If the any attribute's value begins with @+id/, then track it, since aapt seems to be
     // forgiving and allow even non-android namespaced attributes to define a new ID.
     while (eventReader.hasNext()) {
       XMLEvent event = eventReader.nextEvent();
       if (event.isStartElement()) {
         StartElement start = event.asStartElement();
         Iterator<Attribute> attributes = XmlResourceValues.iterateAttributesFrom(start);
         while (attributes.hasNext()) {
           Attribute attribute = attributes.next();
           String value = attribute.getValue();
           if (value.startsWith(SdkConstants.NEW_ID_PREFIX)) {
             String idName = value.substring(SdkConstants.NEW_ID_PREFIX.length());
             newIds.add(idName);
           }
         }
       }
     }
     eventReader.close();
   }
   ImmutableSet<String> idResources = newIds.build();
   overwritingConsumer.consume(fileKey, DataValueFile.of(source));
   for (String id : idResources) {
     combiningConsumer.consume(
         fqnFactory.create(ResourceType.ID, id),
         DataResourceXml.createWithNoNamespace(source, IdXmlResourceValue.of()));
   }
 }
  /**
   * This method reads the agent specific configurations for the device from the
   * "deviceConfigs.properties" file found at /repository/conf folder. If the properties file is not
   * found in the specified path, then the configuration values are set to the default ones in the
   * 'AgentConstants' class.
   *
   * @return an object of type 'AgentConfiguration' which contains all the necessary configuration
   *     attributes
   */
  public static AgentConfiguration readIoTServerConfigs() throws AgentCoreOperationException {
    AgentManager agentManager = AgentManager.getInstance();
    AgentConfiguration iotServerConfigs = new AgentConfiguration();
    Properties properties = new Properties();
    InputStream propertiesInputStream = null;
    String propertiesFileName = AgentConstants.AGENT_PROPERTIES_FILE_NAME;

    try {
      ClassLoader loader = AgentUtilOperations.class.getClassLoader();
      URL path = loader.getResource(propertiesFileName);
      System.out.println(path);
      String root =
          path.getPath()
              .replace("wso2-firealarm-virtual-agent.jar!/deviceConfig.properties", "")
              .replace("jar:", "")
              .replace("file:", "");

      root = URLDecoder.decode(root, StandardCharsets.UTF_8.toString());
      agentManager.setRootPath(root);

      String deviceConfigFilePath = root + AgentConstants.AGENT_PROPERTIES_FILE_NAME;
      propertiesInputStream = new FileInputStream(deviceConfigFilePath);

      // load a properties file from class path, inside static method
      properties.load(propertiesInputStream);

      iotServerConfigs.setTenantDomain(properties.getProperty(AgentConstants.TENANT_DOMAIN));
      iotServerConfigs.setDeviceOwner(properties.getProperty(AgentConstants.DEVICE_OWNER_PROPERTY));
      iotServerConfigs.setDeviceId(properties.getProperty(AgentConstants.DEVICE_ID_PROPERTY));
      iotServerConfigs.setDeviceName(properties.getProperty(AgentConstants.DEVICE_NAME_PROPERTY));
      iotServerConfigs.setControllerContext(
          properties.getProperty(AgentConstants.DEVICE_CONTROLLER_CONTEXT_PROPERTY));
      iotServerConfigs.setScepContext(
          properties.getProperty(AgentConstants.DEVICE_SCEP_CONTEXT_PROPERTY));
      iotServerConfigs.setHTTPS_ServerEndpoint(
          properties.getProperty(AgentConstants.SERVER_HTTPS_EP_PROPERTY));
      iotServerConfigs.setHTTP_ServerEndpoint(
          properties.getProperty(AgentConstants.SERVER_HTTP_EP_PROPERTY));
      iotServerConfigs.setApimGatewayEndpoint(
          properties.getProperty(AgentConstants.APIM_GATEWAY_EP_PROPERTY));
      iotServerConfigs.setMqttBrokerEndpoint(
          properties.getProperty(AgentConstants.MQTT_BROKER_EP_PROPERTY));
      iotServerConfigs.setXmppServerEndpoint(
          properties.getProperty(AgentConstants.XMPP_SERVER_EP_PROPERTY));
      iotServerConfigs.setXmppServerName(
          properties.getProperty(AgentConstants.XMPP_SERVER_NAME_PROPERTY));
      iotServerConfigs.setAuthMethod(properties.getProperty(AgentConstants.AUTH_METHOD_PROPERTY));
      iotServerConfigs.setAuthToken(properties.getProperty(AgentConstants.AUTH_TOKEN_PROPERTY));
      iotServerConfigs.setRefreshToken(
          properties.getProperty(AgentConstants.REFRESH_TOKEN_PROPERTY));
      iotServerConfigs.setDataPushInterval(
          Integer.parseInt(properties.getProperty(AgentConstants.PUSH_INTERVAL_PROPERTY)));

      log.info(
          AgentConstants.LOG_APPENDER + "Tenant Domain: " + iotServerConfigs.getTenantDomain());
      log.info(AgentConstants.LOG_APPENDER + "Device Owner: " + iotServerConfigs.getDeviceOwner());
      log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId());
      log.info(AgentConstants.LOG_APPENDER + "Device Name: " + iotServerConfigs.getDeviceName());
      log.info(
          AgentConstants.LOG_APPENDER
              + "Device Controller Context: "
              + iotServerConfigs.getControllerContext());
      log.info(
          AgentConstants.LOG_APPENDER
              + "IoT Server HTTPS EndPoint: "
              + iotServerConfigs.getHTTPS_ServerEndpoint());
      log.info(
          AgentConstants.LOG_APPENDER
              + "IoT Server HTTP EndPoint: "
              + iotServerConfigs.getHTTP_ServerEndpoint());
      log.info(
          AgentConstants.LOG_APPENDER
              + "API-Manager Gateway EndPoint: "
              + iotServerConfigs.getApimGatewayEndpoint());
      log.info(
          AgentConstants.LOG_APPENDER
              + "MQTT Broker EndPoint: "
              + iotServerConfigs.getMqttBrokerEndpoint());
      log.info(
          AgentConstants.LOG_APPENDER
              + "XMPP Server EndPoint: "
              + iotServerConfigs.getXmppServerEndpoint());
      log.info(
          AgentConstants.LOG_APPENDER
              + "Authentication Method: "
              + iotServerConfigs.getAuthMethod());
      log.info(
          AgentConstants.LOG_APPENDER + "Authentication Token: " + iotServerConfigs.getAuthToken());
      log.info(
          AgentConstants.LOG_APPENDER + "Refresh Token: " + iotServerConfigs.getRefreshToken());
      log.info(
          AgentConstants.LOG_APPENDER
              + "Data Push Interval: "
              + iotServerConfigs.getDataPushInterval());
      log.info(
          AgentConstants.LOG_APPENDER
              + "XMPP Server Name: "
              + iotServerConfigs.getXmppServerName());

    } catch (FileNotFoundException ex) {
      String errorMsg =
          "[" + propertiesFileName + "] file not found at: " + AgentConstants.PROPERTIES_FILE_PATH;
      log.error(AgentConstants.LOG_APPENDER + errorMsg);
      throw new AgentCoreOperationException(errorMsg);

    } catch (IOException ex) {
      String errorMsg =
          "Error occurred whilst trying to fetch ["
              + propertiesFileName
              + "] from: "
              + AgentConstants.PROPERTIES_FILE_PATH;
      log.error(AgentConstants.LOG_APPENDER + errorMsg);
      throw new AgentCoreOperationException(errorMsg);
    } finally {
      if (propertiesInputStream != null) {
        try {
          propertiesInputStream.close();
        } catch (IOException e) {
          log.error(
              AgentConstants.LOG_APPENDER
                  + "Error occurred whilst trying to close InputStream resource used to read the '"
                  + propertiesFileName
                  + "' file");
        }
      }
    }
    return iotServerConfigs;
  }
Esempio n. 7
0
 public BuildCSSTask() {
   setDefaultCharacterEncoding(StandardCharsets.UTF_8.toString());
   setDirNames("/");
   setMain("com.liferay.css.builder.CSSBuilder");
 }