Java Code Examples for com.google.api.client.util.Lists#newArrayList()

The following examples show how to use com.google.api.client.util.Lists#newArrayList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GeolocationProcessorUpgrader.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void upgradeV3ToV4(List<Config> configs) {
  List<Config> configsToRemove = new ArrayList<>();

  String geoIP2DBFile = null;
  String geoIP2DBType = null;

  for (Config config : configs) {
    switch (config.getName()) {
      case "geoIP2DBFile":
        configsToRemove.add(config);
        geoIP2DBFile = config.getValue().toString();
        break;
      case "geoIP2DBType":
        configsToRemove.add(config);
        geoIP2DBType = config.getValue().toString();
        break;
    }
  }

  configs.removeAll(configsToRemove);

  List<Map<String, String>> dbConfigs = Lists.newArrayList();
  Map<String, String> dbConfig = ImmutableMap.of("geoIP2DBFile", geoIP2DBFile, "geoIP2DBType", geoIP2DBType);
  dbConfigs.add(dbConfig);
  configs.add(new Config("dbConfigs", dbConfigs));
}
 
Example 2
Source File: TestCertificates.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
public static JsonWebSignature getJsonWebSignature() throws IOException {
  if (jsonWebSignature == null) {
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    List<String> certificates = Lists.newArrayList();
    certificates.add(FOO_BAR_COM_CERT.getBase64Der());
    certificates.add(CA_CERT.getBase64Der());
    header.setX509Certificates(certificates);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    payload.set("foo", "bar");
    int firstDot = JWS_SIGNATURE.indexOf('.');
    int secondDot = JWS_SIGNATURE.indexOf('.', firstDot + 1);
    byte[] signatureBytes = Base64.decodeBase64(JWS_SIGNATURE.substring(secondDot + 1));
    byte[] signedContentBytes = StringUtils.getBytesUtf8(JWS_SIGNATURE.substring(0, secondDot));
    JsonWebSignature signature =
        new JsonWebSignature(header, payload, signatureBytes, signedContentBytes);
    jsonWebSignature = signature;
  }
  return jsonWebSignature;
}
 
Example 3
Source File: AppEngineDataStoreFactory.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public AppEngineDataStore<V> clear() throws IOException {
  lock.lock();
  try {
    if (memcache != null) {
      memcache.clearAll();
    }
    // no clearAll() method on DataStoreService so have to query all keys & delete them
    List<Key> keys = Lists.newArrayList();
    for (Entity entity : query(true)) {
      keys.add(entity.getKey());
    }
    dataStoreService.delete(keys);
  } finally {
    lock.unlock();
  }
  return this;
}
 
Example 4
Source File: TransactionSnippets.java    From google-cloud-java with Apache License 2.0 6 votes vote down vote up
/** Example of getting entities for several keys. */
// [TARGET get(Key...)]
// [VARIABLE "my_first_key_name"]
// [VARIABLE "my_second_key_name"]
public List<Entity> getMultiple(String firstKeyName, String secondKeyName) {
  Datastore datastore = transaction.getDatastore();
  // TODO change so that it's not necessary to hold the entities in a list for integration testing
  // [START getMultiple]
  KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
  Key firstKey = keyFactory.newKey(firstKeyName);
  Key secondKey = keyFactory.newKey(secondKeyName);
  Iterator<Entity> entitiesIterator = transaction.get(firstKey, secondKey);
  List<Entity> entities = Lists.newArrayList();
  while (entitiesIterator.hasNext()) {
    Entity entity = entitiesIterator.next();
    // do something with the entity
    entities.add(entity);
  }
  transaction.commit();
  // [END getMultiple]
  return entities;
}
 
Example 5
Source File: SolrSearcher.java    From q with Apache License 2.0 6 votes vote down vote up
public String getUrlForGettingDoc(String q, List<String> languages, String dataSetId)
{
	List<NameValuePair> parameters = Lists.newArrayList();

	parameters.add(new BasicNameValuePair("q", getPhraseQueryString(q)));
	parameters.add(new BasicNameValuePair("defType", "edismax"));
	parameters.add(new BasicNameValuePair("lowercaseOperators", "false"));
	parameters.add(new BasicNameValuePair("rows", "100000"));
	parameters.add(new BasicNameValuePair("qs", "10"));
	parameters.add(new BasicNameValuePair("fl", Properties.idField.get() + ", " + Properties.titleFields.get().get(0) + "_en"));
	parameters.add(new BasicNameValuePair("sort", Properties.idField.get() + " DESC"));
	parameters.add(new BasicNameValuePair("qf", getQueryFields(languages)));
	parameters.add(new BasicNameValuePair("fq", Properties.docTypeFieldName.get() + ":" + dataSetId));
	parameters.add(new BasicNameValuePair("wt", "json"));

	return getServerUrl() + "/select?" + URLEncodedUtils.format(parameters, BaseIndexer.ENCODING);
}
 
Example 6
Source File: Report.java    From q with Apache License 2.0 5 votes vote down vote up
public static DetailReport copyCurrentFileToPreviousAndGetPrevious(String currentName, String previousName) throws IOException {
    File currentFile = new File(Properties.dataDir.get() + currentName);
    Path currentPath = currentFile.toPath();
    File previousFile = new File(Properties.dataDir.get() + previousName+".tsv");
    Path previousPath = previousFile.toPath();
    Files.copy(currentPath, previousPath, StandardCopyOption.REPLACE_EXISTING);

    DetailReport previousDetailReport = new DetailReport();
    List<ReportItem> items = Lists.newArrayList();

    InputStream is = new BufferedInputStream(new FileInputStream(previousFile), BUFFER_SIZE);
    BufferedReader reader = new BufferedReader(new InputStreamReader(is, ENCODING), BUFFER_SIZE);
    String lineString = null;
    while ((lineString = reader.readLine()) != null) {
        String[] line = lineString.split(Properties.inputDelimiter.get());

        String name = line[0];
        ResultType failure = ResultType.valueOf(line[1]);
        String query = line[2];
        String expected = line[3];
        String actual = line[4];

        ReportItem reportItem = new DetailReportItem(name, failure, query, expected, actual);
        items.add(reportItem);
    }
    previousDetailReport.setItems(items);

    reader.close();
    is.close();
    return previousDetailReport;
}
 
Example 7
Source File: LogRecordingHandler.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/** Returns a new instance of a list of published record messages. */
public List<String> messages() {
  List<String> result = Lists.newArrayList();
  for (LogRecord record : records) {
    result.add(record.getMessage());
  }
  return result;
}
 
Example 8
Source File: PlatformConverterUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static <T extends StringType> Collection<String> convertList(Iterable<T> vmlist) {
    Collection<String> result = Lists.newArrayList();
    for (T item : vmlist) {
        result.add(item.value());
    }
    return result;
}
 
Example 9
Source File: GoogleSpreadsheetWriter.java    From SPDS with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Prints the names and majors of students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 * @throws GeneralSecurityException 
 * @throws IOException 
 */
public static void write(List<Object> data) throws IOException, GeneralSecurityException  {
	Sheets service = getService();
	String sheetID = getGitRepositoryState().commitId;
	ArrayList<List<Object>> rows = Lists.newArrayList();
	rows.add(data);
	ValueRange body = new ValueRange().setValues(rows);
	service.spreadsheets().values().append(SPREADSHEET_ID, sheetID, body).setValueInputOption("USER_ENTERED")
			.execute();
}
 
Example 10
Source File: GoogleSheetsService.java    From q with Apache License 2.0 5 votes vote down vote up
private List<ReportItem> getReport(List<CellEntry> cellEntries, Map<String, String> header, boolean isDetailReport)
{
    List<ReportItem> returnValue = Lists.newArrayList();
    int previousRow = 0;
    ReportItem reportItem = null;
    for (CellEntry cell : cellEntries) {
        String column = getColumnFromCellAddress(cell);
        Integer row = getRowFromCellAddress(cell);
        String value = cell.getCell().getValue();
        if (row == 1)
            continue;
        if (previousRow != row) {
            if (row != 1 && reportItem!=null)
                returnValue.add(reportItem);
            if (isDetailReport)
                reportItem = new DetailReportItem();
            else
                reportItem = new SummaryReportItem();
        }
        String headerValue = header.get(column);
        reportItem.setValue(headerValue, value);
        previousRow = row;
    }
    if(reportItem!=null)
        returnValue.add(reportItem);
    return returnValue;
}
 
Example 11
Source File: DefaultIdentifiableObjectManager.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
@Transactional( readOnly = true )
public List<? extends IdentifiableObject> getAllByAttributeAndValues( Class<? extends IdentifiableObject> klass,
    Attribute attribute, List<String> values )
{
    IdentifiableObjectStore<IdentifiableObject> store = getIdentifiableObjectStore( klass );
    return store != null ? store.getAllByAttributeAndValues( attribute, values ) : Lists.newArrayList();
}
 
Example 12
Source File: GcpPlatformParameters.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private Collection<DiskType> getDiskTypes() {
    Collection<DiskType> disks = Lists.newArrayList();
    for (GcpDiskType diskType : GcpDiskType.values()) {
        disks.add(diskType(diskType.value()));
    }
    return disks;
}
 
Example 13
Source File: AbstractMemoryDataStore.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
public final Collection<V> values() throws IOException {
  lock.lock();
  try {
    List<V> result = Lists.newArrayList();
    for (byte[] bytes : keyValueMap.values()) {
      result.add(IOUtils.<V>deserialize(bytes));
    }
    return Collections.unmodifiableList(result);
  } finally {
    lock.unlock();
  }
}
 
Example 14
Source File: CloudSpannerPreparedStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testUpdateStatementWithCommitTimestampOneRow() throws SQLException {
  String sql = "UPDATE FOO SET COL1 = 'spanner.commit_timestamp()' WHERE ID = 1";
  Mutation updateMutation = getMutation(sql);
  Assert.assertNotNull(updateMutation);
  Assert.assertEquals(Op.UPDATE, updateMutation.getOperation());
  Assert.assertEquals("FOO", updateMutation.getTable());
  List<String> columns = Lists.newArrayList(updateMutation.getColumns());
  Assert.assertArrayEquals(new String[] {"COL1", "ID"}, columns.toArray());
  Assert.assertArrayEquals(new String[] {"spanner.commit_timestamp()", "1"},
      getValues(updateMutation.getValues()));
}
 
Example 15
Source File: FieldZipProcessor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private boolean checkConfigs(Record record) throws OnRecordErrorException {
  for (FieldZipConfig zipConfig : fieldZipConfigs) {
    List<String> missingFields = Lists.newArrayList();
    List<String> nonListFields = Lists.newArrayList();

    if (!record.has(zipConfig.firstField)) {
      missingFields.add(zipConfig.firstField);
    } else if (!record.get(zipConfig.firstField).getType().isOneOf(Field.Type.LIST, Field.Type.LIST_MAP)) {
      nonListFields.add(zipConfig.firstField);
    }
    if (!record.has(zipConfig.secondField)) {
      missingFields.add(zipConfig.secondField);
    } else if (!record.get(zipConfig.secondField).getType().isOneOf(Field.Type.LIST, Field.Type.LIST_MAP)) {
      nonListFields.add(zipConfig.secondField);
    }

    switch (onStagePreConditionFailure) {
      case TO_ERROR:
        if (!missingFields.isEmpty()) {
          throw new OnRecordErrorException(Errors.ZIP_01, missingFields);
        } else if (!nonListFields.isEmpty()) {
          throw new OnRecordErrorException(Errors.ZIP_00, nonListFields);
        }
        break;
      case CONTINUE:
        if(!missingFields.isEmpty() || !nonListFields.isEmpty()) {
          return false;
        }
        break;
      default:
        throw new IllegalStateException("Invalid value for on stage pre-condition failure");
    }
  }

  return true;
}
 
Example 16
Source File: CloudSpannerPreparedStatementTest.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Test
public void testUpdateStatementWithWhereClause() throws SQLException {
  Mutation updateMutation = getMutation("UPDATE FOO SET COL1=1, COL2=2 WHERE ID=1");
  Assert.assertNotNull(updateMutation);
  Assert.assertEquals(Op.UPDATE, updateMutation.getOperation());
  Assert.assertEquals("FOO", updateMutation.getTable());
  List<String> columns = Lists.newArrayList(updateMutation.getColumns());
  Assert.assertArrayEquals(new String[] {"COL1", "COL2", "ID"}, columns.toArray());
  Assert.assertArrayEquals(new String[] {"1", "2", "1"}, getValues(updateMutation.getValues()));
}
 
Example 17
Source File: GoogleDriveAdapter.java    From jdrivesync with Apache License 2.0 5 votes vote down vote up
private List<String> createParentReferenceList(SyncItem syncItem) {
	if (syncItem.getParent().isPresent()) {
		SyncDirectory syncItemParent = syncItem.getParent().get();
		Optional<File> remoteFileOptional = syncItemParent.getRemoteFile();
		if (remoteFileOptional.isPresent()) {
			return Arrays.asList(remoteFileOptional.get().getId());
		}
	}
	return Lists.newArrayList();
}
 
Example 18
Source File: GcpPlatformParameters.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public List<StackParamValidation> additionalStackParameters() {
    List<StackParamValidation> additionalStackParameterValidations = Lists.newArrayList();
    additionalStackParameterValidations.add(new StackParamValidation(TTL_MILLIS, false, String.class, Optional.of("^[0-9]*$")));
    return additionalStackParameterValidations;
}
 
Example 19
Source File: PCoAnalysis.java    From dataflow-java with Apache License 2.0 4 votes vote down vote up
private List<GraphResult> getPcaData(double[][] data, BiMap<Integer, String> dataNames) {
  int rows = data.length;
  int cols = data.length;

  // Center the similarity matrix.
  double matrixSum = 0;
  double[] rowSums = new double[rows];
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      matrixSum += data[i][j];
      rowSums[i] += data[i][j];
    }
  }
  double matrixMean = matrixSum / rows / cols;
  for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
      double rowMean = rowSums[i] / rows;
      double colMean = rowSums[j] / rows;
      data[i][j] = data[i][j] - rowMean - colMean + matrixMean;
    }
  }


  // Determine the eigenvectors, and scale them so that their
  // sum of squares equals their associated eigenvalue.
  Matrix matrix = new Matrix(data);
  EigenvalueDecomposition eig = matrix.eig();
  Matrix eigenvectors = eig.getV();
  double[] realEigenvalues = eig.getRealEigenvalues();

  for (int j = 0; j < eigenvectors.getColumnDimension(); j++) {
    double sumSquares = 0;
    for (int i = 0; i < eigenvectors.getRowDimension(); i++) {
      sumSquares += eigenvectors.get(i, j) * eigenvectors.get(i, j);
    }
    for (int i = 0; i < eigenvectors.getRowDimension(); i++) {
      eigenvectors.set(i, j, eigenvectors.get(i,j) * Math.sqrt(realEigenvalues[j] / sumSquares));
    }
  }


  // Find the indices of the top two eigenvalues.
  int maxIndex = -1;
  int secondIndex = -1;
  double maxEigenvalue = 0;
  double secondEigenvalue = 0;

  for (int i = 0; i < realEigenvalues.length; i++) {
    double eigenvector = realEigenvalues[i];
    if (eigenvector > maxEigenvalue) {
      secondEigenvalue = maxEigenvalue;
      secondIndex = maxIndex;
      maxEigenvalue = eigenvector;
      maxIndex = i;
    } else if (eigenvector > secondEigenvalue) {
      secondEigenvalue = eigenvector;
      secondIndex = i;
    }
  }


  // Return projected data
  List<GraphResult> results = Lists.newArrayList();
  for (int i = 0; i < rows; i++) {
    results.add(new GraphResult(dataNames.get(i),
        eigenvectors.get(i, maxIndex), eigenvectors.get(i, secondIndex)));
  }

  return results;
}
 
Example 20
Source File: Query.java    From async-datastore-client with Apache License 2.0 4 votes vote down vote up
Query() {
  query = com.google.datastore.v1.Query.newBuilder();
  filters = Lists.newArrayList();
}