Пример #1
0
  protected String cleanseValue(String value) {
    value = StringUtils.trim(value);
    value = StringUtils.removeStart(value, "'");
    value = StringUtils.removeStart(value, "\"");
    value = StringUtils.removeEnd(value, "\"");
    value = StringUtils.removeEnd(value, "'");
    value = StringUtils.trim(value);

    return value;
  }
Пример #2
0
  public static File convertRpmToZip(File file) throws Exception {
    LOG.info("File: " + file.getAbsolutePath());

    FileInputStream fis = new FileInputStream(file);
    ReadableChannelWrapper in = new ReadableChannelWrapper(Channels.newChannel(fis));

    InputStream uncompressed = new GZIPInputStream(fis);
    in = new ReadableChannelWrapper(Channels.newChannel(uncompressed));

    String rpmZipName = file.getName();
    rpmZipName = StringUtils.replace(rpmZipName, ".", "-");
    rpmZipName = rpmZipName + ".zip";
    String rpmZipPath = FilenameUtils.getFullPath(file.getAbsolutePath());

    File rpmZipOutput = new File(rpmZipPath + File.separator + rpmZipName);
    LOG.info("Converting RPM: " + file.getName() + " to ZIP: " + rpmZipOutput.getName());
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(rpmZipOutput));

    String rpmName = file.getName();
    rpmName = StringUtils.replace(rpmName, ".", "-");

    CpioHeader header;
    int total = 0;
    do {
      header = new CpioHeader();
      total = header.read(in, total);

      if (header.getFileSize() > 0) {
        BoundedInputStream bis = new BoundedInputStream(uncompressed, header.getFileSize());

        String relPath = FilenameUtils.separatorsToSystem(header.getName());
        relPath = StringUtils.removeStart(relPath, ".");
        relPath = StringUtils.removeStart(relPath, "/");
        relPath = rpmName + File.separator + relPath;
        relPath = StringUtils.replace(relPath, "\\", "/");

        ZipEntry zipEntry = new ZipEntry(relPath);
        zos.putNextEntry(zipEntry);
        IOUtils.copy(bis, zos);
      } else {
        final int skip = header.getFileSize();
        if (uncompressed.skip(skip) != skip) throw new RuntimeException("Skip failed.");
      }

      total += header.getFileSize();
    } while (!header.isLast());

    zos.flush();
    zos.close();

    return rpmZipOutput;
  }
 @Override
 protected void doPerModuleVersioning(StaplerRequest req) {
   releaseVersionPerModule = Maps.newHashMap();
   nextVersionPerModule = Maps.newHashMap();
   Enumeration params = req.getParameterNames();
   while (params.hasMoreElements()) {
     String key = (String) params.nextElement();
     if (key.startsWith("release.")) {
       releaseVersionPerModule.put(
           StringUtils.removeStart(key, "release."), req.getParameter(key));
     } else if (key.startsWith("next.")) {
       nextVersionPerModule.put(StringUtils.removeStart(key, "next."), req.getParameter(key));
     }
   }
 }
 private static String[] getOutputArgs(String[] args) {
   ArrayList<String> l = new ArrayList<String>();
   for (String arg : args) {
     if (arg.startsWith("-a")) l.add(StringUtils.removeStart(arg, "-a"));
   }
   return l.toArray(new String[l.size()]);
 }
Пример #5
0
  /**
   * convert email address mapping<br>
   * <code>user-</code> will be replace by the email address of the user as stored in the user
   * repository <code>group-</code> will
   */
  public String convertEmailList(String mailTo) {
    StringBuffer ret = new StringBuffer();
    String[] list = mailTo.split(";");
    if (list == null) {
      return "";
    }
    for (int i = 0; i < list.length; i++) { // for each item
      String userName = list[i];
      if (i != 0) {
        ret.append("\n");
      }
      if (userName.startsWith(MailConstants.PREFIX_USER)) {
        userName = StringUtils.removeStart(userName, MailConstants.PREFIX_USER);
        if (log.isDebugEnabled()) {
          log.debug("username =" + userName);
        }
        ret.append(getUserMail(userName));
      } else if (userName.startsWith(MailConstants.PREFIX_GROUP)) {

      } else if (userName.startsWith(MailConstants.PREFIX_ROLE)) {

      } else {
        // none of the above, just add the mail to the list
        ret.append(userName);
      }
    }
    return ret.toString();
  }
 protected Document filterAndAssertOutput(
     String input, Map<String, String> cleaningParameters, String expectedOuput) {
   Document document = filter(input, cleaningParameters);
   String output = XMLUtils.serialize(document, false);
   output = StringUtils.removeStart(output, "<root>");
   output = StringUtils.removeEnd(output, "</root>");
   Assert.assertEquals(expectedOuput, output);
   return document;
 }
Пример #7
0
  /**
   * Executes this script node if necessary and/or possible.
   *
   * @param executeIfDeferred if <tt>false</tt>, and we are emulating IE, and the <tt>defer</tt>
   *     attribute is defined, the script is not executed
   */
  void executeScriptIfNeeded() {
    if (!isExecutionNeeded()) {
      return;
    }

    final HtmlPage page = (HtmlPage) getPage();
    final BrowserVersion browser = page.getWebClient().getBrowserVersion();

    final String src = getSrcAttribute();
    if (src.equals(SLASH_SLASH_COLON)) {
      return;
    }

    if (src != ATTRIBUTE_NOT_DEFINED) {
      if (src.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        // <script src="javascript:'[code]'"></script>
        if (browser.hasFeature(BrowserVersionFeatures.HTMLSCRIPT_SRC_JAVASCRIPT)) {
          String code =
              StringUtils.removeStart(src, JavaScriptURLConnection.JAVASCRIPT_PREFIX).trim();
          final int len = code.length();
          if (len > 2) {
            if ((code.charAt(0) == '\'' && code.charAt(len - 1) == '\'')
                || (code.charAt(0) == '"' && code.charAt(len - 1) == '"')) {
              code = code.substring(1, len - 1);
              if (LOG.isDebugEnabled()) {
                LOG.debug("Executing JavaScript: " + code);
              }
              page.executeJavaScriptIfPossible(code, code, getStartLineNumber());
            }
          }
        }
      } else {
        // <script src="[url]"></script>
        if (LOG.isDebugEnabled()) {
          LOG.debug("Loading external JavaScript: " + src);
        }
        try {
          final JavaScriptLoadResult result =
              page.loadExternalJavaScriptFile(src, getCharsetAttribute());
          if (result == JavaScriptLoadResult.SUCCESS) {
            executeEventIfBrowserHasFeature(
                Event.TYPE_LOAD, BrowserVersionFeatures.EVENT_ONLOAD_EXTERNAL_JAVASCRIPT);
          } else if (result == JavaScriptLoadResult.DOWNLOAD_ERROR) {
            executeEventIfBrowserHasFeature(
                Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT);
          }
        } catch (final FailingHttpStatusCodeException e) {
          executeEventIfBrowserHasFeature(
              Event.TYPE_ERROR, BrowserVersionFeatures.EVENT_ONERROR_EXTERNAL_JAVASCRIPT);
          throw e;
        }
      }
    } else if (getFirstChild() != null) {
      // <script>[code]</script>
      executeInlineScriptIfNeeded();
    }
  }
Пример #8
0
  public Collection getOrCreateCollection(String path) throws XMLDBException {
    path = StringUtils.removeStart(path, "/");
    path = StringUtils.removeEnd(path, "/");
    path = path.replaceAll("[/]+", "/");

    String pathWithURI = uri + path;

    Collection col = DatabaseManager.getCollection(pathWithURI, userName, password);

    if (col != null) {
      return col;
    } else {
      synchronized (syncLock) {
        col = DatabaseManager.getCollection(pathWithURI, userName, password);
        if (col != null) {
          return col;
        }
        String[] paths = path.split("/");

        String[] parentPath = (String[]) ArrayUtils.remove(paths, paths.length - 1);

        this.getOrCreateCollection(StringUtils.join(parentPath, '/'));

        CollectionManagementService mgt = this.getCollectionManagementService();

        col = mgt.createCollection(StringUtils.join(paths, '/'));

        // If we are creating a new root collection, we need to set up the indexing configuration
        // for this collection,
        // which is done by placing a collection.xconf file into the config path structure.
        if (paths.length == 1 && getCollectionRoot().endsWith(paths[0])) {
          log.info("Configuring Indexes for Collection " + paths[0]);
          // Add the index configuration file for our root config
          try {
            String confFilePath = "/collection.xconf";
            String confFileXml =
                IOUtils.toString(this.getClass().getResourceAsStream(confFilePath), "UTF-8");
            Collection configCol = getOrCreateCollection("/system/config/db/" + paths[0]);
            org.xmldb.api.base.Resource r =
                configCol.createResource("collection.xconf", "XMLResource");
            r.setContent(confFileXml);
            configCol.storeResource(r);
            log.info(
                "Wrote index configuration " + r.getParentCollection().getName() + "/" + r.getId());
          } catch (Exception e) {
            log.error(
                "Failure configuring indexes for collection "
                    + paths[0]
                    + " - indexes will not be available!",
                e);
          }
        }
        return col;
      }
    }
  }
Пример #9
0
 /**
  * Only if the path template starts with the datadir, return a path relative to it, otherwise
  * return an absolute path.
  */
 protected String getFilePathRelativeToDataDirIfPossible() {
   String template = getFilePathTemplate();
   if (StringUtils.startsWith(template, "$datadir$")) {
     template = StringUtils.replace(template, "$datadir$", "");
     template = StringUtils.removeStart(template, "/");
   } else {
     template = substituteDatadir(template);
   }
   return substituteScan(template);
 }
 private P2Repo resolveLocalP2RepoFromUrl(String url) {
   String rpp = StringUtils.removeStart(url, "local://");
   // rpp = rpp.substring(0, rpp.indexOf('/'));
   RepoPath repoPath = RepoPathFactory.create(rpp);
   LocalRepoDescriptor localRepoDescriptor =
       centralConfig.getMutableDescriptor().getLocalRepositoriesMap().get(repoPath.getRepoKey());
   if (localRepoDescriptor != null) {
     return new P2Repo(null, repoPath.getRepoKey(), url);
   }
   return null;
 }
Пример #11
0
 private static String getOutputDir(String[] args) {
   String outputDir = null;
   for (String arg : args) {
     if (arg.startsWith("-o")) {
       outputDir = StringUtils.removeStart(arg, "-o");
       break;
     }
   }
   if (outputDir == null) outputDir = new File("").getAbsolutePath();
   return outputDir;
 }
 @Override
 public String getBranchName(String branch) {
   String value = branch;
   for (String prefix : configuration.getBranchNamePrefixes()) {
     value = StringUtils.removeStart(value, prefix);
   }
   // Normalisation
   value = Configuration.normalise(value);
   // Evaluation
   return evaluate(configuration.getBranchNameExpression(), "branch", value);
 }
Пример #13
0
  /**
   * Gets the relative path of a file contained in the project. <br>
   * For example, if the visual studio project is C:/MySolution/MyProject/MyProject.csProj and the
   * file is C:/MySolution/MyProject/Dummy/Foo.cs, then the result is Dummy/Foo.cs
   *
   * @param file the file whose relative path is to be computed
   * @return the relative path, or <code>null</code> if the file is not in the project
   *     subdirectories
   */
  public String getRelativePath(File file) {
    File canonicalDirectory;
    try {
      canonicalDirectory = directory.getCanonicalFile();

      File canonicalFile = file.getCanonicalFile();

      String filePath = canonicalFile.getPath();
      String directoryPath = canonicalDirectory.getPath();
      if (!filePath.startsWith(directoryPath)) {
        // The file is not in the directory
        return null;
      }
      return StringUtils.removeStart(StringUtils.removeStart(filePath, directoryPath), "\\");
    } catch (IOException e) {
      if (LOG.isDebugEnabled()) {
        LOG.debug("io exception with file " + file, e);
      }
      return null;
    }
  }
 public static String sanitize(String mavenArtifactId) {
   String key = mavenArtifactId;
   if (StringUtils.startsWith(mavenArtifactId, SONAR_PREFIX)
       && StringUtils.endsWith(mavenArtifactId, PLUGIN_SUFFIX)) {
     key =
         StringUtils.removeEnd(
             StringUtils.removeStart(mavenArtifactId, SONAR_PREFIX), PLUGIN_SUFFIX);
   } else if (StringUtils.endsWith(mavenArtifactId, SONAR_PLUGIN_SUFFIX)) {
     key = StringUtils.removeEnd(mavenArtifactId, SONAR_PLUGIN_SUFFIX);
   }
   return keepLettersAndDigits(key);
 }
Пример #15
0
  private static Output createOutput(String[] args) {
    String outputClass = null;
    for (String arg : args) {
      if (arg.startsWith("-c")) {
        outputClass = StringUtils.removeStart(arg, "-c");
        break;
      }
    }
    if (outputClass == null) outputClass = XmlOutput.class.getName();

    return (Output) ClassHelper.newInstance(outputClass);
  }
Пример #16
0
 @Override
 public RootContainer<String, IRepositoryViewObject> getTdqRepositoryViewObjects(
     Project project, ERepositoryObjectType type, String folderName, boolean[] options)
     throws PersistenceException {
   String relativeFolder = folderName;
   if (type != null && type.hasFolder()) {
     // Compatible to the existing behavior which keep the full path relative to the project in DQ.
     String baseFolder = ERepositoryObjectType.getFolderName(type);
     relativeFolder = StringUtils.removeStart(relativeFolder, baseFolder);
   }
   return getObjectFromFolder(
       project, type, relativeFolder, OPTION_ONLY_LAST_VERSION | OPTION_DYNAMIC_OBJECTS);
 }
Пример #17
0
  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    final HttpServletRequest servletRequest = (HttpServletRequest) request;

    String requestURI = servletRequest.getRequestURI();
    requestURI =
        StringUtils.removeStart(
            requestURI, servletRequest.getContextPath() + servletRequest.getServletPath());
    String baseURL = StringUtils.removeEnd(servletRequest.getRequestURL().toString(), requestURI);

    Map<String, List<String>> headersMap = new HashMap<>();
    Enumeration<String> headerNames = servletRequest.getHeaderNames();
    if (headerNames != null) {
      while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        List<String> valuesList = Collections.list(servletRequest.getHeaders(headerName));
        headersMap.put(headerName, valuesList);
      }
    }

    RequestContext ctx;
    Principal userPrincipal = servletRequest.getUserPrincipal();
    if (userPrincipal != null) {
      ctx =
          new RequestContext(
              baseURL,
              servletRequest.getRequestURI(),
              servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER),
              userPrincipal,
              headersMap);
    } else {
      ctx =
          new RequestContext(
              baseURL,
              servletRequest.getRequestURI(),
              servletRequest.getHeader(RequestContext.HATEOAS_OPTIONS_HEADER),
              headersMap);
    }

    RequestContext.setRequestContext(ctx);

    try {
      chain.doFilter(request, response);
    } finally {
      RequestContext.clearRequestContext();
    }
  }
  protected void process(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    //        L.trace("begin process");
    String url =
        StringUtils.removeStart(
            StringUtils2.joinIgnoreNull(req.getServletPath(), req.getPathInfo()), "/");
    if (processDocument(url, req, resp)) return;

    Invoker invoker = invokers.get(url);
    if (invoker != null) {
      invoker.invoke(req, resp);
    } else {
      resp.setStatus(404); // Not Found
    }
    //        L.trace("end process");
  }
Пример #19
0
  @Override
  protected String baseIntercept(
      ActionInvocation invoke, HttpServletRequest req, HttpServletResponse resp) throws Exception {
    // TODO Auto-generated method stub

    /**
     * This interceptor is used for urls invoked using SEO type urls The system is configured to
     * support /category/category-name /product/product-name /pagelink/page-name
     */

    // get the product from the path
    String path = StringUtils.removeStart(req.getRequestURI(), req.getContextPath());

    /**
     * should have left /category/<PRODUCT-URL>?request parameters or should have left
     * /pagelink/<PAGE-URL>?request parameters or should have left /product/<PRODUCT-URL>?request
     * parameters keep after second / and before ?
     */

    // remove /product or /category or /page
    String pathnocontext = path.substring(1); // remove /

    // should now have product/<PRODUCT-ID>?request parameters or
    // category/<CATEGORY-ID>?request parameters or pagelink/<PAGE-ID>
    String[] parameters = pathnocontext.split("/");

    // should now have
    // parameters[0] = product or category or pagelink
    // parameters[1] = <PRODUCT-ID>?parameters

    if (parameters == null || parameters.length == 1) {
      throw new Exception("Invalid parameters in request " + path);
    }

    String id = parameters[1];

    if (id.contains(".action")) {
      id = id.substring(0, id.indexOf(".action"));
    }

    SalesManagerBaseAction action = ((SalesManagerBaseAction) invoke.getAction());

    action.setRequestedEntityId(id);

    return null;
  }
Пример #20
0
  public User getUserDataFromFacebook(String faceCode, HttpServletRequest request) {
    User user = new User();
    String token = null;
    if (faceCode != null && !"".equals(faceCode)) {
      String redirectUrl =
          request.getScheme()
              + "://"
              + request.getServerName()
              + ":"
              + request.getServerPort()
              + request.getContextPath()
              + "/socialSignUp";
      String newUrl =
          "https://graph.facebook.com/oauth/access_token?client_id="
              + APP_ID
              + "&redirect_uri="
              + redirectUrl
              + "&client_secret="
              + APP_SECRET
              + "&code="
              + faceCode;

      HttpClient httpclient = new DefaultHttpClient();
      try {
        String responseBody = "";
        HttpGet httpget = new HttpGet(newUrl);
        HttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        responseBody = EntityUtils.toString(entity);
        token =
            StringUtils.removeEnd(
                StringUtils.removeStart(responseBody, "access_token="), "&expires=5180795");
      } catch (ClientProtocolException e) {
        log.error(e);
      } catch (IOException e) {
        log.error(e);
      } finally {
        httpclient.getConnectionManager().shutdown();
      }
    }

    user = getUserFromJsonResponse(token);
    return user;
  }
Пример #21
0
  public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
      throws ServletException, IOException {
    if (!authenticate(request, response)) {
      return;
    }

    final String msgId = StringUtils.removeStart(request.getRequestPathInfo().getSuffix(), "/");
    if (StringUtils.isBlank(msgId)) {
      throw new ServletException("No suffix found");
    }
    if (!sentMessages.contains(msgId)) {
      throw new ServletException("No one is waiting for confirmation for " + msgId);
    } else {
      receivedConfirmations.add(msgId);
      synchronized (receivedConfirmations) {
        receivedConfirmations.notifyAll();
      }
      response.getWriter().append("Message " + msgId + " confirmed");
      LOG.debug("Message " + msgId + " confirmed");
    }
  }
  /**
   * Return string array containing the paths in the view that should be used when polling for
   * changes.
   *
   * @param variableResolver TODO
   * @param build TODO
   * @param launcher TODO
   * @return string array that will be used by the lshistory command and for constructing the config
   *     spec, etc.
   * @throws InterruptedException
   * @throws IOException
   */
  public String[] getViewPaths(
      VariableResolver<String> variableResolver, AbstractBuild build, Launcher launcher)
      throws IOException, InterruptedException {
    String loadRules = getLoadRules();
    if (StringUtils.isBlank(loadRules)) {
      return null;
    }

    String[] rules = loadRules.split("[\\r\\n]+");
    for (int i = 0; i < rules.length; i++) {
      String rule = rules[i];
      // Remove "load " from the string, just in case.
      rule = StringUtils.removeStart(rule, "load ");
      // Remove "\\", "\" or "/" from the load rule. (bug#1706) Only if
      // the view is not dynamic
      // the user normally enters a load rule beginning with those chars
      rule = StringUtils.stripStart(rule, "\\/");
      rules[i] = rule;
    }
    return rules;
  }
Пример #23
0
  protected void process(HttpServletRequest hreq, HttpServletResponse hresp)
      throws ServletException, IOException {
    Request req = createRequest(hreq, hresp);
    if (L.isDebugEnabled()) L.debug(null, req.toString());

    Response resp = createResponse(hreq, hresp);
    try {
      fireBeforeAll(req, resp);
      if (routeSummary
          && "$"
              .equals(StringUtils.removeStart(StringUtils.trimToEmpty(hreq.getPathInfo()), "/"))) {
        resp.body(RawText.of(makeRouteSummary()));
        resp.type("text/plain");
      } else {
        invokeAllMatched(before, req, resp);
        boolean matched = invokeFirstMatched(routes, req, resp);
        invokeAllMatched(after, req, resp);
        if (!matched) TopazHelper.halt(404, "Route error");

        if (L.isDebugEnabled()) L.debug(null, "ok");
      }
      fireSuccess(req, resp);
    } catch (Throwable t) {
      fireExceptionCaught(req, resp, t);
      Throwable c =
          (t instanceof InvocationTargetException)
              ? ((InvocationTargetException) t).getTargetException()
              : t;
      if (!(c instanceof QuietHaltException)) resp.error(c);

      L.warn(null, c, "error");
    } finally {
      fireBeforeOutput(req, resp);
      resp.doOutput(Response.OutputOptions.fromRequest(req));
      fireAfterOutput(req, resp);
      req.deleteUploadedFiles();
      fireAfterAll(req, resp);
      if (L.isDebugEnabled()) L.debug(null, "complete");
    }
  }
Пример #24
0
  /**
   * Finds directories and files within a given directory and its subdirectories.
   *
   * @param classLoader
   * @param rootPath the root directory, for example org/sonar/sqale, or a file in this root
   *     directory, for example org/sonar/sqale/index.txt
   * @param
   * @return a list of relative paths, for example {"org/sonar/sqale", "org/sonar/sqale/foo",
   *     "org/sonar/sqale/foo/bar.txt}. Never null.
   */
  public static Collection<String> listResources(
      ClassLoader classLoader, String rootPath, Predicate<String> predicate) {
    String jarPath = null;
    JarFile jar = null;
    try {
      Collection<String> paths = Lists.newArrayList();
      rootPath = StringUtils.removeStart(rootPath, "/");

      URL root = classLoader.getResource(rootPath);
      if (root != null) {
        checkJarFile(root);

        // Path of the root directory
        // Examples :
        // org/sonar/sqale/index.txt  -> rootDirectory is org/sonar/sqale
        // org/sonar/sqale/  -> rootDirectory is org/sonar/sqale
        // org/sonar/sqale  -> rootDirectory is org/sonar/sqale
        String rootDirectory = rootPath;
        if (StringUtils.substringAfterLast(rootPath, "/").indexOf('.') >= 0) {
          rootDirectory = StringUtils.substringBeforeLast(rootPath, "/");
        }
        jarPath =
            root.getPath().substring(5, root.getPath().indexOf("!")); // strip out only the JAR file
        jar = new JarFile(URLDecoder.decode(jarPath, CharEncoding.UTF_8));
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
          String name = entries.nextElement().getName();
          if (name.startsWith(rootDirectory) && predicate.apply(name)) {
            paths.add(name);
          }
        }
      }
      return paths;
    } catch (Exception e) {
      throw Throwables.propagate(e);
    } finally {
      closeJar(jar, jarPath);
    }
  }
Пример #25
0
 @CheckForNull
 @Override
 protected SCMRevision retrieve(@NonNull SCMHead head, @NonNull TaskListener listener)
     throws IOException, InterruptedException {
   String cacheEntry = getCacheEntry();
   Lock cacheLock = getCacheLock(cacheEntry);
   cacheLock.lock();
   try {
     File cacheDir = getCacheDir(cacheEntry);
     Git git =
         Git.with(listener, new EnvVars(System.getenv()))
             .in(cacheDir)
             .using(GitTool.getDefaultInstallation().getGitExe());
     GitClient client = git.getClient();
     client.addDefaultCredentials(getCredentials());
     if (!client.hasGitRepo()) {
       listener.getLogger().println("Creating git repository in " + cacheDir);
       client.init();
     }
     String remoteName = getRemoteName();
     listener.getLogger().println("Setting " + remoteName + " to " + getRemote());
     client.setRemoteUrl(remoteName, getRemote());
     listener.getLogger().println("Fetching " + remoteName + "...");
     List<RefSpec> refSpecs = getRefSpecs();
     client.fetch(remoteName, refSpecs.toArray(new RefSpec[refSpecs.size()]));
     // we don't prune remotes here, as we just want one head's revision
     for (Branch b : client.getRemoteBranches()) {
       String branchName = StringUtils.removeStart(b.getName(), remoteName + "/");
       if (branchName.equals(head.getName())) {
         return new SCMRevisionImpl(head, b.getSHA1String());
       }
     }
     return null;
   } finally {
     cacheLock.unlock();
   }
 }
Пример #26
0
  public List<V> getRelaxedValue(final String sourceKey, final String[] keywordPrecedence) {
    // TODO - lookup in the relaxed map, based on the keyword precedence

    String baseLine = null;

    for (final String altKeyword : keywordPrecedence) {

      baseLine = StringUtils.removeStart(sourceKey, altKeyword);
      if (!baseLine.equals(sourceKey)) {
        break;
      }
    }

    List<V> vals = null;
    for (final String altKeyword : keywordPrecedence) {

      vals = get(altKeyword + baseLine);
      if (!vals.isEmpty()) {
        break;
      }
    }

    return vals;
  }
Пример #27
0
  @Override
  public Pair<Pair<String, Long>, List<WeiboContent>> read() throws Exception {
    Long txFollowerId = follower.getSeqId();
    OAuth oauth = TencentOAuthCache.getOAuth(txFollowerId, true);

    if (oauth == null) {
      log.info("no tx oauth,please check it " + txFollowerId);
      throw new Exception("no tencent cache");
    }

    String lastId = follower.getLastId();
    Long lastTimeStamp = follower.getLastTimeStamp();

    String response =
        statusesApi.broadcast_timeline(
            oauth,
            WeiBoConst.ResultType.ResultType_Json,
            "2",
            lastTimeStamp != null ? lastTimeStamp.toString() : "0",
            "100",
            lastId != null ? lastId.toString() : "0",
            "0",
            "0",
            "1");

    log.info("TencentWeiboServiceImpl.read() " + response);

    Object jsonObject = new JSONObject(response).getString("data");

    List<WeiboContent> weiboContents = null;

    if (jsonObject != null && !"null".equals(jsonObject)) {
      JSONArray txWeiboArray = new JSONObject(response).getJSONObject("data").getJSONArray("info");

      int size = txWeiboArray.length();

      if (size > 0) {
        weiboContents = new ArrayList<WeiboContent>(size);

        for (int i = 0; i < size; i++) {
          JSONObject json = (JSONObject) txWeiboArray.get(i);
          String weiboId = json.getString("id");
          String image = json.getString("image");
          if (!StringUtils.isBlank(image)) {
            if ("null".equalsIgnoreCase(image)) {
              image = null;
            } else {
              image =
                  StringUtils.removeEnd(StringUtils.removeStart(image, "[\""), "\"]")
                      + "/2000"; // big image.
            }
          }

          if (!syncRecordService.isSynchronized(txFollowerId, weiboId)) {
            weiboContents.add(
                new WeiboContent(
                    weiboId, json.getString("origtext"), image, json.getLong("timestamp")));
          } else {
            log.info("skip weibo " + json);
          }
        }

        // // asc sort weibo content by id.
        // Collections.sort(weiboContents);
        // lastId = max = last list

        if (weiboContents.size() > 0) {
          // lastId = last list
          WeiboContent lastWeiboContent = weiboContents.get(weiboContents.size() - 1);
          lastId = lastWeiboContent.getId() + "";
          lastTimeStamp = lastWeiboContent.getTimeStamp();
        }
      }

      log.info("TencentWeiboServiceImpl.read()" + weiboContents);
    }

    return new Pair<Pair<String, Long>, List<WeiboContent>>(
        new Pair<String, Long>(lastId, lastTimeStamp), weiboContents);
  }
Пример #28
0
 private static String removeQuotes(Matcher<? extends String> matcher) {
   return StringUtils.removeEnd(StringUtils.removeStart(matcher.toString(), "\""), "\"");
 }
Пример #29
0
 private static String getCovertArt(String strHref, String kind) throws IOException {
   String strAlbum = StringUtils.removeStart(strHref, String.format("spotify:%s:", kind));
   Document document = Jsoup.connect(String.format("%s/%s/%s", BASE_URL, kind, strAlbum)).get();
   Element imgElement = document.getElementById(COVER_CSS_ID);
   return imgElement.attr(CORVER_CSS_ATTR);
 }
  @Override
  public void init(ActionServlet servlet, ModuleConfig config) throws ServletException {

    if (!initialized) {
      loadActionsFromFile(actionClasses);
      PartialTileDefinition.init();
      initialized = true;
    }

    final String modulePrefix = StringUtils.removeStart(config.getPrefix(), "/");

    for (Class<?> actionClass : actionClasses) {
      Mapping mapping = actionClass.getAnnotation(Mapping.class);
      if (mapping == null || !modulePrefix.equals(mapping.module())) {
        continue;
      }

      final ActionMapping actionMapping = createCustomActionMapping(mapping);
      if (actionMapping == null) {
        continue;
      }

      actionMapping.setPath(mapping.path());
      actionMapping.setType(actionClass.getName());
      actionMapping.setScope(mapping.scope());
      actionMapping.setParameter(mapping.parameter());
      actionMapping.setValidate(mapping.validate());

      if (mapping.formBeanClass() != ActionForm.class) {
        final String formName = mapping.formBeanClass().getName();
        createFormBeanConfigIfNecessary(config, mapping, formName);
        actionMapping.setName(formName);
      } else if (!mapping.formBean().isEmpty()) {
        actionMapping.setName(mapping.formBean());
      }

      if (mapping.input().isEmpty()) {
        actionMapping.setInput(findInputMethod(actionClass, mapping));
      } else {
        registerInput(actionMapping, mapping.input());
      }

      String defaultResourcesName = getDefaultResourcesName(config);
      Forwards forwards = actionClass.getAnnotation(Forwards.class);
      if (forwards != null) {
        for (final Forward forward : forwards.value()) {
          registerForward(actionMapping, forward, forwards, mapping, defaultResourcesName);
        }
      }
      registerSuperclassForwards(
          actionMapping, actionClass.getSuperclass(), mapping, defaultResourcesName);

      Exceptions exceptions = actionClass.getAnnotation(Exceptions.class);
      if (exceptions != null) {
        registerExceptionHandling(actionMapping, exceptions);
      }

      initializeActionMappingProperties(actionMapping, mapping.customMappingProperties());

      config.addActionConfig(actionMapping);
    }
  }