/**
   * Saves the market configurations : deploy enterprise, username and password
   *
   * @param mkt
   */
  public static void saveMKTConfiguration(@Valid final MKT_Configuration mkt) {
    if (Validation.hasErrors()) {
      flash.error("Please fill in required fields");
      params.flash();
      Validation.keep();
      enable(mkt.getEnterprise_id(), mkt.getEnterprise_name());
    }

    Logger.info("------------------------- INSIDE SAVEMKT()-----------------");
    Logger.info(
        "Enterprise id :  "
            + mkt.getEnterprise_id()
            + " Enterprise Name  :  "
            + mkt.getEnterprise_name()
            + " Deploy username  :  "******" Deploy username  :  "******" Deploy Enterprise  :  "
            + mkt.getDeploy_enterprise_id());

    MKT_Configuration market = new MKT_Configuration();
    market.setEnterprise_id(mkt.getEnterprise_id());
    market.setEnterprise_name(mkt.getEnterprise_name());
    // market.setMkt_deploy_enterprise(mkt.getMkt_deploy_enterprise());
    market.setMkt_deploy_pw(mkt.getMkt_deploy_pw());
    market.setMkt_deploy_user(mkt.getMkt_deploy_user());
    market.setDeploy_enterprise_id(mkt.getDeploy_enterprise_id());
    market.save();
    marketEnable();

    Logger.info("------------------------- EXITING  SAVEMKT()-----------------");
  }
示例#2
0
  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.");
    }
  }
示例#3
0
  /**
   * Creates a new {@link MovieImage}
   *
   * @param movieId
   * @param size
   * @param type
   */
  public static void createMovieImage(
      final Long movieId,
      final EImageSize size,
      final EImageType type,
      final EImageStoreType storeType) {
    final Movie movie = Movie.finder.byId(movieId);
    if (movie == null) {
      if (Logger.isErrorEnabled() == true) {
        Logger.error(
            "Could not fing movie with id: "
                + movieId
                + " for creating a: "
                + MovieImage.class.getName());
      }
      return;
    }

    final MovieImage image = new MovieImage();
    image.movie = movie;
    image.size = size;
    image.type = type;
    image.storeType = storeType;

    image.save();
  }
  /*
   * mongo.local.hostname=localhost
   * mongo.local.port=27017
   * mongo.remote.hostname=
   * mongo.remote.port=25189
   * mongo.remote.username=
   * mongo.remote.password=
   */
  private static DB getDb() {
    String userName = play.Configuration.root().getString("mongo.remote.username");
    String password = play.Configuration.root().getString("mongo.remote.password");
    boolean local = true;

    String localHostName = play.Configuration.root().getString("mongo.local.hostname");
    Integer localPort = play.Configuration.root().getInt("mongo.local.port");

    String remoteHostName = play.Configuration.root().getString("mongo.remote.hostname");
    Integer remotePort = play.Configuration.root().getInt("mongo.remote.port");

    Mongo m;
    DB db = null;
    if (local) {
      String hostname = localHostName;
      int port = localPort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    } else {
      String hostname = remoteHostName;
      int port = remotePort;
      try {
        m = new Mongo(hostname, port);
        db = m.getDB("db");
        boolean auth = db.authenticate(userName, password.toCharArray());
      } catch (Exception e) {
        Logger.error("Exception while intiating Local MongoDB", e);
      }
    }
    return db;
  }
示例#5
0
 public static Result updateGift(String giftId) {
   if (!Utils.checkCredentials(request())) {
     return unauthorized();
   }
   if (!Utils.checkJsonInput(request())) {
     Logger.info("Bad request data for Invite Code " + request().body());
     return generateBadRequest("Bad input json" + request().body());
   }
   Logger.info("Updating Gift Card. GiftId" + giftId);
   Gift gift;
   String giftStatus = "";
   try {
     gift = GiftDAO.getInstance().findGiftById(giftId);
     JsonNode jsonReq = request().body().asJson();
     giftStatus = jsonReq.get("giftStatus").asText();
     gift.setGiftStatus(Gift.GiftStatus.valueOf(giftStatus));
     GiftDAO.getInstance().updateGift(gift);
     Logger.info("Gift Card Updated. GiftId" + giftId);
   } catch (Exception e) {
     Logger.info("Gift Card Update Failed. GiftId" + giftId);
     return generateBadRequest("Invalid Gift Status. Details:" + e);
   }
   // send email to merchant who has challenge with this gift card.
   try {
     if (giftStatus.equals("FUNDED")) {
       EmailService.sendMail(giftId);
     }
   } catch (Exception e) {
     Logger.error("Failed to send Email. GiftId" + giftId);
   }
   return ok(gift.toJson());
 }
  public static void save(long id, String content) {
    try {

      Policy policy =
          Policy.getInstance(
              Play.applicationPath.getAbsolutePath() + "/conf/antisamy-myspace-1.3.xml");
      AntiSamy as = new AntiSamy();
      CleanResults cr = as.scan(content, policy);

      InsConfidential c = InsConfidential.findById(id);
      c.content = cr.getCleanHTML();
      c.save();

      PersonEvaluation.changeMessage(c);

      renderJSON("{\"result\":\"ok\"}");

    } catch (ScanException ex) {

      Logger.error(InsConfidentials.class.getName() + " : " + ex);
      renderJSON("{\"result\":\"ko\"}");
    } catch (PolicyException ex) {

      Logger.error(InsConfidentials.class.getName() + " : " + ex);
      renderJSON("{\"result\":\"ko\"}");
    }
  }
 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()
示例#8
0
  public static synchronized Stack<Evolution> listApplicationEvolutions() {
    Stack<Evolution> evolutions = new Stack<Evolution>();
    evolutions.add(new Evolution(0, "", "", true));
    if (evolutionsDirectory.exists()) {
      for (File evolution : evolutionsDirectory.listFiles()) {
        if (evolution.getName().matches("^[0-9]+[.]sql$")) {
          if (Logger.isTraceEnabled()) {
            Logger.trace("Loading evolution %s", evolution);
          }

          int version =
              Integer.parseInt(evolution.getName().substring(0, evolution.getName().indexOf(".")));
          String sql = IO.readContentAsString(evolution);
          StringBuffer sql_up = new StringBuffer();
          StringBuffer sql_down = new StringBuffer();
          StringBuffer current = new StringBuffer();
          for (String line : sql.split("\r?\n")) {
            if (line.trim().matches("^#.*[!]Ups")) {
              current = sql_up;
            } else if (line.trim().matches("^#.*[!]Downs")) {
              current = sql_down;
            } else if (line.trim().startsWith("#")) {
              // skip
            } else if (!StringUtils.isEmpty(line.trim())) {
              current.append(line).append("\n");
            }
          }
          evolutions.add(new Evolution(version, sql_up.toString(), sql_down.toString(), true));
        }
      }
      Collections.sort(evolutions);
    }
    return evolutions;
  }
示例#9
0
  /**
   * * Creates an entry into the ODocument-Collection and create a new Class named "collectionName"
   *
   * @param collectionName
   * @return
   * @throws Throwable
   */
  public ODocument create(String collectionName) throws Throwable {
    Logger.trace("Method Start");
    try {
      if (existsCollection(collectionName))
        throw new InvalidCollectionException("Collection " + collectionName + " already exists");
    } catch (SqlInjectionException e) {
      throw new InvalidCollectionException(e);
    }
    ODocument doc = super.create();
    doc.field("name", collectionName);
    save(doc);

    // create new class
    OClass documentClass = db.getMetadata().getSchema().getClass(CLASS_NODE_NAME);
    db.getMetadata().getSchema().createClass(collectionName, documentClass);

    // grants to the new class
    ORole registeredRole = RoleDao.getRole(DefaultRoles.REGISTERED_USER.toString());
    ORole anonymousRole = RoleDao.getRole(DefaultRoles.ANONYMOUS_USER.toString());
    registeredRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_ALL);
    registeredRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_ALL);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLASS + "." + collectionName, ORole.PERMISSION_READ);
    anonymousRole.addRule(
        ODatabaseSecurityResources.CLUSTER + "." + collectionName, ORole.PERMISSION_READ);
    PermissionsHelper.grantRead(doc, registeredRole);
    PermissionsHelper.grantRead(doc, anonymousRole);
    Logger.trace("Method End");
    return doc;
  } // getNewModelInstance(String collectionName)
示例#10
0
  public static void serve404(
      NotFound e, ChannelHandlerContext ctx, Request request, HttpRequest nettyRequest) {
    Logger.trace("serve404: begin");
    HttpResponse nettyResponse =
        new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND);
    nettyResponse.setHeader(SERVER, signature);

    nettyResponse.setHeader(CONTENT_TYPE, "text/html");
    Map<String, Object> binding = getBindingForErrors(e, false);

    String format = Request.current().format;
    if (format == null) {
      format = "txt";
    }
    nettyResponse.setHeader(
        CONTENT_TYPE, (MimeTypes.getContentType("404." + format, "text/plain")));

    String errorHtml = TemplateLoader.load("errors/404." + format).render(binding);
    try {
      ChannelBuffer buf = ChannelBuffers.copiedBuffer(errorHtml.getBytes("utf-8"));
      nettyResponse.setContent(buf);
      ChannelFuture writeFuture = ctx.getChannel().write(nettyResponse);
      writeFuture.addListener(ChannelFutureListener.CLOSE);
    } catch (UnsupportedEncodingException fex) {
      Logger.error(fex, "(utf-8 ?)");
    }
    Logger.trace("serve404: end");
  }
  public static void authenticate(String username, String password) {
    Logger.info("Attempting to authenticate with " + username + ":" + password);
    Admin admin = Admin.findByUsername(username);
    if ((admin != null) && (admin.checkPassword(password) == true)) {
      Logger.info("Successfull authentication of " + admin.username);

      /**
       * wanted to put an extra value in session - logged_in_adminid to distinguish an admin, as a
       * user could be logged in and type the route for admin URLs and get into the restricted
       * access areas. By putting a new value in session, it can only be set if an admin is logged
       * in.
       */
      session.put("logged_in_adminid", admin.id);

      /**
       * if login successful, communicate back to AJAX call in adminlogin.js and that will handle
       * the next screen
       */
      JSONObject obj = new JSONObject();
      String value = "correct";
      obj.put("inputdata", value);
      renderJSON(obj);

    } else {
      /**
       * if login unsuccessful, communicate back to AJAX call in adminlogin.js and that will
       * redisplay login.html with error
       */
      Logger.info("Authentication failed");
      JSONObject obj = new JSONObject();
      String value = "Error: Incorrect Email/Password entered.";
      obj.put("inputdata", value);
      renderJSON(obj);
    }
  }
示例#12
0
  protected static void writeResponse(
      ChannelHandlerContext ctx,
      Response response,
      HttpResponse nettyResponse,
      HttpRequest nettyRequest) {
    Logger.trace("writeResponse: begin");
    byte[] content = null;

    final boolean keepAlive = isKeepAlive(nettyRequest);
    if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
      content = new byte[0];
    } else {
      content = response.out.toByteArray();
    }

    ChannelBuffer buf = ChannelBuffers.copiedBuffer(content);
    nettyResponse.setContent(buf);

    if (keepAlive) {
      // Add 'Content-Length' header only for a keep-alive connection.
      Logger.trace("writeResponse: content length [" + response.out.size() + "]");
      setContentLength(nettyResponse, response.out.size());
    }

    ChannelFuture f = ctx.getChannel().write(nettyResponse);

    // Decide whether to close the connection or not.
    if (!keepAlive) {
      // Close the connection when the whole content is written out.
      f.addListener(ChannelFutureListener.CLOSE);
    }
    Logger.trace("writeResponse: end");
  }
示例#13
0
    @Override
    public boolean init() {
      Logger.trace("init: begin");
      Request.current.set(request);
      Response.current.set(response);
      try {
        super.init();
        if (Play.mode == Play.Mode.PROD && staticPathsCache.containsKey(request.path)) {
          RenderStatic rs = null;
          synchronized (staticPathsCache) {
            rs = staticPathsCache.get(request.path);
          }
          serveStatic(rs, ctx, request, response, nettyRequest, event);
          Logger.trace("init: end false");
          return false;
        }
        Router.routeOnlyStatic(request);
      } catch (NotFound nf) {
        serve404(nf, ctx, request, nettyRequest);
        Logger.trace("init: end false");
        return false;
      } catch (RenderStatic rs) {
        if (Play.mode == Play.Mode.PROD) {
          synchronized (staticPathsCache) {
            staticPathsCache.put(request.path, rs);
          }
        }
        serveStatic(rs, ctx, request, response, nettyRequest, this.event);
        Logger.trace("init: end false");
        return false;
      }

      Logger.trace("init: end true");
      return true;
    }
  /**
   * Publish offers per enterprise.
   *
   * @param enterprise_id
   * @param enterprise_name
   */
  public static void publishMarket(final Integer enterprise_id, final String enterprise_name) {
    Logger.info("------------------------- INSIDE publishMarket()-----------------");
    Logger.info("Enterprise_id " + enterprise_id + "Enterprise_name " + enterprise_name);
    String user = session.get("username");
    if (user != null) {
      List<MKT_Configuration> resultSet1 = MarketDAO.getMKTConfiguration(enterprise_id);

      /*
       * check if market is enabled. Publish offers only if market is
       * enabled
       */
      if (resultSet1.size() > 0) {
        List<OfferPurchased> resultSet = ProducerDAO.getSubscribedOffersGroupByServiceLevels();
        Logger.info("ResultSet " + resultSet.size());
        Logger.info("------------------------- EXITING publishMarket()-----------------");
        render(enterprise_id, enterprise_name, resultSet, user);
      } else {
        flash.error(" To continue configure the Market ");
        enable(enterprise_id, enterprise_name);
      }
    } else {
      flash.error("You are not connected.Please Login");
      Login.login_page();
    }
  }
示例#15
0
 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();
   }
 }
        public void run() {

          Logger.info("----Tag.scheduler(): check for new images");
          tagWatchDog(instagram);
          localWatchDog();
          Logger.info("-----------------------------------------");
        } // run
示例#17
0
 private static void crawl() {
   String url = url_tpl + (page++);
   Logger.info("正在抓取:%s", url);
   if (StringUtils.isBlank(url)) return;
   sleep();
   Document doc = Jsoup.parse(WS.url(url).get().body, url);
   Elements elements = doc.select(".video-item");
   if (elements.isEmpty()) return;
   for (Element element : elements) {
     try {
       Element link = element.select(">a").first();
       String cover = link.select("img").first().absUrl("src");
       String coverTitle = link.select(".v-update").first().html();
       String detailUrl = link.absUrl("href");
       String name = element.select(".v-desc .v-title a").first().html();
       Logger.info("正在抓取名称:%s", name);
       Movie movie = Movie.find("byName", name).first();
       if (movie == null) {
         movie = new Movie();
         movie.id = DBCounter.generateUniqueCounter(Movie.class) + "";
       }
       movie.name = name;
       movie.cover = cover;
       movie.cover_title = coverTitle;
       movie.details =
           getDetails(
               movie, "http://video.baidu.com/v?word=" + URLEncoder.encode("美剧 " + name, "GBK"));
       movie.save();
     } catch (Exception e) {
       Logger.error(e.getMessage(), e);
     }
   }
   crawl();
 }
  public static void sendHotImagesToClient(WebSocket.Out<JsonNode> out, String clientId) {
    Logger.info("----Send hot images to client: " + clientId);

    if (hotImages != null) {
      for (int i = 0; i < 4; i++) {
        sendImage(hotImages.get(i), out, "hotImage");
      } // for
    } // if
    //		List<MImages> images = new ArrayList<MImages>();
    //		images = MImages.all();
    //
    //		//find 4 images with the most likes
    //		Collections.sort(images, new Comparator<MImages>() {
    //			public int compare(MImages im1, MImages im2) {
    //		        Long nLikes1 = im1.numberOfLikesIns+im1.numberOfLikesLocall;
    //		        Long nLikes2 = im2.numberOfLikesIns+im2.numberOfLikesLocall;
    //		    	return nLikes1.compareTo(nLikes2);
    //		    }
    //		});
    //
    //		for(int i=images.size()-1; i>images.size()-5; i--){
    //			sendImage(images.get(i), out, "hotImage");
    //		}//for

    // for(MImages image : images) {
    //	Logger.info("		image id: "+image.id+" idIns: "+image.idInstagram+" author:
    // "+image.authorName+" nlikes: "+(image.numberOfLikesIns+image.numberOfLikesLocall));
    // }//for

    Logger.info("-----------------------------");
  } // sendHotImagesToClient
示例#19
0
  public static void create(long personID, String content) {
    try {
      User user = User.loadFromSession();
      Person person = Person.findById(personID);

      Policy policy =
          Policy.getInstance(
              Play.applicationPath.getAbsolutePath() + "/conf/antisamy-myspace-1.3.xml");
      AntiSamy as = new AntiSamy();
      CleanResults cr = as.scan(content, policy);

      InsConfidential c = new InsConfidential();
      c.content = cr.getCleanHTML();
      c.createAt = new GregorianCalendar();
      c.employe = user.person;
      c.person = person;
      c.save();

      flash.success("messageAdded");

      InsConfidentials.show(personID);
    } catch (ScanException ex) {
      Logger.error(InsConfidentials.class.getName() + " : " + ex);
    } catch (PolicyException ex) {
      Logger.error(InsConfidentials.class.getName() + " : " + ex);
    }
  }
  public static void initHotImages() {
    Logger.info("----Init hot images");
    List<MImages> images = new ArrayList<MImages>();

    images = MImages.all();

    // initialize global list that holds 4 top hot images
    hotImages = new ArrayList<MImages>();

    // find 4 images with the most likes
    Collections.sort(
        images,
        new Comparator<MImages>() {
          public int compare(MImages im1, MImages im2) {
            Long nLikes1 = im1.numberOfLikesIns + im1.numberOfLikesLocall;
            Long nLikes2 = im2.numberOfLikesIns + im2.numberOfLikesLocall;
            return nLikes1.compareTo(nLikes2);
          }
        });

    for (int i = images.size() - 1; i > images.size() - 5; i--) {
      hotImages.add(images.get(i));
      Logger.info(
          "		image id: "
              + images.get(i).id
              + " idIns: "
              + images.get(i).idInstagram
              + " author: "
              + images.get(i).authorName
              + " nlikes: "
              + (images.get(i).numberOfLikesIns + images.get(i).numberOfLikesLocall));
    } // for

    Logger.info("-----------------------------");
  } // initHotImages
  public static void showPicasaGallery(Long id, String name) {
    notFoundIfNull(id);
    PicasaGallery gallery = PicasaGallery.findById(id);
    notFoundIfNull(gallery);

    PicasawebService service = new PicasawebService("portfolio");
    List<PhotoEntry> photoEntries = Collections.emptyList();
    try {
      java.net.URL feedUrl = new java.net.URL(gallery.getFeedUrl());

      AlbumFeed feed = service.getFeed(feedUrl, AlbumFeed.class);
      photoEntries = feed.getPhotoEntries();
    } catch (MalformedURLException e) {
      Logger.error("Service URL for Picasa is not well formed");
      e.printStackTrace();
    } catch (IOException e) {
      Logger.error("Error I/O while communicating with Picasa Service");
      e.printStackTrace();
    } catch (ServiceException e) {
      Logger.error("Picasa service error");
      e.printStackTrace();
    }

    List<ImageView> images = new ArrayList<ImageView>();
    for (PhotoEntry entry : photoEntries) {
      ImageView image = new ImageView();
      // We take the largest
      image.thumbnail =
          entry.getMediaThumbnails().get(entry.getMediaThumbnails().size() - 1).getUrl();
      image.url = entry.getMediaContents().get(0).getUrl();
      images.add(image);
    }

    render("Application/gallery.html", images, gallery);
  }
示例#22
0
 public static Route getRoute(
     String method,
     String path,
     String action,
     String params,
     String headers,
     String sourceFile,
     int line) {
   Route route = new Route();
   route.method = method;
   route.path = path.replace("//", "/");
   route.action = action;
   route.routesFile = sourceFile;
   route.routesFileLine = line;
   route.addFormat(headers);
   route.addParams(params);
   route.compute();
   if (Logger.isTraceEnabled()) {
     Logger.trace(
         "Adding ["
             + route.toString()
             + "] with params ["
             + params
             + "] and headers ["
             + headers
             + "]");
   }
   return route;
 }
示例#23
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;
      }
    }
  }
示例#24
0
  /**
   * Method that starts conversation with the caller
   *
   * @return {@link TwiMLResponse} sent over the call
   */
  public static TwiMLResponse getCallStarter(Caller caller) {
    Logger.info("Preparing Greeting message and url.");
    TwiMLResponse twiml = new TwiMLResponse();
    Say say = new Say(TwilioConstants.GREETING);
    say.setVoice(TwilioConstants.FEMALE_USER);

    Gather gather = new Gather();
    gather.setAction(
        "/handle-key/"
            + caller.getDays()
            + "/"
            + caller.getHours()
            + "/"
            + caller.getMinutes()
            + "/"
            + caller.getSeconds()
            + "/");
    gather.setMethod("GET");
    gather.setFinishOnKey("#");
    Say sayInGather = new Say("Please Press a Number.");
    try {
      gather.append(sayInGather);
      twiml.append(say);
      twiml.append(gather);
    } catch (TwiMLException e) {
      Logger.error("Error occured during the Fizz-Buzz generator call: " + e);
    }

    return twiml;
  }
示例#25
0
  @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
  @BodyParser.Of(BodyParser.Json.class)
  public static Result changePassword() {
    Logger.trace("Method Start");
    Http.RequestBody body = request().body();

    JsonNode bodyJson = body.asJson();
    Logger.trace("changePassword bodyJson: " + bodyJson);
    if (bodyJson == null)
      return badRequest(
          "The body payload cannot be empty. Hint: put in the request header Content-Type: application/json");

    // check and validate input
    if (!bodyJson.has("old")) return badRequest("The 'old' field is missing");
    if (!bodyJson.has("new")) return badRequest("The 'new' field is missing");

    String currentPassword = DbHelper.getCurrentHTTPPassword();
    String oldPassword = (String) bodyJson.findValuesAsText("old").get(0);
    String newPassword = (String) bodyJson.findValuesAsText("new").get(0);

    if (!oldPassword.equals(currentPassword)) {
      return badRequest("The old password does not match with the current one");
    }

    UserService.changePasswordCurrentUser(newPassword);
    Logger.trace("Method End");
    return ok();
  }
示例#26
0
  private static boolean callTo(DirectCaller caller) {
    String callFrom = caller.callFrom;
    String callTo = caller.callTo;

    try {

      // Get the account and call factory class
      Account acct = client.getAccount();
      CallFactory callFactory = acct.getCallFactory();

      // build map of post parameters
      Map<String, String> params = new HashMap<String, String>();
      String url = "http://e4fa2e.ngrok.com/v1/twilio/directCall/" + caller.fizzBuzzInput;
      Logger.info("Calling API " + url);
      params.put("From", callFrom);
      params.put("To", callTo);
      params.put("Url", url);
      params.put("Method", "GET");

      // Make a phone call ( This makes a POST request to the Calls
      // resource)
      callFactory.create(params);
    } catch (TwilioRestException e) {
      Logger.error(e.getErrorMessage());
      return false;
    }
    Logger.info("Calling Directly..");
    return true;
  }
示例#27
0
  @Provides(type = Core.Type.SECURITY, with = Core.With.AUTHORIZATION_FAILURE)
  public static Result handleAuthFailure(Node node, String withType, Map<String, Object> args)
      throws NodeLoadException, ModuleException {

    User user = SecurityEventGenerator.triggerCurrentUserInterceptor();
    SecurityEventGenerator.triggerBeforeAuthorizationFailure(user);

    try {
      String unauthorizedPage = Settings.load().getValue(CoreSettingsHelper.Keys.UNAUTHORIZED_PAGE);
      try {
        if (StringUtils.isNotBlank(unauthorizedPage)) {
          Content content = CoreLoader.loadAndDecorateNode(unauthorizedPage, 0);
          if (user != null) {
            return Controller.forbidden(content);
          } else {
            return Controller.unauthorized(content);
          }
        }
      } catch (NodeNotFoundException | NodeLoadException | ModuleException e) {
        ExceptionUtil.assertExceptionHandling(e);
        return CoreLoader.redirectToPageLoadErrorPage();
      }

      if (user != null) {
        Logger.warn("Using fallback forbidden handling, sending 403 with no content");
        return Controller.forbidden();
      } else {
        Logger.warn("Using fallback unauthorized handling, sending 401 with no content");
        return Controller.unauthorized();
      }
    } finally {
      SecurityEventGenerator.triggerAfterAuthorizationFailure(user);
    }
  }
  /**
   * Saves user response.
   *
   * <p>This action builds a Response object from request by creating and parsing DynamicForm data.
   * Built Response object is then validated and returned back to client as a JSON object.
   *
   * <p>If response object is not valid - returns BAD_REQUEST status code to client as well as JSON
   * object with validation errors.
   *
   * <p>If response data is outdated - returns BAD_REQUEST status code to client as well as JSON
   * object with global errors.
   *
   * <p>This action requires CSRF token.
   *
   * @return 200-OK with saved response object as JSON 400-BAD_REQUEST with errors as JSON
   */
  @RequireCSRFCheck
  @Transactional
  public Result createResponse() {
    DynamicForm form = form().bindFromRequest();
    List<Field> activeFields = fieldService.getAllActiveFields();

    Response response = new Response(form.data(), activeFields);
    Logger.info("User send response: {}.", response);
    List<ValidationError> errors = response.validate();
    if (errors != null) {
      errors.forEach(form::reject);
      Logger.warn("User response contains validation errors: {}.", errors);
      return badRequest(form.errorsAsJson());
    }

    Response result = responseService.saveResponse(response);

    if (result == null) {
      form.reject("global", "Some options are outdated!");
      Logger.warn("Users response contains outdated data.");
      return badRequest(form.errorsAsJson());
    } else {
      Logger.info("Response saved: {}.", response);
      return ok(toJson(response));
    }
  }
示例#29
0
 /**
  * Uploads a license file. This is restricted to admin users.
  *
  * @param licenseFile the license file.
  */
 @Restrictions({
   @Restrict({"SYSTEM_ADMIN", "SECURITY_ADMIN"}),
   @Restrict({"RESTRICTED_SYSTEM_ADMIN", "RESTRICTED_SECURITY_ADMIN"})
 })
 public static void upload(@Required File licenseFile) {
   if (Validation.hasErrors()) {
     params.flash();
     Validation.keep();
     license();
   }
   try {
     String license = FileUtils.readFileToString(licenseFile);
     if (StringUtils.isBlank(license)) {
       Logger.error("License file is empty");
       Validation.addError("setup.licenseFile", MessagesUtils.get("license.uploadFailed"));
       params.flash();
       Validation.keep();
       license();
     }
     LicenseUtils.updateLicenseText(license);
     index();
   } catch (IOException e) {
     Validation.addError("setup.licenseFile", MessagesUtils.get("license.uploadFailed"));
     Logger.error(e, "Failed to read license file");
     Validation.keep();
     license();
   }
 }
  /**
   * Saves the market configurations : deploy enterprise, username and password
   *
   * @param mkt
   */
  public static void enableMKTConfiguration(
      final Integer enterprise_id, final String enterprise_name) {
    if (Validation.hasErrors()) {
      flash.error("Please fill in required fields");
      params.flash();
      Validation.keep();
      enable(enterprise_id, enterprise_name);
    }

    Logger.info("------------------------- INSIDE SAVEMKT()-----------------");
    Logger.info("Enterprise id :  " + enterprise_id + " Enterprise Name  :  " + enterprise_name);

    String user = session.get("username");
    String password = session.get("password");

    MKT_Configuration market = new MKT_Configuration();
    market.setEnterprise_id(enterprise_id);
    market.setEnterprise_name(enterprise_name);
    // market.setMkt_deploy_enterprise(mkt.getMkt_deploy_enterprise());
    market.setMkt_deploy_pw(password);
    market.setMkt_deploy_user(user);
    market.setDeploy_enterprise_id(enterprise_id);
    market.save();
    marketEnable();

    Logger.info("------------------------- EXITING  SAVEMKT()-----------------");
  }