Ejemplo n.º 1
0
  public static DocumentListEntry executePost(
      HttpRequestFactory requestFactory, DocsUrl url, AtomContent content) throws IOException {

    HttpRequest request = requestFactory.buildPostRequest(url, content);
    HttpResponse response = requestExecutor.executeSensitive(request);
    return response.parseAs(DocumentListEntry.class);
  }
  private Entry uploadLastChunk(
      byte[] bytes,
      int position,
      int length,
      String fileType,
      HttpRequestFactory requestFactory,
      long size,
      String location) {

    try {

      HttpResponse response =
          putRequest(bytes, position, length, fileType, requestFactory, size, location);
      if (!response.isSuccessStatusCode()) {
        String message =
            "upload finished, but there was an error during upload, "
                + response.getStatusCode()
                + ": "
                + response.getStatusMessage();
        logger.error(message);
        throw new CoreException(message);
      }

      return response.parseAs(Entry.class);
    } catch (IOException e) {
      String message = "unable to parse response " + e.getMessage();
      logger.error(message);
      throw new CoreException(message);
    }
  }
Ejemplo n.º 3
0
  public static Entry executeGet(
      HttpRequestFactory requestFactory, DocsUrl url, Class<Entry> feedClass) throws IOException {

    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse response = requestExecutor.executeNonSensitive(request);
    return response.parseAs(feedClass);
  }
Ejemplo n.º 4
0
  public static InputStream executeGetContent(HttpRequestFactory requestFactory, DocsUrl url)
      throws IOException {

    HttpRequest request = requestFactory.buildGetRequest(url);
    HttpResponse response = requestExecutor.executeNonSensitive(request);
    return response.getContent();
  }
Ejemplo n.º 5
0
  public static UserInfo build(String accessToken, String refreshToken) throws IOException {
    GoogleAccessProtectedResource access =
        new GoogleAccessProtectedResource(
            accessToken,
            ConstFunc.TRANSPORT,
            ConstFunc.JSON_FACTORY,
            ConstFunc.CLIENT_ID,
            ConstFunc.CLIENT_SECRET,
            refreshToken);
    HttpRequestFactory rf = ConstFunc.TRANSPORT.createRequestFactory(access);

    GenericUrl userInfoUrl =
        new GenericUrl("https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + accessToken);

    HttpRequest request = rf.buildGetRequest(userInfoUrl);
    HttpResponse response = request.execute();

    InputStream is = response.getContent();
    Reader isr = new InputStreamReader(is, "UTF-8");

    Gson gson = new Gson();
    UserInfo ui = gson.fromJson(isr, UserInfo.class);

    ui.setAccess_token(accessToken);
    ui.setRefresh_token(refreshToken);

    return ui;
  }
  private String getFileContents(Drive drive, String downloadUrl) {
    if (!TextUtils.isEmpty(downloadUrl)) {
      try {
        HttpResponse resp =
            drive.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl)).execute();

        final char[] buffer = new char[1024];
        final StringBuilder out = new StringBuilder();
        Reader in = null;
        try {
          in = new InputStreamReader(resp.getContent(), "UTF-8");
          for (; ; ) {
            int rsz = in.read(buffer, 0, buffer.length);
            if (rsz < 0) break;
            out.append(buffer, 0, rsz);
          }
        } finally {
          in.close();
        }
        return out.toString();
      } catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Error downloading file contenst", e);
      }
    }
    return null;
  }
Ejemplo n.º 7
0
 public static void executeDelete(
     HttpRequestFactory requestFactory, DocsUrl url, String etag, boolean matchAll)
     throws IOException {
   HttpRequest request = requestFactory.buildDeleteRequest(url);
   if (matchAll) request.getHeaders().setIfMatch("*");
   else request.getHeaders().setIfMatch(etag);
   HttpResponse response = requestExecutor.executeNonSensitive(request);
   response.ignore();
 }
Ejemplo n.º 8
0
  public boolean updateMobileDevice(
      String serialNumber,
      String deviceName,
      String assetTag,
      String building,
      String room,
      String department) {
    boolean success = false;
    MobileDeviceMatch match = findMobileDevice(serialNumber);
    if (match != null) {
      // TODO: urlencode string
      String id = match.id;
      MobileDevice device = getMobileDevice(id);
      if (device != null) {
        String updateUrlString = jssServerUrl + MOBILE_DEVICES_API_PATH + "/id/" + id;
        GenericUrl updateUrl = new GenericUrl(updateUrlString);
        int status = 500;
        try {
          device.general.deviceName = deviceName;
          device.general.assetTag = assetTag;

          if (building != null && !building.isEmpty()) {
            device.location.building = building;
          }
          if (room != null && !room.isEmpty()) {
            device.location.room = room;
          }
          if (department != null && !department.isEmpty()) {
            device.location.department = department;
          }

          XmlHttpContent content = new XmlHttpContent(nsdict, "mobile_device", device);
          if (debug) {
            OutputStream out = new ByteArrayOutputStream();
            content.writeTo(out);
            System.out.println("content " + out.toString());
          }

          // JSS REST API - use PUT method to update existing object
          HttpRequest updateRequest = factory.buildPutRequest(updateUrl, content);
          HttpResponse updateResponse = updateRequest.execute();
          status = updateResponse.getStatusCode();
          if (status < 400) {
            success = true;
          }
        } catch (Exception ex1) {
          System.out.println("Exception! " + ex1.getMessage());
        }
        if (debug) {
          System.out.println("update " + id + ", status " + String.valueOf(status));
        }
      }
    }
    return success;
  }
Ejemplo n.º 9
0
 public String shortUrl(String long_url) {
   GenericData data = new GenericData();
   data.put("longUrl", long_url);
   JsonHttpContent content = new JsonHttpContent();
   content.data = data;
   request.content = content;
   HttpResponse response;
   try {
     response = request.execute();
     Result result = response.parseAs(Result.class);
     return result.shortUrl;
   } catch (IOException e) {
     return null;
   }
 }
Ejemplo n.º 10
0
  public void handleException(Exception e) {
    Log.e("handleException", "not good");

    e.printStackTrace();
    if (e instanceof HttpResponseException) {
      HttpResponse response = ((HttpResponseException) e).getResponse();
      int statusCode = response.getStatusCode();
      try {
        response.ignore();
      } catch (IOException e1) {
        e1.printStackTrace();
      }
      if (statusCode == 401) {
        loadAccount(true);
        return;
      }
    }
  }
Ejemplo n.º 11
0
  public MobileDeviceMatch findMobileDevice(String serialNumber) {
    // TODO: urlencode string
    String matchUrlString = jssServerUrl + MOBILE_DEVICES_API_PATH + "/match/" + serialNumber;
    GenericUrl matchUrl = new GenericUrl(matchUrlString);
    int status = 500;
    try {
      // JSS REST API - use GET method to query existing objects
      // (read-only)
      HttpRequest matchRequest = factory.buildGetRequest(matchUrl);
      HttpResponse matchResponse = matchRequest.execute();
      status = matchResponse.getStatusCode();
      if (status < 400) {
        MobileDeviceList mobileDevices = matchResponse.parseAs(MobileDeviceList.class);
        if (mobileDevices.size == 1) {
          MobileDeviceMatch device = mobileDevices.first();
          if (debug) {
            System.out.println(
                "match "
                    + serialNumber
                    + ", status "
                    + String.valueOf(status)
                    + ", id "
                    + device.id);
          }
          if (device.id != null && !device.id.isEmpty()) {
            return device;
          }
        } else if (debug) {
          System.out.println(
              "match " + serialNumber + ", got " + String.valueOf(mobileDevices.size) + " devices");
        }
      }
    } catch (IndexOutOfBoundsException ex0) {
      System.out.println("Didn't parse any devices. ");
    } catch (Exception ex1) {
      System.out.println("Exception! " + ex1.getMessage());
    }

    if (debug) {
      // Not found or internal error
      System.out.println("match " + serialNumber + ", status " + String.valueOf(status));
    }
    return null;
  }
  @Override
  public GameState call() throws Exception {
    HttpContent content;
    HttpRequest request;
    HttpResponse response;
    GameState gameState = null;
    AdvancedGameState advancedGameState;

    try {
      // Initial request
      logger.info("Sending initial request...");
      content = new UrlEncodedContent(apiKey);
      request = REQUEST_FACTORY.buildPostRequest(gameUrl, content);
      request.setReadTimeout(0); // Wait forever to be assigned to a game
      response = request.execute();
      gameState = response.parseAs(GameState.class);
      logger.info("Game URL: {}", gameState.getViewUrl());

      advancedGameState = new AdvancedGameState(gameState);

      // Game loop
      while (!gameState.getGame().isFinished() && !gameState.getHero().isCrashed()) {
        logger.info("Taking turn " + gameState.getGame().getTurn());
        BotMove direction = bot.move(advancedGameState);
        Move move = new Move(apiKey.getKey(), direction.toString());

        HttpContent turn = new UrlEncodedContent(move);
        HttpRequest turnRequest =
            REQUEST_FACTORY.buildPostRequest(new GenericUrl(gameState.getPlayUrl()), turn);
        HttpResponse turnResponse = turnRequest.execute();

        gameState = turnResponse.parseAs(GameState.class);
        advancedGameState = new AdvancedGameState(advancedGameState, gameState);
      }

    } catch (Exception e) {
      logger.error("Error during game play", e);
    }

    logger.info("Game over");
    return gameState;
  }
Ejemplo n.º 13
0
  @Test
  public void test() throws IOException {

    HttpTransport transport = injector.getInstance(HttpTransport.class);
    JsonFactory jsonFactory = injector.getInstance(JsonFactory.class);

    DriveManager drive =
        new DriveManager(
            transport, jsonFactory, GoogleOAuth2.getGlobalCredential(transport, jsonFactory));
    Drive service = drive.getClient();
    File file = service.files().get("1HyyFJfqms_ZII3kNHr9smIXFadMYNRQvXsOhLOsUhLg").execute();
    //		IOUtils.toString(downloadFile(service, file));
    String downloadUrl = file.getExportLinks().get("text/html");
    System.out.println(downloadUrl);

    HttpRequestFactory factory = transport.createRequestFactory();
    HttpRequest request = factory.buildGetRequest(new GenericUrl(downloadUrl));
    HttpResponse response = request.execute();
    System.out.println(IOUtils.toString(response.getContent()));
  }
Ejemplo n.º 14
0
  public MobileDevice getMobileDevice(String id) {
    String getUrlString = jssServerUrl + MOBILE_DEVICES_API_PATH + "/id/" + id;
    GenericUrl getUrl = new GenericUrl(getUrlString);
    int status = 500;
    try {
      // JSS REST API - use GET method to query existing objects
      // (read-only)
      HttpRequest getRequest = factory.buildGetRequest(getUrl);
      HttpResponse getResponse = getRequest.execute();
      status = getResponse.getStatusCode();
      if (status < 400) {
        MobileDevice device = getResponse.parseAs(MobileDevice.class);
        if (device != null) {
          return device;
        }
      }
    } catch (Exception ex1) {
      System.out.println("Exception! " + ex1.getMessage());
    }

    return null;
  }
Ejemplo n.º 15
0
  /**
   * Retrieve a Google Drive file's content.
   *
   * @param driveFile Google Drive file to retrieve content from.
   * @return Google Drive file's content if successful, {@code null} otherwise.
   */
  public String getFileContent(File driveFile) {
    String result = "";

    if (driveFile.getDownloadUrl() != null && driveFile.getDownloadUrl().length() > 0) {
      try {
        GenericUrl downloadUrl = new GenericUrl(driveFile.getDownloadUrl());

        HttpResponse resp = mService.getRequestFactory().buildGetRequest(downloadUrl).execute();
        InputStream inputStream = null;

        try {
          inputStream = resp.getContent();
          BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
          StringBuilder content = new StringBuilder();
          char[] buffer = new char[1024];
          int num;

          while ((num = reader.read(buffer)) > 0) {
            content.append(buffer, 0, num);
          }
          result = content.toString();
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
        }
      } catch (IOException e) {
        // An error occurred.
        e.printStackTrace();
        return null;
      }
    } else {
      // The file doesn't have any content stored on Drive.
      return null;
    }

    return result;
  }
Ejemplo n.º 16
0
  @Override
  protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
      throws IOException {

    try {
      AppIdentityCredential credential = new AppIdentityCredential(Arrays.asList(STORAGE_SCOPE));

      // Set up and execute Google Cloud Storage request.
      String bucketName = req.getRequestURI();
      if (bucketName.equals("/")) {
        resp.sendError(
            HTTP_NOT_FOUND, "No bucket specified - append /bucket-name to the URL and retry.");
        return;
      }
      // Remove any trailing slashes, if found.
      // [START snippet]
      String cleanBucketName = bucketName.replaceAll("/$", "");
      String uri = GCS_URI + cleanBucketName;
      HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(credential);
      GenericUrl url = new GenericUrl(uri);
      HttpRequest request = requestFactory.buildGetRequest(url);
      HttpResponse response = request.execute();
      String content = response.parseAsString();
      // [END snippet]

      // Display the output XML.
      resp.setContentType("text/xml");
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));
      String formattedContent = content.replaceAll("(<ListBucketResult)", XSL + "$1");
      writer.append(formattedContent);
      writer.flush();
      resp.setStatus(HTTP_OK);
    } catch (Throwable e) {
      resp.sendError(HTTP_NOT_FOUND, e.getMessage());
    }
  }
  protected InputStream getContentStream(String downloadURL) throws PortalException {

    if (Validator.isNull(downloadURL)) {
      return null;
    }

    Drive drive = getDrive();

    HttpRequestFactory httpRequestFactory = drive.getRequestFactory();

    GenericUrl genericUrl = new GenericUrl(downloadURL);

    try {
      HttpRequest httpRequest = httpRequestFactory.buildGetRequest(genericUrl);

      HttpResponse httpResponse = httpRequest.execute();

      return httpResponse.getContent();
    } catch (IOException ioe) {
      _log.error(ioe, ioe);

      throw new SystemException(ioe);
    }
  }
Ejemplo n.º 18
0
  /**
   * * Display an HTTP response header information.
   *
   * @param response The response whose information must be displayed.
   */
  public static void displayResponseHeaders(HttpResponse response) {

    HttpHeaders headers = response.getHeaders();

    // Get the file list iterator.
    Iterator<Entry<String, Object>> iterator = headers.entrySet().iterator();

    System.out.println(
        String.format("%n================== " + "Response Headers" + " ================== %n"));

    while (iterator.hasNext()) {
      Entry<String, Object> entry = iterator.next();
      String key = entry.getKey();
      String value = entry.getValue().toString();
      System.out.println(String.format("Key: %s Value: %s", key, value));
    }
  }
 private BufferedReader printMemberDetails(PrintWriter writer, HttpResponse v1response)
     throws IOException, FactoryConfigurationError {
   BufferedReader in = new BufferedReader(new InputStreamReader(v1response.getContent()));
   try {
     XMLInputFactory inputFactory = XMLInputFactory.newInstance();
     XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
     while (eventReader.hasNext()) {
       XMLEvent event = eventReader.nextEvent();
       if (event.isStartElement()) {
         StartElement startElement = event.asStartElement();
         if (startElement.getName().getLocalPart() == ASSETS) {
           writer.println("<h2>" + startElement.getName().getLocalPart() + "</h2>");
           printAttributes(writer, startElement);
         } else if (startElement.getName().getLocalPart() == ASSET) {
           writer.println("<p>" + startElement.getName().getLocalPart() + ":</p>");
           printAttributes(writer, startElement);
         } else if (startElement.getName().getLocalPart() == ATTRIBUTE) {
           Attribute aName = (Attribute) startElement.getAttributes().next();
           event = eventReader.nextEvent();
           if (event.isEndElement()) {
             writer.println("<p>" + aName.getValue().toString() + "</p>");
           } else {
             writer.println(
                 "<p>"
                     + aName.getValue().toString()
                     + "="
                     + event.asCharacters().getData()
                     + "</p>");
           }
         } else if (startElement.getName().getLocalPart() == RELATION) {
           Attribute aName = (Attribute) startElement.getAttributes().next();
           event = eventReader.nextEvent();
           writer.println("<p>" + aName.getValue().toString() + ":</p>");
         }
       }
     }
   } catch (XMLStreamException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return in;
 }
Ejemplo n.º 20
0
  private String initUpload(
      HttpRequestFactory requestFactory,
      DocsUrl url,
      long size,
      String fileType,
      AtomContent fileContent)
      throws IOException {
    HttpRequest request = requestFactory.buildPostRequest(url, fileContent);
    request.getHeaders().set("X-Upload-Content-Type", fileType);
    request.getHeaders().set("X-Upload-Content-Length", size);
    HttpResponse response = requestExecutor.executeNonSensitive(request);

    if (!response.isSuccessStatusCode()) {
      throw new CoreException(
          "unable to initiate upload, "
              + response.getStatusCode()
              + ": "
              + response.getStatusMessage());
    }
    response.ignore();
    return response.getHeaders().getLocation();
  }
  public List<BeanUsuarioDirectorio> BuscarUsuario() {

    String resultado = null;
    List<BeanUsuarioDirectorio> empleadosNuevos = new ArrayList<BeanUsuarioDirectorio>();
    BeanUsuarioDirectorio empleadoNuevo = null;

    try {

      List<String> SCOPES = Arrays.asList("email");

      String emailAddressDev =
          "*****@*****.**";

      JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
      NetHttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
      GoogleCredential credential;

      credential =
          new GoogleCredential.Builder()
              .setTransport(httpTransport)
              .setJsonFactory(JSON_FACTORY)
              .setServiceAccountId(emailAddressDev)
              .setServiceAccountPrivateKey(key)
              .setServiceAccountScopes(SCOPES)
              .setServiceAccountUser("*****@*****.**")
              .build();

      if (listaRegistrosCyge != null) {

        for (BeanCyge registroCyge : listaRegistrosCyge) {
          if ((registroCyge.getEmail() != null)
              && (!registroCyge.getEmail().isEmpty())
              && !registroCyge.getEmail().trim().isEmpty()) {
            /*PRUEBA OFFLINE*/

            try {
              String URI =
                  "https://bbva-gapis.appspot.com/gprofile/users/" + registroCyge.getEmail();
              HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
              GenericUrl url = new GenericUrl(URI);
              HttpRequest request = requestFactory.buildGetRequest(url);
              HttpResponse response = request.execute();
              String content = response.parseAsString();

              resultado = content;
              /*END PRUEBA OFFLINE*/

              // resultado =
              // "{\"code\":\"OK\",\"message\":\"successful\",\"data\":{\"userDefinedFields\":[{\"key\":\"uid\",\"value\":\"MB58756\"},{\"key\":\"descOUPadre\",\"value\":\"SISTEMAS Y OPERACIONES\"},{\"key\":\"codCorporativo\",\"value\":\"00003719381\"},{\"key\":\"descEmpresaExterno\",\"value\":\" \"},{\"key\":\"codCargo\",\"value\":\"IHJ\"},{\"key\":\"descEmpresa\",\"value\":\"BBVA BANCOMER SERVICIO ADMINIS\"},{\"key\":\"codCSB\",\"value\":\"9016\"},{\"key\":\"descOUBase\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel10\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descCentroCoste\",\"value\":\"D Y D CANALES\"},{\"key\":\"uidJefe\",\"value\":\"M901737\"},{\"key\":\"codEstado\",\"value\":\"DF\"},{\"key\":\"codOUNivel10\",\"value\":\"00012899\"},{\"key\":\"codOUPadre\",\"value\":\"00005833\"},{\"key\":\"descpais\",\"value\":\"MÉXICO\"},{\"key\":\"c\",\"value\":\"MEX\"},{\"key\":\"telephoneNumber\",\"value\":\" \"},{\"key\":\"rangoGlobal\",\"value\":\" \"},{\"key\":\"codPostalCentroTrabajo\",\"value\":\"03339\"},{\"key\":\"codBancoOficinaPers\",\"value\":\"01853307\"},{\"key\":\"descCentroTrabajo\",\"value\":\"CENTRO BANCOMER D.F. (CON COME\"},{\"key\":\"descEstado\",\"value\":\"DISTRITO FEDERAL\"},{\"key\":\"mobile\",\"value\":\" \"},{\"key\":\"descLargaPlanta\",\"value\":\"N-6 C-A C-E M-7 E-24\"},{\"key\":\"esEmpleado\",\"value\":\"E\"},{\"key\":\"title\",\"value\":\"LIDER DE PROYECTO DYD A\"},{\"key\":\"o\",\"value\":\"0185\"},{\"key\":\"codCentroCoste\",\"value\":\"0000\"},{\"key\":\"posicion\",\"value\":\"00238344\"},{\"key\":\"pager\",\"value\":\" \"},{\"key\":\"apellido2\",\"value\":\"RAMIREZ\"},{\"key\":\"codCentroTrabajo\",\"value\":\"25001\"},{\"key\":\"descOUNivel2\",\"value\":\"MEXICO\"},{\"key\":\"descOUNivel1\",\"value\":\"MEXICO\"},{\"key\":\"mail\",\"value\":\"[email protected]\"},{\"key\":\"codOficina\",\"value\":\"01853307\"},{\"key\":\"codOUNivel1\",\"value\":\"00000141\"},{\"key\":\"codOUNivel2\",\"value\":\"00000141\"},{\"key\":\"apellido1\",\"value\":\"ROSAS\"},{\"key\":\"codOUNivel3\",\"value\":\"00005833\"},{\"key\":\"descCodPostalCentroTrabajo\",\"value\":\"DF\"},{\"key\":\"descOUNivel9\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel8\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel7\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel6\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel5\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel4\",\"value\":\"TECNOLOGIA MULTICANAL\"},{\"key\":\"descOUNivel3\",\"value\":\"SISTEMAS Y OPERACIONES\"},{\"key\":\"descBancoOficinaPers\",\"value\":\"3307\"},{\"key\":\"corporateNumber\",\"value\":\" \"},{\"key\":\"codOUNivel5\",\"value\":\"00012899\"},{\"key\":\"codOUNivel4\",\"value\":\"00010142\"},{\"key\":\"codOUNivel7\",\"value\":\"00012899\"},{\"key\":\"codOUNivel6\",\"value\":\"00012899\"},{\"key\":\"codOUNivel9\",\"value\":\"00012899\"},{\"key\":\"codOUNivel8\",\"value\":\"00012899\"}],\"id\":\"102286709937216158038\",\"addresses\":[{\"country\":\"MÉXICO\",\"countryCode\":\"ES\",\"formatted\":\"DISTRITO FEDERAL\\n03339\\nMÉXICO\",\"locality\":\"DF\",\"poBox\":\"03339\",\"postalCode\":\"03339\",\"streetAddress\":\"N-6 C-A C-E M-7 E-24\",\"type\":\"work\"}],\"updateTime\":1449889391185,\"customSchemas\":{\"ldapUserData\":{\"uid\":\"MB58756\",\"descOUPadre\":\"SISTEMAS Y OPERACIONES\",\"codCorporativo\":\"00003719381\",\"descEmpresaExterno\":\" \",\"codCargo\":\"IHJ\",\"descEmpresa\":\"BBVA BANCOMER SERVICIO ADMINIS\",\"codCSB\":\"9016\",\"descOUBase\":\"CANALES ATENDIDOS\",\"descOUNivel10\":\"CANALES ATENDIDOS\",\"descCentroCoste\":\"D Y D CANALES\",\"uidJefe\":\"M901737\",\"codEstado\":\"DF\",\"codOUNivel10\":\"00012899\",\"codOUPadre\":\"00005833\",\"descpais\":\"MÉXICO\",\"codPais\":\"MEX\",\"telephoneNumber\":\" \",\"rangoGlobal\":\" \",\"codPostalCentroTrabajo\":\"03339\",\"codBancoOficinaPers\":\"01853307\",\"descCentroTrabajo\":\"CENTRO BANCOMER D.F. (CON COME\",\"descEstado\":\"DISTRITO FEDERAL\",\"mobile\":\" \",\"descLargaPlanta\":\"N-6 C-A C-E M-7 E-24\",\"esEmpleado\":\"E\",\"title\":\"LIDER DE PROYECTO DYD A\",\"organization\":\"0185\",\"codCentroCoste\":\"0000\",\"posicion\":\"00238344\",\"pager\":\" \",\"apellido2\":\"RAMIREZ\",\"codCentroTrabajo\":\"25001\",\"descOUNivel2\":\"MEXICO\",\"descOUNivel1\":\"MEXICO\",\"mail\":\"[email protected]\",\"codOficina\":\"01853307\",\"codOUNivel1\":\"00000141\",\"codOUNivel2\":\"00000141\",\"apellido1\":\"ROSAS\",\"codOUNivel3\":\"00005833\",\"descCodPostalCentroTrabajo\":\"DF\",\"descOUNivel9\":\"CANALES ATENDIDOS\",\"descOUNivel8\":\"CANALES ATENDIDOS\",\"descOUNivel7\":\"CANALES ATENDIDOS\",\"descOUNivel6\":\"CANALES ATENDIDOS\",\"descOUNivel5\":\"CANALES ATENDIDOS\",\"descOUNivel4\":\"TECNOLOGIA MULTICANAL\",\"descOUNivel3\":\"SISTEMAS Y OPERACIONES\",\"descBancoOficinaPers\":\"3307\",\"corporateNumber\":\" \",\"codOUNivel5\":\"00012899\",\"codOUNivel4\":\"00010142\",\"codOUNivel7\":\"00012899\",\"codOUNivel6\":\"00012899\",\"codOUNivel9\":\"00012899\",\"codOUNivel8\":\"00012899\"}},\"emails\":[{\"address\":\"[email protected]\",\"primary\":true}],\"etag\":\"\\\"KuAr0EK1uUI7oJNfO_dWOREN2ro/dbE6bs1euQMov6wc4Dmi3rfnjUc\\\"\",\"externalIds\":[{\"customType\":\"Employee ID\",\"type\":\"custom\",\"value\":\"MB58756\"}],\"kind\":\"admin#directory#user\",\"name\":{\"familyName\":\"ROSAS RAMIREZ\",\"fullName\":\"PEDRO ROSAS RAMIREZ\",\"givenName\":\"PEDRO\"},\"nonEditableAliases\":[\"[email protected]\"],\"organizations\":[{\"customType\":\"Work\",\"department\":\"CANALES ATENDIDOS\",\"location\":\"018533073307\",\"name\":\"BBVA BANCOMER SERVICIO ADMINIS\",\"primary\":true,\"title\":\"LIDER DE PROYECTO DYD A\"}],\"primaryEmail\":\"[email protected]\",\"suspended\":false,\"status\":\"ACTIVE\",\"ouResponsible\":{\"id\":\"00012899\",\"name\":\"CANALES ATENDIDOS\",\"responsibleEmployeeId\":\"M62139\",\"updateDate\":1450243038394}}}";
              ParsearJson parser = new ParsearJson();

              empleadoNuevo = parser.ConvertirAUsuario(resultado);

              System.out.println(resultado);

              empleadosNuevos.add(empleadoNuevo);

            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      } else {
        for (String strEmailUsuario : listaEmailsUsuarios) {

          /*PRUEBA OFFLINE*/

          String URI = "https://bbva-gapis.appspot.com/gprofile/users/" + strEmailUsuario;
          HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
          GenericUrl url = new GenericUrl(URI);
          HttpRequest request = requestFactory.buildGetRequest(url);
          HttpResponse response = request.execute();
          String content = response.parseAsString();

          resultado = content;
          /*END PRUEBA OFFLINE*/

          // resultado =
          // "{\"code\":\"OK\",\"message\":\"successful\",\"data\":{\"userDefinedFields\":[{\"key\":\"uid\",\"value\":\"MB58756\"},{\"key\":\"descOUPadre\",\"value\":\"SISTEMAS Y OPERACIONES\"},{\"key\":\"codCorporativo\",\"value\":\"00003719381\"},{\"key\":\"descEmpresaExterno\",\"value\":\" \"},{\"key\":\"codCargo\",\"value\":\"IHJ\"},{\"key\":\"descEmpresa\",\"value\":\"BBVA BANCOMER SERVICIO ADMINIS\"},{\"key\":\"codCSB\",\"value\":\"9016\"},{\"key\":\"descOUBase\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel10\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descCentroCoste\",\"value\":\"D Y D CANALES\"},{\"key\":\"uidJefe\",\"value\":\"M901737\"},{\"key\":\"codEstado\",\"value\":\"DF\"},{\"key\":\"codOUNivel10\",\"value\":\"00012899\"},{\"key\":\"codOUPadre\",\"value\":\"00005833\"},{\"key\":\"descpais\",\"value\":\"MÉXICO\"},{\"key\":\"c\",\"value\":\"MEX\"},{\"key\":\"telephoneNumber\",\"value\":\" \"},{\"key\":\"rangoGlobal\",\"value\":\" \"},{\"key\":\"codPostalCentroTrabajo\",\"value\":\"03339\"},{\"key\":\"codBancoOficinaPers\",\"value\":\"01853307\"},{\"key\":\"descCentroTrabajo\",\"value\":\"CENTRO BANCOMER D.F. (CON COME\"},{\"key\":\"descEstado\",\"value\":\"DISTRITO FEDERAL\"},{\"key\":\"mobile\",\"value\":\" \"},{\"key\":\"descLargaPlanta\",\"value\":\"N-6 C-A C-E M-7 E-24\"},{\"key\":\"esEmpleado\",\"value\":\"E\"},{\"key\":\"title\",\"value\":\"LIDER DE PROYECTO DYD A\"},{\"key\":\"o\",\"value\":\"0185\"},{\"key\":\"codCentroCoste\",\"value\":\"0000\"},{\"key\":\"posicion\",\"value\":\"00238344\"},{\"key\":\"pager\",\"value\":\" \"},{\"key\":\"apellido2\",\"value\":\"RAMIREZ\"},{\"key\":\"codCentroTrabajo\",\"value\":\"25001\"},{\"key\":\"descOUNivel2\",\"value\":\"MEXICO\"},{\"key\":\"descOUNivel1\",\"value\":\"MEXICO\"},{\"key\":\"mail\",\"value\":\"[email protected]\"},{\"key\":\"codOficina\",\"value\":\"01853307\"},{\"key\":\"codOUNivel1\",\"value\":\"00000141\"},{\"key\":\"codOUNivel2\",\"value\":\"00000141\"},{\"key\":\"apellido1\",\"value\":\"ROSAS\"},{\"key\":\"codOUNivel3\",\"value\":\"00005833\"},{\"key\":\"descCodPostalCentroTrabajo\",\"value\":\"DF\"},{\"key\":\"descOUNivel9\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel8\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel7\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel6\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel5\",\"value\":\"CANALES ATENDIDOS\"},{\"key\":\"descOUNivel4\",\"value\":\"TECNOLOGIA MULTICANAL\"},{\"key\":\"descOUNivel3\",\"value\":\"SISTEMAS Y OPERACIONES\"},{\"key\":\"descBancoOficinaPers\",\"value\":\"3307\"},{\"key\":\"corporateNumber\",\"value\":\" \"},{\"key\":\"codOUNivel5\",\"value\":\"00012899\"},{\"key\":\"codOUNivel4\",\"value\":\"00010142\"},{\"key\":\"codOUNivel7\",\"value\":\"00012899\"},{\"key\":\"codOUNivel6\",\"value\":\"00012899\"},{\"key\":\"codOUNivel9\",\"value\":\"00012899\"},{\"key\":\"codOUNivel8\",\"value\":\"00012899\"}],\"id\":\"102286709937216158038\",\"addresses\":[{\"country\":\"MÉXICO\",\"countryCode\":\"ES\",\"formatted\":\"DISTRITO FEDERAL\\n03339\\nMÉXICO\",\"locality\":\"DF\",\"poBox\":\"03339\",\"postalCode\":\"03339\",\"streetAddress\":\"N-6 C-A C-E M-7 E-24\",\"type\":\"work\"}],\"updateTime\":1449889391185,\"customSchemas\":{\"ldapUserData\":{\"uid\":\"MB58756\",\"descOUPadre\":\"SISTEMAS Y OPERACIONES\",\"codCorporativo\":\"00003719381\",\"descEmpresaExterno\":\" \",\"codCargo\":\"IHJ\",\"descEmpresa\":\"BBVA BANCOMER SERVICIO ADMINIS\",\"codCSB\":\"9016\",\"descOUBase\":\"CANALES ATENDIDOS\",\"descOUNivel10\":\"CANALES ATENDIDOS\",\"descCentroCoste\":\"D Y D CANALES\",\"uidJefe\":\"M901737\",\"codEstado\":\"DF\",\"codOUNivel10\":\"00012899\",\"codOUPadre\":\"00005833\",\"descpais\":\"MÉXICO\",\"codPais\":\"MEX\",\"telephoneNumber\":\" \",\"rangoGlobal\":\" \",\"codPostalCentroTrabajo\":\"03339\",\"codBancoOficinaPers\":\"01853307\",\"descCentroTrabajo\":\"CENTRO BANCOMER D.F. (CON COME\",\"descEstado\":\"DISTRITO FEDERAL\",\"mobile\":\" \",\"descLargaPlanta\":\"N-6 C-A C-E M-7 E-24\",\"esEmpleado\":\"E\",\"title\":\"LIDER DE PROYECTO DYD A\",\"organization\":\"0185\",\"codCentroCoste\":\"0000\",\"posicion\":\"00238344\",\"pager\":\" \",\"apellido2\":\"RAMIREZ\",\"codCentroTrabajo\":\"25001\",\"descOUNivel2\":\"MEXICO\",\"descOUNivel1\":\"MEXICO\",\"mail\":\"[email protected]\",\"codOficina\":\"01853307\",\"codOUNivel1\":\"00000141\",\"codOUNivel2\":\"00000141\",\"apellido1\":\"ROSAS\",\"codOUNivel3\":\"00005833\",\"descCodPostalCentroTrabajo\":\"DF\",\"descOUNivel9\":\"CANALES ATENDIDOS\",\"descOUNivel8\":\"CANALES ATENDIDOS\",\"descOUNivel7\":\"CANALES ATENDIDOS\",\"descOUNivel6\":\"CANALES ATENDIDOS\",\"descOUNivel5\":\"CANALES ATENDIDOS\",\"descOUNivel4\":\"TECNOLOGIA MULTICANAL\",\"descOUNivel3\":\"SISTEMAS Y OPERACIONES\",\"descBancoOficinaPers\":\"3307\",\"corporateNumber\":\" \",\"codOUNivel5\":\"00012899\",\"codOUNivel4\":\"00010142\",\"codOUNivel7\":\"00012899\",\"codOUNivel6\":\"00012899\",\"codOUNivel9\":\"00012899\",\"codOUNivel8\":\"00012899\"}},\"emails\":[{\"address\":\"[email protected]\",\"primary\":true}],\"etag\":\"\\\"KuAr0EK1uUI7oJNfO_dWOREN2ro/dbE6bs1euQMov6wc4Dmi3rfnjUc\\\"\",\"externalIds\":[{\"customType\":\"Employee ID\",\"type\":\"custom\",\"value\":\"MB58756\"}],\"kind\":\"admin#directory#user\",\"name\":{\"familyName\":\"ROSAS RAMIREZ\",\"fullName\":\"PEDRO ROSAS RAMIREZ\",\"givenName\":\"PEDRO\"},\"nonEditableAliases\":[\"[email protected]\"],\"organizations\":[{\"customType\":\"Work\",\"department\":\"CANALES ATENDIDOS\",\"location\":\"018533073307\",\"name\":\"BBVA BANCOMER SERVICIO ADMINIS\",\"primary\":true,\"title\":\"LIDER DE PROYECTO DYD A\"}],\"primaryEmail\":\"[email protected]\",\"suspended\":false,\"status\":\"ACTIVE\",\"ouResponsible\":{\"id\":\"00012899\",\"name\":\"CANALES ATENDIDOS\",\"responsibleEmployeeId\":\"M62139\",\"updateDate\":1450243038394}}}";
          ParsearJson parser = new ParsearJson();

          empleadoNuevo = parser.ConvertirAUsuario(resultado);

          System.out.println(resultado);

          empleadosNuevos.add(empleadoNuevo);
        }
      }

    } catch (IOException e) {

      e.printStackTrace();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return empleadosNuevos;
  }
 /**
  * Parses the given error HTTP response using the given JSON factory.
  *
  * @param jsonFactory JSON factory
  * @param response HTTP response
  * @return new instance of the Google JSON error information
  * @throws IllegalArgumentException if content type is not {@link Json#MEDIA_TYPE} or if expected
  *     {@code "data"} or {@code "error"} key is not found
  */
 public static GoogleJsonError parse(JsonFactory jsonFactory, HttpResponse response)
     throws IOException {
   return new JsonCParser(jsonFactory)
       .parseAndClose(response.getContent(), response.getContentCharset(), GoogleJsonError.class);
 }
Ejemplo n.º 23
0
 public static Feed first100Entries(HttpRequestFactory requestFactory, DocsUrl url)
     throws IOException {
   HttpRequest request = requestFactory.buildGetRequest(url);
   HttpResponse response = requestExecutor.executeNonSensitive(request);
   return response.parseAs(Feed.class);
 }
Ejemplo n.º 24
0
  private boolean getSig(PageInfo page) {
    if (!proxy.isAvailable()) return false;

    if (page.dataProcessed.get()
        || page.getSig() != null
        || page.sigChecked.get()
        || page.loadingStarted.get()) return false;

    boolean sigFound = false;
    String rqUrl =
        ExecutionContext.baseUrl
            + ImageExtractor.PAGES_REQUEST_TEMPLATE.replace(
                ImageExtractor.RQ_PG_PLACEHOLDER, page.getPid());

    try {
      HttpResponse resp = getContent(rqUrl, proxy, true);
      if (resp == null) {
        logger.info(String.format(SIG_ERROR_TEMPLATE, rqUrl, proxy.toString()));
        return false;
      }

      String respStr = IOUtils.toString(resp.getContent());
      PagesInfo framePages = Mapper.objectMapper.readValue(respStr, PagesInfo.class);

      PageInfo[] pages = framePages.getPagesArray();
      for (PageInfo framePage : pages)
        if (framePage.getOrder() >= page.getOrder() && framePage.getSrc() != null) {
          PageInfo _page =
              ExecutionContext.bookInfo.getPagesInfo().getPageByPid(framePage.getPid());

          if (_page.dataProcessed.get() || _page.getSig() != null || _page.sigChecked.get())
            continue;

          String _frameSrc = framePage.getSrc();
          if (_frameSrc != null) _page.setSrc(_frameSrc);

          if (_page.getSig() != null) {
            if (_page.getPid().equals(page.getPid())) sigFound = true;
            _page.sigChecked.set(true);

            proxy.promoteProxy();

            // Если есть возможность - пытаемся грузить страницу сразу
            Pools.imgExecutor.execute(new PageImgProcessor(_page, proxy));
          }

          if (_page.getSrc() != null && _page.getSig() == null)
            logger.finest(String.format(SIG_WRONG_FORMAT, _page.getSrc()));
        }
    } catch (JsonParseException
        | JsonMappingException
        | SocketTimeoutException
        | SocketException
        | NoHttpResponseException ce) {
      if (!proxy.isLocal()) {
        proxy.registerFailure();
        logger.info(String.format("Proxy %s failed!", proxy.toString()));
      }

      ce.printStackTrace();
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    return sigFound;
  }