@RequestMapping(value = "/rec/rec", method = RequestMethod.GET)
  public ResponseEntity<ArrayList<String>> recomendaciones(
      @RequestParam("url") String url,
      @RequestParam(value = "custom", required = false) String custom,
      @RequestParam(value = "expire", required = false) String expireDate,
      @RequestParam(value = "hasToken", required = false) String hasToken,
      HttpServletRequest request) {

    UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"});
    /*
     * Check if url comes through http or https
     */
    if (urlValidator.isValid(url)) {
      /*
       * Hash of URL or custom
       */
      String id;
      if (!custom.equals("")) {

        id = custom;

        if (shortURLRepository.findByHash(id) == null) {
          System.out.println("1");
          return new ResponseEntity<>(HttpStatus.CREATED);
        } else {
          System.out.println("2");
          try {
            HttpResponse<JsonNode> response =
                Unirest.get("https://wordsapiv1.p.mashape.com/words/" + id + "/synonyms")
                    .header("X-Mashape-Key", "VLzNEVr9zQmsh0gOlqs6wudMxDo1p1vCnjEjsnjNBhOCFeqLxr")
                    .header("Accept", "application/json")
                    .asJson();
            ObjectMapper map = new ObjectMapper();
            Synonym sin = map.readValue(response.getBody().toString(), Synonym.class);
            return new ResponseEntity<>(sin.getSynonyms(), HttpStatus.BAD_REQUEST);
          } catch (Exception e) {
            /*
             * Caso en el que la id seleccionada esta cogida y la
             * API no da alternativas
             */
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
          }
        }
      } else {
        return new ResponseEntity<>(HttpStatus.OK);
      }
    } else {
      System.out.println("3");
      return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
  }
Exemplo n.º 2
0
 private void test(OsmPrimitive p) {
   for (String k : p.keySet()) {
     // Test key against URL validator
     if (!doTest(p, k, URL_KEYS, UrlValidator.getInstance(), INVALID_URL)) {
       // Test key against e-mail validator only if the URL validator did not fail
       doTest(p, k, EMAIL_KEYS, EmailValidator.getInstance(), INVALID_EMAIL);
     }
   }
 }
Exemplo n.º 3
0
  /**
   * This method determines what text likely represents and sets the proper attribute on the Author.
   *
   * @param author
   * @param text
   */
  private void setAuthorAttribute(Author author, String text) {
    EmailValidator emailValidator = EmailValidator.getInstance(false);

    // Check if it is a valid email.
    if (emailValidator.isValid(text)) {
      // It is, so set it there.
      author.setEmail(text);

      return;
    }

    UrlValidator urlValidator = UrlValidator.getInstance();

    // Now check if it is a URL.
    if (urlValidator.isValid(text)) {
      author.setUrl(text);

      return;
    }

    // If all else fails, then it will just be a name!
    author.setName(text);
  }
  /**
   * If shortURL is valid, creates it and saves it XXX: at the moment, it just ignores unknown
   * emails, with no feedback for users.
   */
  protected ShortURL createAndSaveIfValid(
      String url,
      String custom,
      String hasToken,
      String expireDate,
      String ip,
      String[] emails,
      Principal principal,
      String country) {

    UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"});
    /*
     * Check if url comes through http or https
     */
    if (urlValidator.isValid(url)) {
      logger.info("Shortening valid url " + url);
      /*
       * Creates a hash from the current date in case this is not custom
       */
      String id;
      String now = new Date().toString();
      if (custom.equals("")) {
        id = Hashing.murmur3_32().hashString(now, StandardCharsets.UTF_8).toString();
      } else {
        id = custom;
      }

      /*
       * Has Token
       */
      String token = null;
      if (hasToken != null && !hasToken.equals("")) {
        token = UUID.randomUUID().toString();
      }
      /*
       * Expire date
       */
      Date expire = null;
      if (!expireDate.equals("")) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {
          expire = sdf.parse(expireDate);
        } catch (ParseException e) {
          e.printStackTrace();
          logger.info("Error: badly introduced date.");
        }
      }

      /*
       * Checks every mail inserted by the user, and maintains a list with
       * those corresponding to registered users.
       */
      List<String> trueEmails = new ArrayList<String>();
      for (int i = 0; i < emails.length; i++) {
        if (!emails[i].equals("")) {
          User foundUser = null;

          foundUser = userRepository.findByMail(emails[i]);
          if (foundUser != null) {
            trueEmails.add(foundUser.getMail());
          }
        }
      }

      /*
       * If no valid emails are introduced, link will be public and it
       * wont have an email list.
       */
      boolean isPrivate = false;
      if (trueEmails.size() > 0) {
        isPrivate = true;
      } else {
        trueEmails = null;
      }

      /*
       * Gets email
       */
      String owner = getOwnerMail();

      /*
       * Creates ShortURL object
       */
      ShortURL su =
          new ShortURL(
              id,
              url,
              linkTo(
                      methodOn(UrlShortenerControllerWithLogs.class)
                          .redirectTo(id, null, null, null, null))
                  .toUri(),
              new Date(System.currentTimeMillis()),
              expire,
              owner,
              token,
              HttpStatus.TEMPORARY_REDIRECT.value(),
              ip,
              country,
              isPrivate,
              trueEmails);

      /*
       * Insert to DB
       */
      return shortURLRepository.save(su);
    } else {
      logger.info("Not valid url " + url);
      return null;
    }
  }
  protected ShortURL createAndSaveIfValid(
      String url,
      String sponsor,
      String brand,
      String owner,
      String ip,
      String name,
      String username,
      boolean advert,
      int seconds,
      boolean useConditional) {
    UrlValidator urlValidator = new UrlValidator(new String[] {"http", "https"});
    if (urlValidator.isValid(url) || (url.equals("") && useConditional)) {
      ShortURL su = null;
      ResponseEntity<String> entity =
          new RestTemplate().getForEntity("http://ipinfo.io/" + ip + "/json", String.class);
      String json = entity.getBody().toString();
      String country = "";
      try {
        JSONObject obj = new JSONObject(json);
        country = obj.getString("country");
      } catch (JSONException e) {
      }

      if (!name.equals("")) {
        su =
            new ShortURL(
                name,
                url,
                linkTo(methodOn(UrlShortenerControllerWithLogs.class).redirectTo(name, null))
                    .toUri(),
                sponsor,
                new Date(System.currentTimeMillis()),
                owner,
                HttpStatus.TEMPORARY_REDIRECT.value(),
                true,
                ip,
                country,
                username,
                advert,
                seconds);
      } else {
        String id = Hashing.murmur3_32().hashString(url, StandardCharsets.UTF_8).toString();
        su =
            new ShortURL(
                id,
                url,
                linkTo(methodOn(UrlShortenerController.class).redirectTo(id, null)).toUri(),
                sponsor,
                new Date(System.currentTimeMillis()),
                owner,
                HttpStatus.TEMPORARY_REDIRECT.value(),
                true,
                ip,
                country,
                username,
                advert,
                seconds);
      }
      return shortURLRepositoryExtended.save(su);
    } else {
      return null;
    }
  }
Exemplo n.º 6
0
  /**
   * @param theUrl
   * @param conAttempts
   * @return
   * @throws IOException
   */
  public boolean validUrl(String theUrl, int conAttempts) throws IOException {
    long total_time = 0, endTime = 0;
    long startTime = System.currentTimeMillis();
    URL link = new URL(theUrl);
    int CONNECT_TIMEOUT = 5000, READ_TIMEOUT = 2000;

    HttpURLConnection huc = (HttpURLConnection) link.openConnection();
    huc.setRequestProperty("User-Agent", userAgent);
    huc.setConnectTimeout(CONNECT_TIMEOUT);
    huc.setReadTimeout(READ_TIMEOUT);
    try {
      huc.connect();

    } catch (java.net.ConnectException e) {
      print(e.getMessage() + "\n");
      if (e.getMessage().equalsIgnoreCase("Connection timed out")) {
        if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
          System.out.println("Recurrencing validUrl method...");
          return validUrl(theUrl, conAttempts + 1);
        } else return false;
      } else return false;

    } catch (java.net.SocketTimeoutException e) {
      print(e.getMessage() + "\n");
      if (e.getMessage().equalsIgnoreCase("connect timed out")) {
        if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
          System.out.println("Recurrencing validUrl method...");
          return validUrl(theUrl, conAttempts + 1);
        } else return false;
      } else return false;

    } catch (IOException e) {
      print(e.getMessage() + "\n");
      return false;
    }
    UrlValidator urlValidator = new UrlValidator();
    if (urlValidator.isValid(theUrl) == true) {
      System.out.println("valid url form");
      if (huc.getContentType() != null) {
        System.out.println("Content: " + huc.getContentType());
        if (huc.getContentType().equals("text/html")
            || huc.getContentType().equals("unknown/unknown")) {
          if (getResposeCode(theUrl, 0) >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            System.out.println("Server Response Code: " + getResposeCode(theUrl, 0));
            return false;
          }
        }
        System.out.println(huc.getContentType());
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        System.out.println("Total elapsed time is :" + total_time + "\n");
        return true;
      } else { // edw erxetai an den prolavei na diavasei h an einai null to content
        endTime = System.currentTimeMillis();
        total_time = total_time + (endTime - startTime);
        System.out.println("Total elapsed time is :" + total_time + "\n");
        if (conAttempts != MAX_CONNECTION_ATTEMPTS) {
          System.out.println("Recurrencing validUrl method...");
          return validUrl(theUrl, conAttempts + 1);
        } else return false;
      }
    } else {
      endTime = System.currentTimeMillis();
      total_time = total_time + (endTime - startTime);
      System.out.println("Total elapsed time is :" + total_time + "\n");
      return false;
    }
  }