Example #1
0
  public void loadGridNet(String mapGrid) throws IOException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(mapGrid));

    logger.debug("loading {}...", mapGrid);

    CSVReader reader = new CSVReader(new FileReader(mapGrid), ',', '"', 1);
    String[] row;
    while ((row = reader.readNext()) != null) {
      String gridId = row[1].trim();
      String dmRoads = row[2].trim();
      String gjRoads = row[3].trim();

      Set<String> x =
          Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(dmRoads));
      Set<String> y =
          Sets.newHashSet(Splitter.on('|').trimResults().omitEmptyStrings().split(gjRoads));
      if (x.size() > 0 || y.size() > 0) {
        MapGrid grid = new MapGrid();
        grid.dmRoads = x;
        grid.gjRoads = y;

        gridNet.put(gridId, grid);
        //                logger.debug("{},{},{}", gridId, x, y);
      }
    }

    reader.close();
  }
Example #2
0
 @GET
 @Path("/{id}/contains")
 /*
     @ApiOperation(httpMethod = "GET", value = "Get the genes that contain the given string")
 */
 public Response getByContainsQuery(@PathParam("id") String query) {
   try {
     checkParams();
     XRefsDBAdaptor x = dbAdaptorFactory.getXRefDBAdaptor(this.species, this.assembly);
     List<List<Xref>> xrefs = x.getByContainsQueryList(Splitter.on(",").splitToList(query));
     if (query.startsWith("rs")
         || query.startsWith("AFFY_")
         || query.startsWith("SNP_")
         || query.startsWith("VAR_")
         || query.startsWith("CRTAP_")
         || query.startsWith("FKBP10_")
         || query.startsWith("LEPRE1_")
         || query.startsWith("PPIB_")) {
       List<QueryResult> snpXrefs =
           x.getByStartsWithSnpQueryList(Splitter.on(",").splitToList(query), queryOptions);
       //                for (List<Xref> xrefList : snpXrefs) {
       //                    xrefs.get(0).addAll(xrefList);
       //                }
     }
     return generateResponse(query, xrefs);
   } catch (Exception e) {
     e.printStackTrace();
     return createErrorResponse("getAllByAccessions", e.toString());
   }
 }
Example #3
0
 public static Map<FormatBundle, Map<Integer, List<Path>>> getFormatNodeMap(JobContext job) {
   Map<FormatBundle, Map<Integer, List<Path>>> formatNodeMap = Maps.newHashMap();
   Configuration conf = job.getConfiguration();
   String crunchInputs = conf.get(CRUNCH_INPUTS);
   if (crunchInputs == null || crunchInputs.isEmpty()) {
     return ImmutableMap.of();
   }
   for (String input : Splitter.on(RECORD_SEP).split(crunchInputs)) {
     List<String> fields = Lists.newArrayList(SPLITTER.split(input));
     FormatBundle<InputFormat> inputBundle =
         FormatBundle.fromSerialized(fields.get(0), job.getConfiguration());
     if (!formatNodeMap.containsKey(inputBundle)) {
       formatNodeMap.put(inputBundle, Maps.<Integer, List<Path>>newHashMap());
     }
     Integer nodeIndex = Integer.valueOf(fields.get(1));
     if (!formatNodeMap.get(inputBundle).containsKey(nodeIndex)) {
       formatNodeMap.get(inputBundle).put(nodeIndex, Lists.<Path>newLinkedList());
     }
     List<Path> formatNodePaths = formatNodeMap.get(inputBundle).get(nodeIndex);
     String paths = fields.get(2);
     for (String path : Splitter.on(PATH_SEP).split(paths)) {
       formatNodePaths.add(new Path(path));
     }
   }
   return formatNodeMap;
 }
Example #4
0
 private static ImmutableMap<String, String> getQueryMap(final String query)
     throws MalformedRequestException {
   if (StringUtils.isBlank(query)) {
     return ImmutableMap.of();
   } else {
     final Iterable<String> params = Splitter.on('&').split(query);
     final ImmutableMap.Builder<String, String> map = ImmutableMap.builder();
     for (final String param : params) {
       final ImmutableList<String> strings = ImmutableList.copyOf(Splitter.on('=').split(param));
       final String name = strings.get(0);
       if (strings.size() > 2) {
         throw new MalformedRequestException("Multiple '=' for parameter " + name);
       }
       final String value;
       if (strings.size() > 1) {
         value = strings.get(1);
       } else {
         value = null;
       }
       if (map.build().keySet().contains(name)) {
         throw new MalformedRequestException("Duplicate value for parameter " + name);
       }
       map.put(name, value);
     }
     return map.build();
   }
 }
Example #5
0
  public Map<String, Path> buildMultipleAndReturnOutputs(String... args) throws IOException {
    // Add in `--show-output` to the build, so we can parse the output paths after the fact.
    ImmutableList<String> buildArgs =
        ImmutableList.<String>builder().add("--show-output").add(args).build();
    ProjectWorkspace.ProcessResult buildResult =
        runBuckBuild(buildArgs.toArray(new String[buildArgs.size()]));
    buildResult.assertSuccess();

    // Grab the stdout lines, which have the build outputs.
    List<String> lines =
        Splitter.on(CharMatcher.anyOf(System.lineSeparator()))
            .trimResults()
            .omitEmptyStrings()
            .splitToList(buildResult.getStdout());

    // Skip the first line, which is just "The outputs are:".
    assertThat(lines.get(0), Matchers.equalTo("The outputs are:"));
    lines = lines.subList(1, lines.size());

    Splitter lineSplitter = Splitter.on(' ').trimResults();
    ImmutableMap.Builder<String, Path> builder = ImmutableMap.builder();
    for (String line : lines) {
      List<String> fields = lineSplitter.splitToList(line);
      assertThat(fields, Matchers.hasSize(2));
      builder.put(fields.get(0), getPath(fields.get(1)));
    }

    return builder.build();
  }
 @Singleton
 @Iso3166
 @Override
 public Map<String, Set<String>> get() {
   Builder<String, Set<String>> codes = ImmutableMap.<String, Set<String>>builder();
   for (String key : ImmutableSet.of(PROPERTY_REGION, PROPERTY_ZONE))
     try {
       String regionString = injector.getInstance(Key.get(String.class, named(key + "s")));
       for (String region : Splitter.on(',').split(regionString)) {
         try {
           codes.put(
               region,
               ImmutableSet.copyOf(
                   Splitter.on(',')
                       .split(
                           injector.getInstance(
                               Key.get(
                                   String.class,
                                   named(key + "." + region + "." + ISO3166_CODES))))));
         } catch (ConfigurationException e) {
           // this happens if regions property isn't set
           // services not run by AWS may not have regions, so this is ok.
         }
       }
     } catch (ConfigurationException e) {
       // this happens if regions property isn't set
       // services not run by AWS may not have regions, so this is ok.
     }
   return codes.build();
 }
Example #7
0
 @GET
 @Path("/{id}/xref")
 @ApiOperation(httpMethod = "GET", value = "Retrieves all the external references for the ID")
 public Response getByFeatureId(
     @PathParam("id") String query, @DefaultValue("") @QueryParam("dbname") String dbname) {
   try {
     checkParams();
     XRefsDBAdaptor xRefDBAdaptor = dbAdaptorFactory.getXRefDBAdaptor(this.species, this.assembly);
     if (!dbname.equals("")) {
       queryOptions.put("dbname", Splitter.on(",").splitToList(dbname));
     }
     return createOkResponse(
         xRefDBAdaptor.getAllByDBNameList(Splitter.on(",").splitToList(query), queryOptions));
     //            if (dbName.equals("")) {
     //                return generateResponse(query, "XREF",
     // x.getAllByDBNameList(Splitter.on(",").splitToList(query), null));
     //            }
     //            else {
     //                return generateResponse(query, "XREF",
     // x.getAllByDBNameList(Splitter.on(",").splitToList(query),
     // Splitter.on(",").splitToList(dbName)));
     //            }
   } catch (Exception e) {
     e.printStackTrace();
     return createErrorResponse("getAllByAccessions", e.toString());
   }
 }
Example #8
0
  /**
   * Creates the list of comparables
   *
   * @since $version
   * @author hceylan
   */
  private void createComparables() {
    // order on id
    if (this.mapping.getOrderBy().trim().length() == 0) {
      if (this.mapping.isAssociation()) {
        final EntityTypeImpl<E> type = ((PluralAssociationMapping<?, ?, E>) this.mapping).getType();
        if (type.hasSingleIdAttribute()) {
          this.comparables.add(new ComparableMapping(true, (Mapping<?, ?, ?>) type.getIdMapping()));
        } else {
          for (final Pair<BasicMapping<? super E, ?>, BasicAttribute<?, ?>> pair :
              type.getIdMappings()) {
            this.comparables.add(new ComparableMapping(true, pair.getFirst()));
          }
        }
      } else if (this.mapping.getType().getPersistenceType() == PersistenceType.EMBEDDABLE) {
        throw new MappingException(
            "Embeddable element collections requires OrderBy value",
            this.mapping.getAttribute().getLocator());
      } else {
        this.comparables.add(new ComparableMapping(true, null));
      }
    } else {
      final Iterator<String> i =
          Splitter.on(",").trimResults().split(this.mapping.getOrderBy()).iterator();
      while (i.hasNext()) {
        final Iterator<String> j = Splitter.on(" ").trimResults().split(i.next()).iterator();

        int index = 0;
        String path = null;
        boolean order = true;
        while (j.hasNext()) {
          if (index == 0) {
            path = j.next();
          } else if (index == 1) {
            order = "ASC".equals(j.next().toUpperCase());
          } else {
            throw new MappingException(
                "Invalid order by statement: " + this.mapping.getOrderBy() + ".",
                this.mapping.getAttribute().getLocator());
          }

          index++;
        }

        if (this.mapping.getType().getPersistenceType() == PersistenceType.BASIC) {
          throw new MappingException(
              "Basic element collection must not have OrderBy value",
              this.mapping.getAttribute().getLocator());
        }

        final Mapping<?, ?, ?> mapping = this.mapping.getMapping(path);
        if (mapping == null) {
          throw new MappingException(
              "Sort property cannot be found: " + path, this.mapping.getAttribute().getLocator());
        }

        this.comparables.add(new ComparableMapping(order, mapping));
      }
    }
  }
  /**
   * Get a {@link org.kitesdk.data.PartitionKey} corresponding to a partition's filesystem path
   * represented as a {@link URI}. If the path is not a valid partition, then {@link
   * IllegalArgumentException} is thrown. Note that the partition does not have to exist.
   *
   * @param dataset the filesystem dataset
   * @param partitionPath a directory path where the partition data is stored
   * @return a partition key representing the partition at the given path
   * @since 0.4.0
   */
  @SuppressWarnings("deprecation")
  public static PartitionKey partitionKeyForPath(Dataset dataset, URI partitionPath) {
    Preconditions.checkState(
        dataset.getDescriptor().isPartitioned(),
        "Attempt to get a partition on a non-partitioned dataset (name:%s)",
        dataset.getName());

    Preconditions.checkArgument(
        dataset instanceof FileSystemDataset, "Dataset is not a FileSystemDataset");
    FileSystemDataset fsDataset = (FileSystemDataset) dataset;

    FileSystem fs = fsDataset.getFileSystem();
    URI partitionUri = fs.makeQualified(new Path(partitionPath)).toUri();
    URI directoryUri = fsDataset.getDirectory().toUri();
    URI relativizedUri = directoryUri.relativize(partitionUri);

    if (relativizedUri.equals(partitionUri)) {
      throw new IllegalArgumentException(
          String.format(
              "Partition URI %s has different " + "root directory to dataset (directory: %s).",
              partitionUri, directoryUri));
    }

    Iterable<String> parts = Splitter.on('/').split(relativizedUri.getPath());

    PartitionStrategy partitionStrategy = dataset.getDescriptor().getPartitionStrategy();
    List<FieldPartitioner> fieldPartitioners = partitionStrategy.getFieldPartitioners();
    if (Iterables.size(parts) > fieldPartitioners.size()) {
      throw new IllegalArgumentException(
          String.format(
              "Too many partition directories " + "for %s (%s), expecting %s.",
              partitionUri, Iterables.size(parts), fieldPartitioners.size()));
    }

    List<Object> values = Lists.newArrayList();
    int i = 0;
    for (String part : parts) {
      Iterator<String> split = Splitter.on('=').split(part).iterator();
      String fieldName = split.next();
      FieldPartitioner fp = fieldPartitioners.get(i++);
      if (!fieldName.equals(fp.getName())) {
        throw new IllegalArgumentException(
            String.format(
                "Unrecognized partition name " + "'%s' in partition %s, expecting '%s'.",
                fieldName, partitionUri, fp.getName()));
      }
      if (!split.hasNext()) {
        throw new IllegalArgumentException(
            String.format(
                "Missing partition value for " + "'%s' in partition %s.", fieldName, partitionUri));
      }
      String stringValue = split.next();
      Object value = fp.valueFromString(stringValue);
      values.add(value);
    }
    return org.kitesdk.data.impl.Accessor.getDefault()
        .newPartitionKey(values.toArray(new Object[values.size()]));
  }
 protected void setupCredentials() {
   identity = System.getProperty("test." + provider + ".identity", "administrator");
   credential = System.getProperty("test." + provider + ".credential", "12345");
   endpoint =
       URI.create(System.getProperty("test." + provider + ".endpoint", "http://localhost:18083/"));
   apiVersion = System.getProperty("test." + provider + ".apiversion", "4.1.2r73507");
   majorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 0);
   minorVersion = Iterables.get(Splitter.on('r').split(apiVersion), 1);
 }
Example #11
0
 public NameParts(final String dn) {
   final ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
   for (final String chunk : Splitter.on(',').trimResults().split(dn)) {
     List<String> pairs = ImmutableList.copyOf(Splitter.on('=').trimResults().split(chunk));
     if (pairs.size() == 2) {
       builder.put(pairs.get(0), pairs.get(1));
     }
   }
   original = dn;
   parts = builder.build();
 }
 /**
  * Constructs a ApplicationBundler.
  *
  * @param excludePackages Class packages to exclude
  * @param includePackages Always includes classes/resources in these packages. Note that classes
  *     in these packages will not get inspected for dependencies.
  */
 public ApplicationBundler(Iterable<String> excludePackages, Iterable<String> includePackages) {
   this.excludePackages = ImmutableList.copyOf(excludePackages);
   this.includePackages = ImmutableList.copyOf(includePackages);
   this.acceptClassPath =
       Sets.difference(
           Sets.newHashSet(
               Splitter.on(File.pathSeparatorChar).split(System.getProperty("java.class.path"))),
           Sets.newHashSet(
               Splitter.on(File.pathSeparatorChar)
                   .split(System.getProperty("sun.boot.class.path"))));
 }
 public void testBuildImage() throws IOException, InterruptedException, URISyntaxException {
   BuildOptions options = BuildOptions.Builder.tag("testBuildImage").verbose(false).nocache(false);
   InputStream buildImageStream =
       api().build(new File(Resources.getResource("Dockerfile").toURI()), options);
   String buildStream = consumeStream(buildImageStream, false);
   Iterable<String> splitted = Splitter.on("\n").split(buildStream.replace("\r", "").trim());
   String lastStreamedLine = Iterables.getLast(splitted).trim();
   String rawImageId =
       Iterables.getLast(Splitter.on("Successfully built ").split(lastStreamedLine));
   String imageId = rawImageId.substring(0, 11);
   Image image = api().inspectImage(imageId);
   api().deleteImage(image.getId(), DeleteImageOptions.Builder.force(true));
 }
  /**
   * Get HttpResourceModel which matches the HttpMethod of the request.
   *
   * @param routableDestinations List of ResourceModels.
   * @param targetHttpMethod HttpMethod.
   * @param requestUri request URI.
   * @return RoutableDestination that matches httpMethod that needs to be handled. null if there are
   *     no matches.
   */
  private List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>>
      getMatchedDestination(
          List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>>
              routableDestinations,
          HttpMethod targetHttpMethod,
          String requestUri) {

    Iterable<String> requestUriParts = Splitter.on('/').omitEmptyStrings().split(requestUri);
    List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> matchedDestinations =
        Lists.newArrayListWithExpectedSize(routableDestinations.size());
    int maxExactMatch = 0;
    int maxGroupMatch = 0;
    int maxPatternLength = 0;

    for (PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> destination :
        routableDestinations) {
      HttpResourceModel resourceModel = destination.getDestination();
      int groupMatch = destination.getGroupNameValues().size();

      for (HttpMethod httpMethod : resourceModel.getHttpMethod()) {
        if (targetHttpMethod.equals(httpMethod)) {

          int exactMatch =
              getExactPrefixMatchCount(
                  requestUriParts,
                  Splitter.on('/').omitEmptyStrings().split(resourceModel.getPath()));

          // When there are multiple matches present, the following precedence order is used -
          // 1. template path that has highest exact prefix match with the url is chosen.
          // 2. template path has the maximum groups is chosen.
          // 3. finally, template path that has the longest length is chosen.
          if (exactMatch > maxExactMatch) {
            maxExactMatch = exactMatch;
            maxGroupMatch = groupMatch;
            maxPatternLength = resourceModel.getPath().length();

            matchedDestinations.clear();
            matchedDestinations.add(destination);
          } else if (exactMatch == maxExactMatch && groupMatch >= maxGroupMatch) {
            if (groupMatch > maxGroupMatch || resourceModel.getPath().length() > maxPatternLength) {
              maxGroupMatch = groupMatch;
              maxPatternLength = resourceModel.getPath().length();
              matchedDestinations.clear();
            }
            matchedDestinations.add(destination);
          }
        }
      }
    }
    return matchedDestinations;
  }
Example #15
0
 private static LibraryDeps fromReaderEx(Reader reader) throws Exception {
   LibraryDeps deps = new LibraryDeps();
   BufferedReader buf = new BufferedReader(reader);
   // Check version.
   {
     String line = buf.readLine();
     if (!Objects.equal(line, VERSION)) {
       return deps;
     }
   }
   // Read units dependencies.
   String relPath;
   while (null != (relPath = buf.readLine())) {
     Source source = new Source();
     // Read flags.
     source.shouldRecompileOnAnyTopLevelChange = Boolean.parseBoolean(buf.readLine());
     // Read top symbols.
     {
       String line = buf.readLine();
       Iterable<String> topSymbols = Splitter.on(' ').omitEmptyStrings().split(line);
       Iterables.addAll(source.topSymbols, topSymbols);
     }
     // Read all symbols.
     {
       String line = buf.readLine();
       Iterable<String> allSymbols = Splitter.on(' ').omitEmptyStrings().split(line);
       Iterables.addAll(source.allSymbols, allSymbols);
     }
     // Read holes.
     {
       String line = buf.readLine();
       Iterable<String> holes = Splitter.on(' ').omitEmptyStrings().split(line);
       Iterables.addAll(source.holes, holes);
     }
     // Read dependencies.
     while (true) {
       String line = buf.readLine();
       // Blank line: next unit.
       if (line.length() == 0) {
         break;
       }
       // Parse line.
       String[] parts = line.split(" ");
       source.deps.add(new Dependency(new URI(parts[0]), parts[1], Long.parseLong(parts[2])));
     }
     // Remember dependencies for current unit.
     deps.sources.put(relPath, source);
   }
   return deps;
 }
  public void shouldSplitIntoList() {
    final String input = "first , second , third , fourth ,,, seventh";

    assertEquals(
        Lists.newArrayList("first ", " second ", " third ", " fourth ", "", "", " seventh"),
        Lists.newArrayList(Splitter.on(",").split(input)));

    assertEquals(
        Lists.newArrayList("first ", " second ", " third ", " fourth ", " seventh"),
        Lists.newArrayList(Splitter.on(",").omitEmptyStrings().split(input)));

    assertEquals(
        Lists.newArrayList("first", "second", "third", "fourth", "", "", "seventh"),
        Lists.newArrayList(Splitter.on(",").trimResults().split(input)));
  }
  @BeforeClass
  public static void setUp() throws IOException {
    InputStream dataFileInputStream =
        NaraSoundexTest.class.getResourceAsStream("DaitchMokotoffSoundexTest.data");
    List<String> lines = CharStreams.readLines(new InputStreamReader(dataFileInputStream));

    for (String currentLine : lines) {
      if (!currentLine.startsWith(";")) {
        Iterable<String> components = Splitter.on("->").trimResults().split(currentLine);
        Iterable<String> expectedValues =
            Splitter.on(",").trimResults().split(Iterables.get(components, 1));
        testCases.putAll(Iterables.get(components, 0), expectedValues);
      }
    }
  }
Example #18
0
  /**
   * Setup blocked flag for all builtin UDFs as per udf whitelist and blacklist
   *
   * @param whiteListStr
   * @param blackListStr
   */
  public void setupPermissionsForUDFs(String whiteListStr, String blackListStr) {
    Set<String> whiteList =
        Sets.newHashSet(
            Splitter.on(",").trimResults().omitEmptyStrings().split(whiteListStr.toLowerCase()));
    Set<String> blackList =
        Sets.newHashSet(
            Splitter.on(",").trimResults().omitEmptyStrings().split(blackListStr.toLowerCase()));
    blackList.removeAll(FunctionRegistry.HIVE_OPERATORS);

    for (Map.Entry<String, FunctionInfo> funcEntry : mFunctions.entrySet()) {
      funcEntry
          .getValue()
          .setBlockedFunction(isUdfBlocked(funcEntry.getKey(), whiteList, blackList));
    }
  }
Example #19
0
public class SampleConverter {

  private final BufferedReader reader;
  private static final Splitter TAB_SPLITTER = Splitter.on("\t");

  public SampleConverter(Reader reader) {
    this.reader = new BufferedReader(reader);
  }

  public void convert(File outputFile) throws IOException {
    FileOutputStream os = new FileOutputStream(outputFile);
    String line;
    while ((line = reader.readLine()) != null) {
      List<String> sampleValues = Lists.newArrayList(Iterables.skip(TAB_SPLITTER.split(line), 1));
      int sampleValueShortL =
          (int) (Double.parseDouble(sampleValues.get(0)) * Integer.MAX_VALUE * 0.1);
      int sampleValueShortR =
          (int) (Double.parseDouble(sampleValues.get(1)) * Integer.MAX_VALUE * 0.1);
      os.write(ByteBuffer.allocate(4).putInt(sampleValueShortL).array());
      os.write(ByteBuffer.allocate(4).putInt(sampleValueShortR).array());
    }
    os.close();
    reader.close();
  }
}
  public void shouldSplitIntoMap() {
    final String input = "key1=value1&key2=value2";

    assertEquals(
        ImmutableMap.of("key1", "value1", "key2", "value2"),
        Splitter.on("&").withKeyValueSeparator("=").split(input));
  }
  @Test
  public void testFromSystem_containsListValues() throws Exception {
    AbstractConfiguration.setDefaultListDelimiter('|');
    Map<String, String> properties = Maps.newHashMap();
    properties.put("testProperty", "b,bee");

    for (Entry<String, String> entry : properties.entrySet()) {
      System.setProperty(entry.getKey(), entry.getValue());
    }

    Splitter splitter = Splitter.on(',');
    Configuration systemConfiguration = configurationHelper.fromSystem();
    for (Entry<String, String> entry : properties.entrySet()) {
      String[] actualValues = systemConfiguration.getStringArray(entry.getKey());
      String[] expectedValues;
      if ("line.separator".equals(entry.getKey())) {
        expectedValues = new String[] {SystemUtils.LINE_SEPARATOR};
      } else {
        expectedValues = splitter.splitToList(entry.getValue()).toArray(new String[0]);
      }
      assertArrayEquals(
          String.format("Values for key %s do not match", entry.getKey()),
          expectedValues,
          actualValues);
    }
  }
 @Override
 public boolean hasClass(String cssClassName) {
   String cssClassValue = getAttribute("class").toLowerCase();
   List<String> cssClasses =
       Lists.newArrayList(Splitter.on(" ").omitEmptyStrings().trimResults().split(cssClassValue));
   return cssClasses.contains(cssClassName.toLowerCase());
 }
  // TODO(ns): Handle multiple statements on the same line like:
  // var x = foo; var y = bar;
  public void parseLine(PeekingIterator<Character> chars) {
    // Consume all trailing whitespace and end-of-statement chars.
    consumeAllMatching(chars, CharMatcher.WHITESPACE.or(CharMatcher.is(';')));

    // Parse the last expression of the line.  We presume it's the right hand side of an assignment.
    Expression rhs = getExpression(chars);

    // Make sure it really was the right hand sign of the assignment (the next non-space char should
    // be an equals sign).
    consumeAllMatching(chars, CharMatcher.WHITESPACE);
    if (!chars.hasNext() || '=' != chars.next()) {
      return;
    }

    // Get the remainder of the line, until the next line-feed (don't want to keep going forever).
    // TODO(gmoura): go until the beginning of the expression instead of beginning of line.
    String line = "";
    while (chars.hasNext() && !CharMatcher.anyOf("\n;{}()").matches(chars.peek())) {
      line = chars.next() + line;
    }
    // Assign each variable to the value of the RHS.
    for (String side : Splitter.on('=').split(line)) {
      String[] pieces = side.trim().split(" ");
      String variable = pieces[pieces.length - 1];
      if (!Strings.isNullOrEmpty(variable)) {
        variableTypes.put(variable, rhs);
      }
    }
  }
  @Override
  public String intercept(ActionInvocation invocation) throws Exception {
    Map<String, Object> session = invocation.getInvocationContext().getSession();
    User user = (User) session.get("user");

    HttpServletRequest request =
        (HttpServletRequest) invocation.getInvocationContext().get(StrutsStatics.HTTP_REQUEST);

    if (user != null) {
      return invocation.invoke();
    } else {
      Cookie[] cookies = request.getCookies();
      if (cookies != null) {
        for (Cookie cookie : cookies) {
          if (cookie.getName().equals("remember-me")) {
            Map<String, String> loginParameters =
                Splitter.on('&').withKeyValueSeparator('=').split(cookie.getValue());
            UserDao userDao = new UserDaoImpl();
            user = userDao.loginUser(loginParameters.get("email"), loginParameters.get("password"));
            if (!loginParameters.get("password").equals(user.getPassword())) {
              return "login";
            } else {
              session.put("user", user);
              request.setAttribute("rememberMe", "true");
              return invocation.invoke();
            }
          }
        }
      }
      return "login";
    }
  }
Example #25
0
 /**
  * Injects the StorageInfo into the FileAttributes.
  *
  * <p>Legacy fields that used to be stored in StorageInfo, but are now stored in FileAttributes,
  * are injected into the FileAttributes too.
  *
  * <p>Should only be used when backwards compatibility must be maintained.
  */
 public static FileAttributes injectInto(StorageInfo info, FileAttributes attributes) {
   attributes.setStorageInfo(info);
   attributes.setSize(info.getLegacySize());
   attributes.setAccessLatency(info.getLegacyAccessLatency());
   attributes.setRetentionPolicy(info.getLegacyRetentionPolicy());
   String cFlag = info.getKey("flag-c");
   if (cFlag != null) {
     attributes.setChecksums(
         Sets.newHashSet(
             transform(
                 Splitter.on(',').trimResults().omitEmptyStrings().split(cFlag),
                 new Function<String, Checksum>() {
                   @Override
                   public Checksum apply(String digest) {
                     return Checksum.parseChecksum(digest);
                   }
                 })));
   }
   String uid = info.getKey("uid");
   if (uid != null) {
     attributes.setOwner(Integer.parseInt(uid));
   }
   String gid = info.getKey("gid");
   if (gid != null) {
     attributes.setGroup(Integer.parseInt(gid));
   }
   attributes.setFlags(info.getMap());
   return attributes;
 }
Example #26
0
  public static void main(String[] args) {
    String string = "1|2|3|4|";
    // 拆分字符串
    List<String> ret = Splitter.on("|").trimResults().omitEmptyStrings().splitToList(string);
    System.out.println("ret.size() = " + ret.size());
    for (String s : ret) {
      System.out.println("s = " + s);
    }

    String mapString = "a=1,b=2,c=3";
    // 拆分map
    Map<String, String> map = Splitter.on(",").withKeyValueSeparator("=").split(mapString);
    for (Map.Entry<String, String> m : map.entrySet()) {
      System.out.println("first = " + m.getKey() + ", second = " + m.getValue());
    }
  }
 private static void validateAnalyzerMessage(
     Map<IssueAttribute, String> attrs, AnalyzerMessage analyzerMessage) {
   Double effortToFix = analyzerMessage.getCost();
   if (effortToFix != null) {
     assertEquals(Integer.toString(effortToFix.intValue()), attrs, IssueAttribute.EFFORT_TO_FIX);
   }
   AnalyzerMessage.TextSpan textSpan = analyzerMessage.primaryLocation();
   assertEquals(normalizeColumn(textSpan.startCharacter), attrs, IssueAttribute.START_COLUMN);
   assertEquals(Integer.toString(textSpan.endLine), attrs, IssueAttribute.END_LINE);
   assertEquals(normalizeColumn(textSpan.endCharacter), attrs, IssueAttribute.END_COLUMN);
   if (attrs.containsKey(IssueAttribute.SECONDARY_LOCATIONS)) {
     List<AnalyzerMessage> secondaryLocations = analyzerMessage.secondaryLocations;
     Multiset<String> actualLines = HashMultiset.create();
     for (AnalyzerMessage secondaryLocation : secondaryLocations) {
       actualLines.add(Integer.toString(secondaryLocation.getLine()));
     }
     List<String> expected =
         Lists.newArrayList(
             Splitter.on(",")
                 .omitEmptyStrings()
                 .trimResults()
                 .split(attrs.get(IssueAttribute.SECONDARY_LOCATIONS)));
     List<String> unexpected = new ArrayList<>();
     for (String actualLine : actualLines) {
       if (expected.contains(actualLine)) {
         expected.remove(actualLine);
       } else {
         unexpected.add(actualLine);
       }
     }
     if (!expected.isEmpty() || !unexpected.isEmpty()) {
       Fail.fail("Secondary locations: expected: " + expected + " unexpected:" + unexpected);
     }
   }
 }
/** Resolve the field names of entity class variables using Morphia's mapper. */
public class MorphiaPropertyResolver implements PropertyResolver {

  private final Mapper mapper;
  private final Splitter splitter = Splitter.on('.');
  private final Joiner joiner = Joiner.on('.');

  public MorphiaPropertyResolver() {
    this(new Mapper());
  }

  public MorphiaPropertyResolver(Mapper mapper) {
    this.mapper = mapper;
  }

  @Override
  public String resolve(String fieldName, Class<?> entityClass) {
    Iterable<String> fieldNames = splitter.split(fieldName);
    List<String> resolved = Lists.newArrayList();
    Class<?> lastClass = entityClass;
    for (String name : fieldNames) {
      MappedField mappedField = mapper.getMappedClass(lastClass).getMappedFieldByJavaField(name);
      if (mappedField != null) {
        lastClass = mappedField.getConcreteType();
        resolved.add(mappedField.getNameToStore());
      } else {
        resolved.add(name);
      }
    }
    return joiner.join(resolved);
  }
}
Example #29
0
  public static void main(String[] args) throws Exception {
    final Configuration configuration = HBaseConfiguration.create();
    configuration.addResource("grade.xml");
    String tables = configuration.get("hbase.cdn.tables");
    if (Strings.isNullOrEmpty(tables)) {
      return;
    }
    List<String> list = Lists.newArrayList(Splitter.on(",").split(tables));
    List<String> results =
        Lists.transform(
            list,
            new Function<String, String>() {
              @Override
              public String apply(@Nullable java.lang.String input) {
                return String.format(
                    configuration.get("hdfs.directory.base.db"), new Date(), input);
              }
            });

    String[] arrays =
        new String[] {
          Joiner.on(",").join(results),
          String.format(configuration.get("hdfs.directory.num.middle"), new Date()),
          String.format(configuration.get("hdfs.directory.num.result"), new Date())
        };
    AbstractJob job = new TopNJob();
    //        job.setStart(true);
    int i = ToolRunner.run(configuration, job, arrays);
    System.exit(i);
  }
Example #30
0
 @IMCCallback
 public void processIMCRequests(FMLInterModComms.IMCEvent event) {
   Splitter splitter = Splitter.on("@").trimResults();
   for (IMCMessage m : event.getMessages()) {
     if ("add-facade".equals(m.key)) {
       String[] array = Iterables.toArray(splitter.split(m.getStringValue()), String.class);
       if (array.length != 2) {
         Logger.getLogger("Buildcraft")
             .log(
                 Level.INFO,
                 String.format(
                     "Received an invalid add-facade request %s from mod %s",
                     m.getStringValue(), m.getSender()));
         continue;
       }
       Integer blId = Ints.tryParse(array[0]);
       Integer metaId = Ints.tryParse(array[1]);
       if (blId == null || metaId == null) {
         Logger.getLogger("Buildcraft")
             .log(
                 Level.INFO,
                 String.format(
                     "Received an invalid add-facade request %s from mod %s",
                     m.getStringValue(), m.getSender()));
         continue;
       }
       ItemFacade.addFacade(new ItemStack(blId, 1, metaId));
     }
   }
 }