Ejemplo n.º 1
0
  @Test
  public void should_return_notFound_if_attempt_doesnt_exist() {

    final String uri = String.format(URI, "type", "key");

    Response response = invoke(uri).get();
    assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());

    JsonObject token1 = response.readEntity(JsonObject.class);
    JsonArray jsonArray = token1.getJsonObject("errors").getJsonArray("messages");

    for (int i = 0; jsonArray.size() > i; i++) {
      JsonObject item = jsonArray.getJsonObject(i);

      assertEquals(
          NotFoundEnum.ATTEMPT.getCode().longValue(), item.getJsonNumber("code").longValue());
      assertNull(item.getJsonString("field"));
      assertEquals("attempt_not_found", item.getJsonString("message").getString());
    }
  }
Ejemplo n.º 2
0
  ObservableList<Question> getObservableList() throws IOException {
    String url = "http://api.stackexchange.com/2.2/search?tagged=javafx&site=stackoverflow";
    URL host = new URL(url);
    JsonReader jr = Json.createReader(new GZIPInputStream(host.openConnection().getInputStream()));

    JsonObject jsonObject = jr.readObject();
    JsonArray jsonArray = jsonObject.getJsonArray("items");
    ObservableList<Question> answer = FXCollections.observableArrayList();

    jsonArray
        .iterator()
        .forEachRemaining(
            (JsonValue e) -> {
              JsonObject obj = (JsonObject) e;
              JsonString name = obj.getJsonObject("owner").getJsonString("display_name");
              JsonString quest = obj.getJsonString("title");
              JsonNumber jsonNumber = obj.getJsonNumber("creation_date");
              Question q =
                  new Question(name.getString(), quest.getString(), jsonNumber.longValue() * 1000);
              answer.add(q);
            });
    return answer;
  }
  /**
   * This methods print outs public profile informations of given user sets the plusProfile with all
   * those information. getPlusProfile() can be used to get the information.
   *
   * @param userName : user name of a Google plus user to crawl the public profile informations.
   * @return no return value
   */
  public void startCrawling(String userName) {
    try {

      InputStream is =
          new URL("https://www.googleapis.com/plus/v1/people/" + userName + "?key=" + API_KEY)
              .openStream();

      JsonReader rdr = Json.createReader(is);
      JsonObject obj = rdr.readObject();

      // retrieve user's profile information

      System.out.println("\nGoogle+ Profile crawler started...\n");
      System.out.println("____________________________________");
      System.out.println("         Profile");
      System.out.println("====================================");
      String displayName = obj.getJsonString("displayName").getString();
      System.out.println("Name: " + displayName);
      getPlusProfile().setName(displayName);

      String user_id = obj.getJsonString("id").getString();
      System.out.println("ID: " + user_id);
      // getPlusProfile().setUserId(user_id);//number format user id
      getPlusProfile().setUserId(userName);

      if (obj.containsKey("gender")) {
        String gender = obj.getJsonString("gender").getString();
        System.out.println("Gender: " + gender);
        getPlusProfile().setGender(gender);
      } else {
        System.out.println("Gender: " + "");
        getPlusProfile().setGender("");
      }

      getPlusProfile().setDateOfBirth("");
      JsonString occupationJson = obj.getJsonString("occupation");
      if (occupationJson != null) {
        String occupation = obj.getJsonString("occupation").getString();
        System.out.println("Occupation: " + occupation);
      }

      // retrieve user's work and education information
      JsonArray results = obj.getJsonArray("placesLived");
      if (results != null) {
        System.out.println("____________________________________");
        System.out.println("         Locations Lived");
        System.out.println("====================================");
        int i = 0;
        for (JsonObject result : results.getValuesAs(JsonObject.class)) {
          String location = result.getString("value");
          System.out.println(location);
          if (i == 0) getPlusProfile().setCurrentLocation(location);
          else getPlusProfile().setHomeLocation(location);

          i++;
        }
        if (i == 1) getPlusProfile().setHomeLocation(getPlusProfile().getCurrentLocation());

      } else {
        System.out.println("Location info NOT AVAILABLE");
        getPlusProfile().setCurrentLocation("");
        getPlusProfile().setHomeLocation("");
      }

      // retrieve user's work and education information
      Set<String> wrkEdu = new TreeSet<String>();
      results = obj.getJsonArray("organizations");
      if (results != null) {
        System.out.println("____________________________________");
        System.out.println("         Work and Education");
        System.out.println("====================================");
        for (JsonObject result : results.getValuesAs(JsonObject.class)) {

          if (result.containsKey("name")) {
            String workEdu = result.getString("name");
            System.out.println(workEdu);
          } else {
            wrkEdu.add("");
            System.out.println("Company name NOT AVAILABLE");
          }
        }

        getPlusProfile().setEmployer(wrkEdu);
        getPlusProfile().setEducation(wrkEdu);
      } else {
        System.out.println("Work and Education info NOT AVAILABLE");
        getPlusProfile().setEmployer(wrkEdu);
        getPlusProfile().setEducation(wrkEdu);
      }
      List<String> languages = new ArrayList<String>();
      getPlusProfile().setLanguages(languages);

      firefoxDriver = new FirefoxDriver();
      firefoxDriver.get("https://plus.google.com/" + userName + "/about");
      Thread.sleep(3000);

      // get list of circles
      List<WebElement> circle = firefoxDriver.findElements(By.className("bkb"));
      Set<String> circles = new TreeSet<String>();

      if (circle.size() != 0) {
        String circleText = circle.get(0).getText();
        System.out.println(circleText);
        String circleCountstr = circleText.split("\\s+")[0];
        if (circleCountstr.contains(",")) {
          circleCountstr = circleCountstr.replace(",", "");
        }
        int circleCount = Integer.parseInt(circleCountstr);
        System.out.println("Circle Count:" + circleCount);

        WebElement circleLink =
            firefoxDriver.findElement(By.xpath("//span[contains(text(),'" + circleText + "')]"));
        circleLink.click();
        Thread.sleep(3000);

        WebElement friendListBox = firefoxDriver.findElement(By.className("G-q-B"));

        Robot robot = new Robot();

        int loop = 0;
        while (loop < circleCount / 10) {
          if (circles.size() == circleCount) break;

          Thread.sleep(3000);

          List<WebElement> friendList = friendListBox.findElements(By.tagName("a"));

          for (WebElement friend : friendList) {
            System.out.println(friend.getText());
            circles.add(friend.getText());
          }

          int count = 0;
          while (count < 500) {
            robot.keyPress(java.awt.event.KeyEvent.VK_DOWN);
            count++;
          }

          loop++;
        }
      }
      List<String> friends = new ArrayList<String>();
      for (String friend : circles) {
        friends.add(friend);
      }
      getPlusProfile().setFriends(friends);

      System.out.println(
          "_________________________________________________________________________________________");

      System.out.println("Finish Crawling...");
      closePlusWebDriverNode();

    } catch (AWTException ex) {
      System.out.println("Problem in key press:" + ex);
    } catch (IOException ex) {
      System.out.println(ex);
    } catch (InterruptedException ex) {
      System.out.println();
    }
  }
  public void logController(String topic, MqttMessage mqttMessage) {
    // get deviceId
    String[] split = topic.split("log/");
    String deviceId = split[1];

    // parse log
    try {
      JsonReader reader = Json.createReader(new StringReader(mqttMessage.toString()));
      JsonObject jsonMessage = reader.readObject();
      String logType = jsonMessage.getString("type");
      switch (logType) {
        case LOG_NORMAL:
          int temperature = 0;
          int timer = jsonMessage.getInt("time");
          try {
            temperature = jsonMessage.getInt("temperature");
          } catch (Exception se1) {
            // @todo: warning
            break;
          }
          JsonString subDeviceId = jsonMessage.getJsonString("subId");
          if (subDeviceId == null) sessionHandle.drawTemperature(deviceId, timer, temperature);
          else sessionHandle.drawTemperature(deviceId, timer, temperature, subDeviceId.toString());
          break;
        case LOG_WARNING:
          timer = jsonMessage.getInt("time");
          subDeviceId = jsonMessage.getJsonString("subId");
          int subdeviceNo = jsonMessage.getInt("number");
          String deviceState = jsonMessage.getString("value");
          String msg;
          switch (subdeviceNo) {
            case 1:
              msg = ("0".equals(deviceState)) ? "Button release" : "Button clicked";
              break;
            case 2:
              msg = ("0".equals(deviceState)) ? "Cửa cuốn được cuộn lên" : "Đang thả cửa cuốn";
              break;
            default:
              msg = DEFAULT_ALERT_MSG;
              break;
          }
          if (subDeviceId == null) sessionHandle.doAlert(deviceId, timer, msg);
          else sessionHandle.doAlert(deviceId, timer, msg, subDeviceId.toString());
          break;
        case LOG_CONTROL:
          String state = jsonMessage.getString("light");
          subdeviceNo = jsonMessage.getInt("no");
          sessionHandle.updateLightState(deviceId, subdeviceNo, state);
          break;
        case LOG_ACK:
          subdeviceNo = jsonMessage.getInt("number");
          deviceState = jsonMessage.getString("value");
          state = ("0".equals(deviceState)) ? "off" : "on";
          sessionHandle.ackLightState(deviceId, subdeviceNo, state);
          break;
        case LOG_DEVICE_STATUS:
          JsonArray lstDevice = jsonMessage.getJsonArray("status");
          System.out.println("Update status:");
          for (int i = 0; i < lstDevice.size(); i++) {
            JsonObject device = (JsonObject) lstDevice.get(i);
            System.out.println(device.toString());
            subdeviceNo = device.getInt("no");
            int intState = device.getInt("value");
            state = (intState == 0) ? "off" : "on";
            sessionHandle.updateLightState(deviceId, subdeviceNo, state);
          }
          sessionHandle.finishUpdateDeviceStatus();
          break;
        default:
      }

    } catch (Exception ex) {
      System.out.println("Parse error");
      System.out.println(topic);
      System.out.println(mqttMessage);
      System.out.println(ex.getMessage());
    }
  }
  private static boolean loadATMSwitchConfig(String connId) throws Exception {

    InputStream is = null;
    boolean isLoadedFlag = false;
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    is = classLoader.getResource(atmSwitchConfigFileName).openStream();

    if (is == null) {
      throw new Exception("Unable to load config file - " + atmSwitchConfigFileName);
    }

    try {
      JsonReader jsonReader = Json.createReader(is);
      JsonObject allConfigs = jsonReader.readObject();
      JsonString logFileLocation = allConfigs.getJsonString(logFileLocationKey);
      if (logFileLocation == null) {
        throw new Exception(logFileLocationKey + " parameter missing in the configuration....");
      }
      if ("".equals(connId))
        logger =
            (new AsynchLogger(logFileLocation.toString() + "/ISOSysLog", Level.INFO))
                .getLogger("ISOSysLog");

      JsonArray serverConfigs = allConfigs.getJsonArray(serverConfigKey);
      if (serverConfigs == null) {
        throw new Exception(
            serverConfigKey + " parameter missing. No server Configurations specified....");
      }
      logger.info("Initializing ATM Switch Configuration....");

      if (manifestAttrs != null && "".equals(connId)) {

        logger.info(
            "Build version "
                + manifestAttrs.getValue("Implementation-Version")
                + " Build Date "
                + manifestAttrs.getValue("Build-Time"));
      }

      for (int i = 0; i < serverConfigs.size(); i++) {

        JsonObject serverConfig = serverConfigs.getJsonObject(i);
        JsonString host = serverConfig.getJsonString(serverHostKey);
        JsonNumber port = serverConfig.getJsonNumber(portKey);
        JsonNumber connTimeOut = serverConfig.getJsonNumber(connTimeOutKey);
        JsonNumber readTimeOut = serverConfig.getJsonNumber(readTimeOutKey);
        JsonNumber retry = serverConfig.getJsonNumber(retryKey);
        JsonNumber threadTimeOut = serverConfig.getJsonNumber(threadTimeOutKey);
        JsonString logLevelJson = serverConfig.getJsonString(loglevelKey);
        JsonNumber echoTimeInterval = serverConfig.getJsonNumber(echoTimeIntervalKey);
        JsonString uidFormat = serverConfig.getJsonString("uidFormat");

        if (host == null || port == null) {
          logger.error(
              serverConfig
                  + " Bad configuration for connection ( Host OR Port is missing ). Not Loading this connection....");
          continue;
        }
        if (uidFormat == null) {
          logger.error(
              serverConfig
                  + " Bad configuration for connection ( uidFormat is missing ). Not Loading this connection....");
          continue;
        }

        Level level = null;
        if (logLevelJson == null) {
          level = Level.INFO;
        } else {
          String logLevel = logLevelJson.getString();
          if (logLevel.equalsIgnoreCase("TRACE")) {
            level = Level.TRACE;
          } else if (logLevel.equalsIgnoreCase("DEBUG")) {
            level = Level.DEBUG;
          } else {
            level = Level.INFO;
          }
        }
        MessageUIDGenerator messageUIDGenerator =
            MessageUIDGeneratorFactory.getMessageUIDGenerator(uidFormat.toString());
        if (!"".equals(connId)) {
          if (!connId.equalsIgnoreCase(host.getString() + "_" + port.intValue())) {
            continue;
          }
        }
        ATMSwitchTCPHandler.manualStopPool.put(
            host.getString() + "_" + String.valueOf(port.intValue()), Boolean.FALSE);
        ConnectionBean bean =
            new ConnectionBean(
                host.getString(),
                port.intValue(),
                (connTimeOut == null ? 8000 : connTimeOut.intValue()),
                (readTimeOut == null ? 8000 : readTimeOut.intValue()),
                (threadTimeOut == null ? 5000 : threadTimeOut.intValue()),
                (retry == null ? 3 : retry.intValue()),
                (echoTimeInterval == null ? 0 : echoTimeInterval.intValue()));

        ServerContainer container =
            new ServerContainer(bean, logFileLocation.getString(), level, messageUIDGenerator);
        try {
          if (container.connect(false)) {
            logger.info(bean.toString() + " Loaded....");
            isLoadedFlag = true;
          } else {
            logger.warn(bean.toString() + " could not be loaded....");
          }
        } catch (InterruptedException e) {
          logger.error(
              "( "
                  + bean.getUniqueName()
                  + " ,loadAllClientConnection(, ,) ) Interrupted Exception",
              e);
        } catch (ExecutionException e) {
          logger.error(
              "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) ExecutionException",
              e);
        } catch (IOException e) {
          logger.error(
              "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) IOException", e);
        } catch (Exception e) {
          logger.error(
              "( " + bean.getUniqueName() + " ,loadAllClientConnection(, ,) ) Exception", e);
        }
      }

    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          logger.error("IOException in closing the stream for JSON config property file....", e);
        }
      }
    }
    return isLoadedFlag;
  }