コード例 #1
0
 public static String dumpConfigurationAsJson() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory jfactory = mapper.getJsonFactory();
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator gen = jfactory.createJsonGenerator(sw);
     gen.writeStartArray();
     for (String v : keys) {
       String st = dumpConfigurationAsJson(v);
       ObjectMapper op = new ObjectMapper();
       JsonNode p = op.readTree(st);
       Logger.debug("OBJECT:" + p.toString());
       Logger.debug("STRING:" + st);
       // JsonParser jp = jfactory.createJsonParser(st);
       gen.writeTree(p);
     }
     gen.writeEndArray();
     gen.close();
     return sw.toString();
   } catch (Exception e) {
     Logger.error("Cannot generate a json for the configuration", e);
   }
   return "[]";
 } // dumpConfigurationAsJson()
コード例 #2
0
  @Override
  public F.Promise<SimpleResult> call(Context ctx) throws Throwable {
    if (Logger.isTraceEnabled()) Logger.trace("Method Start");
    Context.current.set(ctx);

    if (Logger.isDebugEnabled())
      Logger.debug("AnonymousLogin  for resource " + Context.current().request());

    String user = BBConfiguration.getBaasBoxUsername();
    String password = BBConfiguration.getBaasBoxPassword();

    // retrieve AppCode
    String appCode = RequestHeaderHelper.getAppCode(ctx);

    ctx.args.put("username", user);
    ctx.args.put("password", password);
    ctx.args.put("appcode", appCode);

    if (Logger.isDebugEnabled()) Logger.debug("username (defined in conf file): " + user);
    if (Logger.isDebugEnabled()) Logger.debug("password (defined in conf file): " + password);
    if (Logger.isDebugEnabled()) Logger.debug("appcode (from header or querystring): " + appCode);
    if (Logger.isDebugEnabled()) Logger.debug("token: N/A");

    // executes the request
    F.Promise<SimpleResult> tempResult = delegate.call(ctx);

    WrapResponse wr = new WrapResponse();
    // SimpleResult result=wr.wrap(ctx, tempResult);
    F.Promise<SimpleResult> result = wr.wrapAsync(ctx, tempResult);
    if (Logger.isTraceEnabled()) Logger.trace("Method End");
    return result;
  }
コード例 #3
0
  @Override
  public void doSave(Identity socialUser) {

    // Recherche d'un user existant et création ou mise à jour des données en SGBD
    User userCfp = User.findByExternalId(socialUser.id().id(), socialUser.id().providerId());
    Logger.debug(
        "doSave "
            + socialUser.fullName()
            + " / socialUserId : "
            + socialUser.id().id()
            + " - "
            + socialUser.id().providerId());
    if (userCfp == null) {
      Logger.debug("Création du user : "******"Mise à jour du user : " + socialUser.fullName());
      userCfp.fullname = socialUser.fullName();
      if (socialUser.avatarUrl().isDefined()) {
        userCfp.avatar = socialUser.avatarUrl().get();
      }
    }

    if (User.findAll().isEmpty()) {
      userCfp.admin = true;
    }

    userCfp.save();
  }
コード例 #4
0
ファイル: PdfFileUtil.java プロジェクト: nileblack/mnc
 private static void processPages(PdfFile file, int dpi, int start, int end) {
   try {
     Document document = new Document();
     String staticpath = Play.configuration.getProperty("staticpath", "");
     Logger.debug("process %s", staticpath + file.originalFile);
     document.setFile(staticpath + file.originalFile);
     int numberOfPages = document.getNumberOfPages();
     boolean thumbnail = false;
     if (start < 0 && end < 0) {
       file.numPages = numberOfPages;
       file.save();
       thumbnail = true;
     }
     if (end < 0) {
       end = numberOfPages;
     }
     if (start < 0) {
       start = 0;
     }
     Logger.debug("process %s which has pages %s", file.title, numberOfPages);
     for (int i = start; i < end; i++) {
       processPage(file, document, i, dpi, thumbnail);
     }
   } catch (PDFException e) {
     e.printStackTrace();
   } catch (PDFSecurityException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #5
0
ファイル: WidgetManager.java プロジェクト: kjbekkelund/awacs
  protected static SortedSet<Widget> findAllWidgets() {
    String ext = ".java";
    Logger.debug("Scanning for widgets...");

    SortedSet<Widget> all = new TreeSet<Widget>();

    for (VirtualFile f : Play.javaPath) {
      VirtualFile widgets = f.child("widgets");
      if (widgets.exists()) {
        Logger.debug("Searching " + widgets.getName());
        for (VirtualFile pkg : widgets.list()) {
          if (pkg != null && pkg.isDirectory()) {
            for (VirtualFile w : pkg.list()) {
              if (w.getName().endsWith(ext)) {
                String className = w.getName().substring(0, w.getName().length() - ext.length());
                String widgetName = pkg.getName() + "." + className;
                if (isWidget(widgetName))
                  try {
                    all.add(getWidget(widgetName));
                    Logger.debug("Found " + widgetName);
                  } catch (InvalidWidgetException e) {
                    Logger.error(e, widgetName + " is not a widget?!");
                  }
                else Logger.warn(widgetName + " is not a widget.");
              }
            }
          }
        }
      }
    }
    Logger.info("Found " + all.size() + " widgets");
    return all;
  }
コード例 #6
0
ファイル: Post.java プロジェクト: rlguarino/lifeinvader
  public static void deletePost(Long post_ID) throws SQLException {
    Post post = null;

    String deletePostStr =
        String.format("DELETE from %s where postid = ?", Post.dquote(POST), post_ID);

    Connection conn = null;
    PreparedStatement deleteP = null;

    if (post_ID != null) {
      try {
        conn = DB.getConnection();
        deleteP = conn.prepareStatement(deletePostStr);
        ResultSet rs = deleteP.executeQuery();

        if (rs.next()) {
          Logger.debug("Failed to delete the Post.");
        }
        deleteP.close();
        conn.close();
      } catch (SQLException e) {
        Logger.debug("Failed while trying to delete the post.");
      }
    } else {
      Logger.debug("Post id is null.");
    }
  }
コード例 #7
0
 public static void log(
     String level,
     String clazz,
     String clazzSimpleName,
     String packageName,
     String method,
     String signature,
     String fileName,
     String relativeFileName,
     int line,
     Object[] args) {
   Throwable throwable = null;
   String pattern = "";
   if (args[0] instanceof Throwable) {
     throwable = (Throwable) args[0];
     pattern = (String) args[1];
   } else {
     pattern = (String) args[0];
   }
   pattern = stringFormatPrefix + pattern;
   Object[] betterLogsArgs = new Object[argsPrefix.size()];
   int i = 0;
   for (String argName : argsPrefix) {
     if ("class".equals(argName)) betterLogsArgs[i] = clazz;
     if ("simpleClass".equals(argName)) betterLogsArgs[i] = clazzSimpleName;
     if ("package".equals(argName)) betterLogsArgs[i] = packageName;
     if ("method".equals(argName)) betterLogsArgs[i] = method;
     if ("file".equals(argName)) betterLogsArgs[i] = fileName;
     if ("line".equals(argName)) betterLogsArgs[i] = line;
     if ("relativeFile".equals(argName)) betterLogsArgs[i] = relativeFileName;
     if ("signature".equals(argName)) betterLogsArgs[i] = signature;
     i++;
   }
   if ("trace".equals(level)) {
     Logger.trace(pattern, handleLogArgs(betterLogsArgs, args, 1));
   } else if ("debug".equals(level)) {
     if (throwable != null)
       Logger.debug(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2));
     else Logger.debug(pattern, handleLogArgs(betterLogsArgs, args, 1));
   } else if ("info".equals(level)) {
     if (throwable != null)
       Logger.info(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2));
     else Logger.info(pattern, handleLogArgs(betterLogsArgs, args, 1));
   } else if ("warn".equals(level)) {
     if (throwable != null)
       Logger.warn(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2));
     else Logger.warn(pattern, handleLogArgs(betterLogsArgs, args, 1));
   } else if ("error".equals(level)) {
     if (throwable != null)
       Logger.error(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2));
     else Logger.error(pattern, handleLogArgs(betterLogsArgs, args, 1));
   } else if ("fatal".equals(level)) {
     if (throwable != null)
       Logger.fatal(throwable, pattern, handleLogArgs(betterLogsArgs, args, 2));
     else Logger.fatal(pattern, handleLogArgs(betterLogsArgs, args, 1));
   }
 }
コード例 #8
0
  public static void collect(CollectorInfo.Moment moment) {
    List<Page> pages = MongoService.getAllPages();
    for (Page page : pages) {
      try {

        long lastMonth = DateTime.now().minusMonths(1).toDateTime().getMillis() / 1000;
        long now = DateTime.now().toDateTime().getMillis() / 1000;

        PagingParameters pagingParameters = new PagingParameters(25, null, lastMonth, now);
        PagedList<Post> posts;
        switch (moment) {
          case ALL:
            posts = facebook.feedOperations().getPosts(page.getId());
            break;
          case RECENT:
            posts = facebook.feedOperations().getPosts(page.getId(), pagingParameters);
            break;
          default:
            posts = facebook.feedOperations().getPosts(page.getId());
            break;
        }

        boolean firstTime = true;
        do {
          try {
            if (!firstTime)
              posts = facebook.feedOperations().getPosts(page.getId(), posts.getNextPage());
            firstTime = false;
            for (Post post : posts) {
              Set<User> users = new HashSet<>();
              Set<Comment> comments = new HashSet<>();
              fetchCommentAndUpdateUsers(post, comments, users, page);
              fetchLikesAndUpdateUsers(post, users, page);

              MongoService.save(post);

              for (Comment comment : comments) {
                MongoService.save(comment);
              }
              // save or update users iterations
              MongoService.save(users);
            }
          } catch (Exception e) {
            Logger.debug("error on get more  posts: " + e.getMessage());
          }
          Logger.debug("update:" + page.getTitle() + "  ");
        } while (posts.getNextPage() != null);
        Logger.debug("Finished page:" + page.getId());

      } catch (Exception e) {
        Logger.debug("error on page:" + page.getId());
      }
    }
  }
コード例 #9
0
ファイル: DbHelper.java プロジェクト: vvhh2002/baasbox
 public static OCommandRequest selectCommandBuilder(
     String from, boolean count, QueryParams criteria) throws SqlInjectionException {
   OGraphDatabase db = DbHelper.getConnection();
   OCommandRequest command =
       db.command(
           new OSQLSynchQuery<ODocument>(selectQueryBuilder(from, count, criteria))
               .setFetchPlan(fetchPlan.replace("?", criteria.getDepth().toString())));
   if (!command.isIdempotent()) throw new SqlInjectionException();
   Logger.debug("commandBuilder: ");
   Logger.debug("  " + criteria.toString());
   Logger.debug("  " + command.toString());
   return command;
 }
コード例 #10
0
 /** Is this method get PlayPropertiesAccessor annotation ? */
 private boolean hasPlayPropertiesAccessorAnnotation(CtMethod ctMethod) {
   for (Object object : ctMethod.getAvailableAnnotations()) {
     Annotation ann = (Annotation) object;
     Logger.debug("Annotation method is " + ann.annotationType().getName());
     if (ann.annotationType()
         .getName()
         .equals("play.classloading.enhancers.PropertiesEnhancer$PlayPropertyAccessor")) {
       Logger.debug("Method " + ctMethod.getName() + " has be enhanced by propertiesEnhancer");
       return true;
     }
   }
   Logger.debug("Method " + ctMethod.getName() + " has not be enhance by propertiesEnhancer");
   return false;
 }
コード例 #11
0
 private void install7Zip() throws RemoteException {
   Logger.debug("Unzipping 7zip...");
   this.remoteConnection.executeCommand(
       "powershell -command & { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::ExtractToDirectory('"
           + this.homeDir
           + "\\"
           + WindowsInstaller.SEVEN_ZIP_ARCHIVE
           + "', '"
           + this.homeDir
           + "\\"
           + WindowsInstaller.SEVEN_ZIP_DIR
           + "'); }");
   Logger.debug("7zip successfully unzipped!");
 }
コード例 #12
0
ファイル: Datasets.java プロジェクト: robstek/geo-publisher
  public static Promise<Result> editForm(final String datasetId) {
    // TODO
    Logger.debug("editForm");

    final ActorSelection database = Akka.system().actorSelection(databaseRef);

    return from(database)
        .get(Dataset.class, datasetId)
        .query(listDatasetColumns(datasetId))
        .executeFlat(
            new Function2<Dataset, List<Column>, Promise<Result>>() {
              @Override
              public Promise<Result> apply(final Dataset ds, final List<Column> columns)
                  throws Throwable {
                return from(database)
                    .get(SourceDataset.class, ds.sourceDataset().id())
                    .executeFlat(
                        new Function<SourceDataset, Promise<Result>>() {
                          @Override
                          public Promise<Result> apply(final SourceDataset sds) throws Throwable {
                            final Form<DatasetForm> datasetForm =
                                Form.form(DatasetForm.class)
                                    .fill(new DatasetForm(ds, sds.dataSource().id(), columns));

                            Logger.debug("Edit datasetForm: " + datasetForm);
                            return renderEditForm(datasetForm);
                          }
                        });
              }
            });
    //		return Promise.pure ((Result) ok ());
  }
コード例 #13
0
ファイル: Datasets.java プロジェクト: robstek/geo-publisher
  public static Promise<Result> getDatasetJson(final String datasetId) {
    final ActorSelection database = Akka.system().actorSelection(databaseRef);

    Logger.debug("getDatasetJson: " + datasetId);

    return from(database)
        .get(Dataset.class, datasetId)
        .execute(
            new Function<Dataset, Result>() {
              @Override
              public Result apply(final Dataset ds) throws Throwable {
                final ObjectNode result = Json.newObject();

                result.put("id", datasetId);

                if (ds == null) {
                  result.put("status", "notfound");
                  return ok(result);
                }

                result.put("status", "ok");
                result.put("dataset", Json.toJson(ds));

                return ok(result);
              }
            });
  }
コード例 #14
0
  /**
   * Do merge.
   *
   * @return the result
   */
  @SubjectPresent
  public static Result doMerge() {
    Logger.debug("Account doMerge");
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    // this is the currently logged in user
    final AuthUser aUser = PlayAuthenticate.getUser(session());

    // this is the user that was selected for a login
    final AuthUser bUser = PlayAuthenticate.getMergeUser(session());
    if (bUser == null) {
      // user to merge with could not be found, silently redirect to login
      return redirect(routes.Application.index());
    }

    final Form<Accept> filledForm = ACCEPT_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not select whether to merge or not merge
      return badRequest(ask_merge.render(filledForm, aUser, bUser));
    } else {
      // User made a choice :)
      final boolean merge = filledForm.get().accept;
      if (merge) {
        flash(
            ControllerUtil.FLASH_INFO_KEY, Messages.get("playauthenticate.accounts.merge.success"));
      }
      return PlayAuthenticate.merge(ctx(), merge);
    }
  }
コード例 #15
0
 private String createImageUrl() {
   Logger.debug("uploader url : " + Play.configuration.getProperty("domain.uploader"));
   return "http://"
       + Play.configuration.getProperty("domain.uploader")
       + "/attaches/"
       + group(CONTENT_GROUP);
 }
コード例 #16
0
 /**
  * Verify.
  *
  * @param token the token
  * @return the result
  */
 public static Result verify(final String token) {
   Logger.debug("Account verify");
   com.feth.play.module.pa.controllers.Authenticate.noCache(response());
   final TokenAction ta = tokenIsValid(token, Type.EMAIL_VERIFICATION);
   if (ta == null) {
     return badRequest(no_token_or_invalid.render());
   }
   final String email = ta.targetUser.email;
   //		final User verifiedUser = ta.targetUser;
   // if(session().containsKey("acctType") && StringUtils.equals("event",
   // session().get("acctType"))) {
   // verifiedUser.addRoles(SecurityRole.EVENT_ADMIN);
   // } else {
   // verifiedUser.addRoles(SecurityRole.PFP_ADMIN);
   // }
   User.verify(ta.targetUser);
   flash(
       ControllerUtil.FLASH_INFO_KEY,
       Messages.get("playauthenticate.verify_email.success", email));
   if (ControllerUtil.getLocalUser(session()) != null) {
     return redirect(routes.Application.index());
   } else {
     return redirect(routes.Signup.login());
   }
 }
コード例 #17
0
  @Override
  public void onStart(play.Application argo) {
    super.beforeStart(argo);
    Logger.debug("** on start **");
    try {
      MorphiaObject.mongo = new MongoClient("127.0.0.1", 27017);
    } catch (Exception e) {
      e.printStackTrace();
    }
    MorphiaObject.morphia = new Morphia();
    MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
    MorphiaObject.datastore.ensureIndexes();
    MorphiaObject.datastore.ensureCaps();

    Logger.debug("** Morphia datastore: " + MorphiaObject.datastore.getDB());
  }
コード例 #18
0
ファイル: SpringPlugin.java プロジェクト: noikiy/projects
 @Override
 public void onStop() {
   if (applicationContext != null) {
     Logger.debug("Closing Spring application context");
     applicationContext.close();
   }
 }
コード例 #19
0
ファイル: Datasets.java プロジェクト: robstek/geo-publisher
  public static Promise<Result> setNotificationResult(
      final String datasetId, final String notificationId) {
    final String[] resultString = request().body().asFormUrlEncoded().get("result");
    if (resultString == null || resultString.length != 1 || resultString[0] == null) {
      return Promise.pure((Result) redirect(controllers.routes.Datasets.show(datasetId)));
    }

    final ConfirmNotificationResult result = ConfirmNotificationResult.valueOf(resultString[0]);

    Logger.debug("Conform notification: " + notificationId + ", " + result);

    final ActorSelection database = Akka.system().actorSelection(databaseRef);

    return from(database)
        .query(new PutNotificationResult(notificationId, result))
        .execute(
            new Function<Response<?>, Result>() {
              @Override
              public Result apply(final Response<?> response) throws Throwable {
                if (response.getOperationresponse().equals(CrudResponse.OK)) {
                  flash("success", "Resultaat van de structuurwijziging is opgeslagen");
                } else {
                  flash("danger", "Resultaat van de structuurwijziging kon niet worden opgeslagen");
                }
                return redirect(controllers.routes.Datasets.show(datasetId));
              }
            });
  }
コード例 #20
0
  @Override
  public Object authenticate(final Context context, final Object payload) throws AuthException {

    final Request request = context.request();
    final String uri = request.uri();

    if (Logger.isDebugEnabled()) {
      Logger.debug("Returned with URL: '" + uri + "'");
    }

    final Configuration c = getConfiguration();

    final ConsumerKey key =
        new ConsumerKey(
            c.getString(SettingKeys.CONSUMER_KEY), c.getString(SettingKeys.CONSUMER_SECRET));
    final String requestTokenURL = c.getString(SettingKeys.REQUEST_TOKEN_URL);
    final String accessTokenURL = c.getString(SettingKeys.ACCESS_TOKEN_URL);
    final String authorizationURL = c.getString(SettingKeys.AUTHORIZATION_URL);
    final ServiceInfo info =
        new ServiceInfo(requestTokenURL, accessTokenURL, authorizationURL, key);
    final OAuth service = new OAuth(info, true);

    checkError(request);

    if (uri.contains(Constants.OAUTH_VERIFIER)) {

      final RequestToken rtoken =
          (RequestToken) PlayAuthenticate.removeFromCache(context.session(), CACHE_TOKEN);
      final String verifier = Authenticate.getQueryString(request, Constants.OAUTH_VERIFIER);
      final Either<OAuthException, RequestToken> retrieveAccessToken =
          service.retrieveAccessToken(rtoken, verifier);

      if (retrieveAccessToken.isLeft()) {
        throw new AuthException(retrieveAccessToken.left().get().getLocalizedMessage());
      } else {
        final I i = buildInfo(retrieveAccessToken.right().get());
        return transform(i);
      }
    } else {

      final String callbackURL = getRedirectUrl(request);

      final Either<OAuthException, RequestToken> reponse =
          service.retrieveRequestToken(callbackURL);

      if (reponse.isLeft()) {
        // Exception happened
        throw new AuthException(reponse.left().get().getLocalizedMessage());
      } else {
        // All good, we have the request token
        final RequestToken rtoken = reponse.right().get();

        final String token = rtoken.token();
        final String redirectUrl = service.redirectUrl(token);

        PlayAuthenticate.storeInCache(context.session(), CACHE_TOKEN, rtoken);
        return redirectUrl;
      }
    }
  }
コード例 #21
0
ファイル: Post.java プロジェクト: rlguarino/lifeinvader
  /**
   * FindById Searches the database for a Group object by the object id.
   *
   * @param connection The jdbc connection
   * @param id The id to select by
   */
  public static Post FindByID(Long post_ID) throws SQLException {
    Post post = null;
    PreparedStatement findPostId = null;
    Connection conn = null;

    String sql = String.format("SELECT * from %s where postid = ?", Post.dquote(POST), post_ID);

    if (post_ID != null) {
      try {
        conn = DB.getConnection();
        findPostId = conn.prepareStatement(sql);
        findPostId.setLong(1, post_ID);

        ResultSet rs = findPostId.executeQuery();

        if (rs.next()) {
          post =
              new Post(
                  rs.getString(Post.CONTENT),
                  rs.getString(Post.TYPE),
                  rs.getTimestamp(Post.TIMESTAMP),
                  rs.getLong(Post.USER_ID),
                  rs.getLong(Post.WALL_ID),
                  rs.getLong(Post.POST_ID));
        }

        findPostId.close();
        conn.close();
        return post;
      } catch (SQLException e) {
        Logger.debug("Error retrieving post.", e);
      }
    }
    return post;
  }
コード例 #22
0
ファイル: API.java プロジェクト: Agrassx/MapsCoffeeServer
  @BodyParser.Of(BodyParser.Json.class)
  public F.Promise<Result> addPoint() {

    JsonNode json = request().body().asJson();
    play.Logger.debug("AddPoint (Json): " + request().body().asJson().toString());

    String name = json.findPath("name").textValue();
    double latitude = json.get("location").get("lat").asDouble();
    double longitude = json.get("location").get("lon").asDouble();
    float rating = json.get("rating").floatValue();
    String id_token = json.findPath("access_token").textValue();
    String user_name = json.findPath("user_name").textValue();
    String user_id = json.findPath("user_id").textValue();

    latitude = getSixDecimalFormatNumber(latitude);
    longitude = getSixDecimalFormatNumber(longitude);

    ObjectNode newPoint = getNewPointJson(name, "", latitude, longitude);
    ObjectNode cafeInfo = getCafeInfoJson(rating, user_id, user_name);

    play.Logger.debug(
        String.format("\n Json newPoint: %s \n Json CafeInfo: %s", newPoint, cafeInfo));

    String id = generateId(name + latitude + longitude);

    WSRequest requestNewPoint = ws.url(getAddPointUrl(id)).setContentType("application/json");
    F.Promise<WSResponse> responsePromise;
    if (isValidToken(id_token)) {
      responsePromise = requestNewPoint.post(newPoint);
      return responsePromise.map(
          response -> {
            if (response.getStatus() == Http.Status.CREATED && addCafeInfo(id, cafeInfo)) {
              return ok(response.asJson());
            } else {
              return badRequest(response.asJson());
            }
          });

    } else {
      responsePromise = null;
      ObjectNode status = Json.newObject();
      status.put("status", "error");
      status.put("point", newPoint);
      status.put("reason", "invalid token");
      return responsePromise.map(wsResponse -> unauthorized(status));
    }
  }
コード例 #23
0
ファイル: API.java プロジェクト: Agrassx/MapsCoffeeServer
  public F.Promise<Result> points(String n, String s, String w, String e) {
    WSRequest request = ws.url(getSearchUrl());
    F.Promise<WSResponse> responsePromise = request.post(getRequestBody(n, s, w, e));

    play.Logger.debug(String.format("N - : %s, E - : %s, W - : %s, E - : %s", n, s, w, e));

    return responsePromise.map(response -> ok(getJsonPoints(response.asJson())));
  }
コード例 #24
0
  /**
   * Do forgot password.
   *
   * @return the result
   */
  public static Result doForgotPassword() {
    Logger.debug("Account doForgotPassword");
    com.feth.play.module.pa.controllers.Authenticate.noCache(response());
    final Form<EmailUserIdentity> filledForm = FORGOT_PASSWORD_FORM.bindFromRequest();
    if (filledForm.hasErrors()) {
      // User did not fill in his/her email
      return badRequest(password_forgot.render(filledForm));
    } else {
      // The email address given *BY AN UNKNWON PERSON* to the form - we
      // should find out if we actually have a user with this email
      // address and whether password login is enabled for him/her. Also
      // only send if the email address of the user has been verified.
      final String email = filledForm.get().email;

      final User user = User.findByEmail(email);
      if (user == null) {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_WARNING_KEY,
            "Your email address doesn't match our records. Please try again.");
      } else {
        // We don't want to expose whether a given email address is signed
        // up, so just say an email has been sent, even though it might not
        // be true - that's protecting our user privacy.
        flash(
            ControllerUtil.FLASH_INFO_KEY,
            Messages.get("playauthenticate.reset_password.message.instructions_sent", email));

        // yep, we have a user with this email that is active - we do
        // not know if the user owning that account has requested this
        // reset, though.
        final EmailAuthProvider provider = EmailAuthProvider.getProvider();
        // User exists
        if (user.emailValidated) {
          provider.sendPasswordResetMailing(user, ctx());
          // In case you actually want to let (the unknown person)
          // know whether a user was found/an email was sent, use,
          // change the flash message
        } else {
          // We need to change the message here, otherwise the user
          // does not understand whats going on - we should not verify
          // with the password reset, as a "bad" user could then sign
          // up with a fake email via OAuth and get it verified by an
          // a unsuspecting user that clicks the link.
          flash(
              ControllerUtil.FLASH_INFO_KEY,
              Messages.get("playauthenticate.reset_password.message.email_not_verified"));

          // You might want to re-send the verification email here...
          provider.sendVerifyEmailMailingAfterSignup(user, ctx());
        }
      }

      return redirect(routes.Signup.login());
    }
  }
コード例 #25
0
ファイル: PushService.java プロジェクト: kronik/baasbox
 public void send(String message, String username)
     throws PushNotInitializedException, UserNotFoundException, SqlInjectionException,
         InvalidRequestException, IOException, UnknownHostException {
   if (Logger.isDebugEnabled())
     Logger.debug("Try to send a message (" + message + ") to " + username);
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   ODocument userSystemProperties = user.field(UserDao.ATTRIBUTES_SYSTEM);
   if (Logger.isDebugEnabled()) Logger.debug("userSystemProperties: " + userSystemProperties);
   List<ODocument> loginInfos = userSystemProperties.field(UserDao.USER_LOGIN_INFO);
   if (Logger.isDebugEnabled()) Logger.debug("Sending to " + loginInfos.size() + " devices");
   for (ODocument loginInfo : loginInfos) {
     String pushToken = loginInfo.field(UserDao.USER_PUSH_TOKEN);
     String vendor = loginInfo.field(UserDao.USER_DEVICE_OS);
     if (Logger.isDebugEnabled()) Logger.debug("push token: " + pushToken);
     if (Logger.isDebugEnabled()) Logger.debug("vendor: " + vendor);
     if (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(pushToken)) {
       VendorOS vos = VendorOS.getVendorOs(vendor);
       if (Logger.isDebugEnabled()) Logger.debug("vos: " + vos);
       if (vos != null) {
         IPushServer pushServer = Factory.getIstance(vos);
         pushServer.setConfiguration(getPushParameters());
         pushServer.send(message, pushToken);
       } // vos!=null
     } // (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(deviceId)
   } // for (ODocument loginInfo : loginInfos)
 } // send
コード例 #26
0
ファイル: Scenario.java プロジェクト: pmichna/citygame
 public List<Checkpoint> findNearbyCheckpoints(double longitude, double latitude) {
   List<Checkpoint> nearby = new ArrayList<Checkpoint>();
   Logger.debug("finding checkpoints");
   for (Checkpoint c : checkpoints) {
     Logger.debug("Longitude: " + longitude);
     Logger.debug("Longitude d: " + (c.longitude - longitude));
     Logger.debug(
         "Distance: "
             + (c.longitude - longitude) * (c.longitude - longitude)
             + (c.latitude - latitude) * (c.latitude - latitude));
     if ((c.longitude - longitude) * (c.longitude - longitude)
             + (c.latitude - latitude) * (c.latitude - latitude)
         < 0.0025 * 0.0025) {
       nearby.add(c);
     }
   }
   return nearby;
 }
コード例 #27
0
ファイル: Application.java プロジェクト: hoyajigi/yobi
 private static void makeTestRepository() {
   for (Project project : Project.find.all()) {
     Logger.debug("makeTestRepository: " + project.name);
     try {
       RepositoryService.createRepository(project);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
コード例 #28
0
 void loadUrlMappingsFromFile(String configFile) {
   try {
     Logger.debug("Loading urlMappings from: " + configFile);
     ObjectMapper mapper = new ObjectMapper();
     JsonNode jsonNode = mapper.readTree(readFile(configFile, StandardCharsets.UTF_8));
     urlMatcher = new UrlMatcherImpl(jsonNode);
   } catch (Throwable e) {
     throw new RuntimeException("Error loading mappings from file: " + configFile, e);
   }
 }
コード例 #29
0
 // default visibility for test access
 void loadUrlMappingsFromWS(String wsRequestPath) {
   try {
     Logger.debug("Loading urlMappings from: " + wsRequestPath);
     RestTemplate restTemplate = new RestTemplate();
     JsonNode jsonNode = restTemplate.getForObject(wsRequestPath, JsonNode.class);
     urlMatcher = new UrlMatcherImpl(jsonNode);
   } catch (Throwable e) {
     throw new RuntimeException("Error loading mappings from address: " + wsRequestPath, e);
   }
 }
コード例 #30
0
ファイル: PdfFileUtil.java プロジェクト: nileblack/mnc
  private static void processPage(
      PdfFile file, Document document, int i, int scaleInt, boolean isthumbnail) {
    float scale = scaleInt / 100.0f;
    float rotation = 0f;

    PDimension size = document.getPageDimension(i, rotation, scale);

    // double dpi = Math.sqrt((size.getWidth() * size.getWidth()) +
    // (size.getHeight() * size.getHeight()))
    // / Math.sqrt((8.5 * 8.5) + (11 * 11));
    // if (dpi < (targetDPI - 0.1)) {
    // scale = (float) (targetDPI / dpi);
    size = document.getPageDimension(i, rotation, scale);
    // }

    int pageWidth = (int) (size.getWidth());
    int pageHeight = (int) (size.getHeight());
    BufferedImage image = new BufferedImage(pageWidth, pageHeight, BufferedImage.TYPE_3BYTE_BGR);
    Graphics2D g = image.createGraphics();
    document.paintPage(i, g, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
    g.dispose();
    if (!isthumbnail) {
      String pageImage = getPageImagePath(file, i, scaleInt, isthumbnail);
      ImageUtil.saveJPEG(image, pageImage);
      Logger.debug("Page File Path: %s", pageImage);
    } else {
      String pageThumbnail = getPageImagePath(file, i, scaleInt, isthumbnail);
      BufferedImage thumbnail = ImageUtil.thumbnail(image, 140, 160, false, false);
      ImageUtil.saveJPEG(thumbnail, pageThumbnail);
      Logger.debug("Page Thumbnail Path: %s", pageThumbnail);
      models.Page page = models.Page.find("file= ? and page = ?", file, i).first();
      if (page == null) {
        page = new models.Page();
        page.file = file;
        page.page = i;
      }
      page.content = document.getPageText(i).toString();
      page.width = pageWidth;
      page.height = pageHeight;
      page.save();
    }
    Logger.debug("process page %s", i);
  }