Example #1
0
  @Override
  public void doGet(final HttpServletRequest request, final HttpServletResponse response)
      throws ServletException, IOException {

    // set MIME type and encoding
    response.setContentType("text/html");
    response.setCharacterEncoding("UTF-8");

    // get writer for output
    final PrintWriter p = response.getWriter();

    // make sure that we have obtained an access token, otherwise redirect
    // to login
    final String accessToken = request.getParameter("access_token");
    if (accessToken == null) {
      response.sendRedirect(Config.getValue("LOGIN_URL"));
      return;
    } else {
      // Store the token in a session
      HttpSession session = request.getSession();
      session.setAttribute(Config.getValue("ACCESS_TOKEN_SESSION"), accessToken);
    }

    // get client
    final DefaultFacebookClient client = new DefaultFacebookClient(accessToken);

    // retrieve the document with all friend user ids
    try {

      final URL url =
          new URL(
              "https://api.facebook.com/method/fql.query?access_token="
                  + accessToken
                  + "&query="
                  + URLEncoder.encode(
                      "SELECT name,uid,pic_square FROM user WHERE uid IN ( SELECT uid2 FROM friend WHERE uid1=me() ) ORDER BY name;",
                      "UTF-8"));

      final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      final DocumentBuilder builder = factory.newDocumentBuilder();

      final Document doc = builder.parse(url.openStream());

      // returns an XML tree
      // OutputGenerator.transformToXML(new DOMSource(doc), new
      // StreamResult(p));

      // transform the XML to HTML
      String xslFile = File.separator + "xsl" + File.separator + "facebook.xsl";
      final StreamSource source =
          new StreamSource(new File(this.getServletContext().getRealPath(xslFile)));
      OutputGenerator.transformWithStyle(new DOMSource(doc), source, new StreamResult(p));
    } catch (final Exception e) {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }

    p.flush();
    p.close();
  }
Example #2
0
 @Test
 public void testPropertiesParseUtfKey() throws Exception {
   configFile.setFileContents(
       " gsa.hostname=not_used\n" + "how\\u2202you= i am happy. how are you?\n");
   config.load(configFile);
   assertEquals("i am happy. how are you?", config.getValue("how\u2202you"));
 }
Example #3
0
 @Test
 public void testPropertiesParseKeyEscapedWhitespace() throws Exception {
   configFile.setFileContents(
       " gsa.hostname=not_used\n" + " \\ \\ Tru\\ \\ th\\ \\                   :  Beauty");
   config.load(configFile);
   assertEquals("Beauty", config.getValue("  Tru  th  "));
 }
Example #4
0
 /**
  * Check if we have any value for this option (either set explicitly or some default value). Does
  * not check if the value can be parsed.
  *
  * @param option the option to check.
  * @return true if there is some value available for this option.
  * @see Option#isEnabled(OptionGroup)
  * @see #isSet(Option)
  */
 public boolean hasValue(Option<?> option) {
   if (!containsOption(option)) {
     throw new BadConfigurationError(
         "Option " + option.getKey() + " is not known in group " + prefix);
   }
   String val = config.getValue(getConfigKey(option));
   return val != null || option.getDefaultValue(this) != null;
 }
Example #5
0
 @Test
 public void testPropertiesParseUtfValue() throws Exception {
   configFile.setFileContents(
       " gsa.hostname=not_used\n"
           + "howyou = \\u2202i am happy\\u2202. how are you?\\u2202\\u2202\n");
   config.load(configFile);
   assertEquals("\u2202i am happy\u2202. how are you?\u2202\u2202", config.getValue("howyou"));
 }
Example #6
0
 @Test
 public void testPropertiesParseMultiline() throws Exception {
   configFile.setFileContents(
       " gsa.hostname=not_used\n"
           + "fruits                           apple, banana, pear, \\\n"
           + "                          cantaloupe, watermelon, \\\n"
           + "                          kiwi, mango\n\n");
   config.load(configFile);
   String golden = "apple, banana, pear, cantaloupe, watermelon, kiwi, mango";
   assertEquals(golden, config.getValue("fruits"));
 }
  /**
   * Read all urls of additional nodes stored from the puppet master config, find out node with
   * certain dns and return type of additional node with certain dns. For example: given:
   * $additional_builders =
   * "http://builder2.example.com:8080/builder/internal/builder,http://builder3.example.com:8080/builder/internal/builder"
   * dns = "builder3.example.com" Result = BUILDER
   */
  @Nullable
  public NodeConfig.NodeType recognizeNodeTypeFromConfigBy(String dns) {
    for (Map.Entry<NodeConfig.NodeType, String> entry :
        ADDITIONAL_NODES_CODENVY_PROPERTIES.entrySet()) {
      String additionalNodesProperty = entry.getValue();
      String additionalNodes = config.getValue(additionalNodesProperty);

      if (additionalNodes != null && additionalNodes.contains(dns)) {
        return entry.getKey();
      }
    }

    return null;
  }
Example #8
0
 @Test
 public void testGetValue() {
   config.addKey(
       "somekey",
       "default",
       new Config.ValueComputer() {
         public String compute(String rawValue) {
           assertEquals("default", rawValue);
           return "computed";
         }
       });
   assertEquals("default", config.getRawValue("somekey"));
   assertEquals("computed", config.getValue("somekey"));
 }
Example #9
0
  /**
   * Try to get the value of an option, or its default value. If no value and no default value is
   * available, this returns null, even if the option is not optional.
   *
   * <p>Note that after {@link #checkOptions()} has been called, this method should not throw any
   * errors.
   *
   * @param option the option to query.
   * @param <T> Type of the option
   * @return The value, the default value, or null if no value is available.
   * @throws IllegalArgumentException if the config-value cannot be parsed or is not valid.
   */
  public <T> T tryGetOption(Option<T> option) throws IllegalArgumentException {
    if (!containsOption(option)) {
      throw new BadConfigurationError(
          "Option " + option.getKey() + " is not known in group " + prefix);
    }

    String val = config.getValue(getConfigKey(option));

    if (val == null) {
      return option.getDefaultValue(this);
    } else {
      return option.parse(this, val);
    }
  }
Example #10
0
  public boolean addOneJob(long configID, boolean immediate) {
    ZCDeployJobSchema job = new ZCDeployJobSchema();
    ZCDeployConfigSchema config = new ZCDeployConfigSchema();
    config.setID(configID);
    if (!config.fill()) {
      return false;
    }

    String staticDir =
        Config.getContextRealPath() + Config.getValue("Statical.TargetDir").replace('\\', '/');
    String sourcePath =
        staticDir + "/" + ApplicationPage.getCurrentSiteAlias() + config.getSourceDir();
    job.setID(NoUtil.getMaxID("DeployJobID"));
    job.setConfigID(config.getID());
    job.setSource(sourcePath);
    job.setMethod(config.getMethod());

    String targetDir = config.getTargetDir();
    if (XString.isEmpty(targetDir)) {
      targetDir = "/";
    } else if (!targetDir.endsWith("/")) {
      targetDir = targetDir + "/";
    }

    job.setTarget(targetDir);
    job.setSiteID(config.getSiteID());
    job.setHost(config.getHost());
    job.setPort(config.getPort());
    job.setUserName(config.getUserName());
    job.setPassword(config.getPassword());
    job.setStatus(0L);
    job.setAddTime(new Date());
    job.setAddUser(User.getUserName());

    Transaction trans = new Transaction();
    trans.add(job, OperateType.INSERT);
    if (trans.commit()) {
      if (immediate) {
        executeJob(config, job);
      }
      return true;
    }
    LogUtil.getLogger().info("添加部署任务时,数据库操作失败");
    return false;
  }
Example #11
0
 static {
   for (Config s : EnumSet.allOf(Config.class)) lookup.put(s.getValue(), s);
 }
Example #12
0
  public static void main(String[] args) throws Exception {

    // load main configuration
    String configLoc = System.getProperty(CONFIG_LOCATION_SYS_VAR, CONFIG_LOCATION_DEFAULT);
    System.setProperty(CONFIG_LOCATION_SYS_VAR, configLoc);
    Properties configProps = new Properties();
    try {
      configProps.load(new FileInputStream(ResourceUtils.getFile(configLoc)));
      logger.info("Successfully loaded main configuration.");
    } catch (Exception ex) {
      logger.error("Fail to start in early part", ex);
      throw ex;
    }
    Config config = new Config(configProps);

    // load log4j configuration
    // @todo review the effect and final configuration when -Dlog4j.properties is specified with
    // command line
    String log4jConfigLoc = config.getValue(ItemMeta.BOOTSTRAP_LOG4J_CONFIG_LOCATION);
    if (log4jConfigLoc != null) {
      Properties log4jConfig = new Properties();

      try {
        log4jConfig.load(new FileInputStream(ResourceUtils.getFile(log4jConfigLoc)));
        org.apache.log4j.LogManager.resetConfiguration();
        org.apache.log4j.PropertyConfigurator.configure(log4jConfig);
        logger.info("Successfully loaded log4j configuration at {}", log4jConfigLoc);
      } catch (Exception ex) {
        logger.error("Faile to load specified log4j configuration", ex);
        throw ex;
      }
    }

    ServletContextHandler sch =
        new ServletContextHandler(ServletContextHandler.SECURITY | ServletContextHandler.SESSIONS);

    sch.setContextPath(config.getValue(ItemMeta.ROOT_SERVLET_CONTEXT_PATH));
    sch.getSessionHandler()
        .getSessionManager()
        .setSessionCookie(config.getValue(ItemMeta.ROOT_SERVLET_SESSION_ID));

    ServletHolder dsh = sch.addServlet(DefaultServlet.class, "/");
    dsh.setInitOrder(1);

    ServletHolder jsh = new ServletHolder(JerseySpringServlet.class);
    jsh.setInitParameter(
        JerseySpringServlet.INIT_PARM_SPRING_CONFIG_LOCATION,
        config.getValue(ItemMeta.BOOTSTRAP_SPRING_CONFIG_LOCATION));
    // Refer https://jersey.java.net/apidocs/1.18/jersey/index.html?constant-values.html
    jsh.setInitParameter(JSONConfiguration.FEATURE_POJO_MAPPING, "true");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(
        ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS,
        "com.sun.jersey.api.container.filter.LoggingFilter");
    jsh.setInitParameter(ResourceConfig.FEATURE_TRACE, "true");
    // jsh.setInitParameter(JSONMarshaller.FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_FORMATTED, "true");
    // jsh.setInitParameter(FeaturesAndProperties.FEATURE_XMLROOTELEMENT_PROCESSING, "true");

    sch.addServlet(jsh, config.getValue(ItemMeta.JERSEY_SERVLET_URL_PATTEN));
    jsh.setInitOrder(config.getIntValue(ItemMeta.JERSEY_SERVLET_INIT_ORDER));

    // For more, refer
    // http://download.eclipse.org/jetty/stable-7/apidocs/index.html?org/eclipse/jetty/servlets/CrossOriginFilter.html
    FilterHolder fh = new FilterHolder(CrossOriginFilter.class);
    fh.setName("crossOriginFilter");
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_ORIGINS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_ORIGINS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_METHODS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_METHODS));
    fh.setInitParameter(
        CrossOriginFilter.ALLOWED_HEADERS_PARAM,
        config.getValue(ItemMeta.CROSS_ORIGIN_FILTER_ALLOWED_HEADERS));
    sch.addFilter(fh, "/*", FilterMapping.DEFAULT);

    Server jetty = new Server();
    HandlerList hl = new HandlerList();
    hl.addHandler(sch);
    jetty.setHandler(hl);
    jetty.setThreadPool(
        new QueuedThreadPool(config.getIntValue(ItemMeta.WEB_SERVER_THREAD_POOL_SIZE)));

    SelectChannelConnector conn = new SelectChannelConnector();
    conn.setPort(config.getIntValue(ItemMeta.WEB_SERVER_PORT));
    conn.setMaxIdleTime(config.getIntValue(ItemMeta.WEB_SERVER_MAX_IDLE_TIME));

    MBeanContainer mbc = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    mbc.setDomain(config.getValue(ItemMeta.JMX_DOMAIN) + ".jetty");
    jetty.getContainer().addEventListener(mbc);
    jetty.addBean(mbc);

    jetty.addConnector(conn);
    jetty.setStopAtShutdown(true);

    try {
      jetty.start();
      logger.info("Jetty started at port {} on {}", conn.getPort(), "127.0.0.1");
    } catch (Exception ex) {
      logger.error("Fail to start Jetty.", ex);
      System.exit(-1);
    }
  }
Example #13
0
 public String selectedCommand() {
   return config.getValue(getConfigKey(CMD_KEY));
 }
Example #14
0
  public ZCDeployJobSet getJobs(long siteID, ArrayList list, String operation) {
    ZCDeployJobSet jobSet = new ZCDeployJobSet();
    for (int j = 0; j < list.size(); j++) {
      String srcPath = (String) list.get(j);
      if (XString.isEmpty(srcPath)) {
        continue;
      }
      srcPath = srcPath.replace('\\', '/').replaceAll("///", "/").replaceAll("//", "/");

      String baseDir =
          Config.getContextRealPath() + Config.getValue("Statical.TargetDir").replace('\\', '/');
      baseDir = baseDir + "/" + SiteUtil.getAlias(siteID);

      baseDir = baseDir.replaceAll("///", "/");
      baseDir = baseDir.replaceAll("//", "/");
      srcPath = srcPath.replaceAll(baseDir, "");

      ZCDeployConfigSchema config = new ZCDeployConfigSchema();

      QueryBuilder qb =
          new QueryBuilder(
              " where UseFlag =1 and siteid=? and ? like concat(sourcedir,'%')", siteID, srcPath);
      if (Config.isSQLServer()) {
        qb.setSQL(" where siteid=? and charindex(sourcedir,?)=0");
      }
      if (Config.isDB2()) {
        qb.setSQL(" where siteid=? and locate(sourcedir,'" + srcPath + "')=0");
        qb.getParams().remove(qb.getParams().size() - 1);
      }

      ZCDeployConfigSet set = config.query(qb);

      for (int i = 0; i < set.size(); i++) {
        config = set.get(i);
        String target = config.getTargetDir();
        if (XString.isEmpty(target)) {
          target = "/";
        } else if (!target.endsWith("/")) {
          target = target + "/";
        }

        String filePath = srcPath;
        if (!config.getSourceDir().equals("/")) {
          filePath = srcPath.replaceAll(config.getSourceDir(), "");
        }
        target = dealFileName(target, filePath);

        ZCDeployJobSchema job = new ZCDeployJobSchema();
        job.setID(NoUtil.getMaxID("DeployJobID"));
        job.setConfigID(config.getID());
        job.setSource(baseDir + srcPath);
        job.setMethod(config.getMethod());
        job.setTarget(target);
        job.setSiteID(config.getSiteID());
        job.setHost(config.getHost());
        job.setPort(config.getPort());
        job.setUserName(config.getUserName());
        job.setPassword(config.getPassword());
        job.setRetryCount(0L);
        job.setStatus(0L);
        job.setOperation(operation);
        job.setAddTime(new Date());
        if (User.getCurrent() != null) job.setAddUser(User.getUserName());
        else {
          job.setAddUser("SYS");
        }

        jobSet.add(job);
      }
    }

    return jobSet;
  }
Example #15
0
 @Test
 public void testPropertiesParseEscapeASlash6() throws Exception {
   configFile.setFileContents(" gsa.hostname=not_used\n" + "slash=  \\\\\\\t\\\\\\\f");
   config.load(configFile);
   assertEquals("\\\t\\\f", config.getValue("slash"));
 }
Example #16
0
 @Test
 public void testSimplestPropertiesParse() throws Exception {
   configFile.setFileContents(" \t gsa.hostname \t = feedhost bob\n");
   config.load(configFile);
   assertEquals("feedhost bob", config.getValue("gsa.hostname"));
 }
Example #17
0
 @Test
 public void testPropertiesParseColon2() throws Exception {
   configFile.setFileContents(" gsa.hostname=not_used\n" + " Truth                    :Beauty");
   config.load(configFile);
   assertEquals("Beauty", config.getValue("Truth"));
 }