当前位置: 首页>>代码示例>>Java>>正文


Java Preconditions类代码示例

本文整理汇总了Java中com.google.api.client.repackaged.com.google.common.base.Preconditions的典型用法代码示例。如果您正苦于以下问题:Java Preconditions类的具体用法?Java Preconditions怎么用?Java Preconditions使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Preconditions类属于com.google.api.client.repackaged.com.google.common.base包,在下文中一共展示了Preconditions类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: init

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Performs all necessary setup steps for running requests against the API.
 *
 * @param applicationName the name of the application: com.example.app
 * @param serviceAccountEmail the Service Account Email (empty if using
 *            installed application)
 * @return the {@Link AndroidPublisher} service
 * @throws GeneralSecurityException
 * @throws IOException
 */
public static AndroidPublisher init(String applicationName,
                                    @Nullable String serviceAccountEmail) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName),
            "applicationName cannot be null or empty!");

    // Authorization.
    newTrustedTransport();
    Credential credential;
    if (serviceAccountEmail == null || serviceAccountEmail.isEmpty()) {
        //TODO : ask for the service account and key.p12 file with a dialog ;)
        credential = authorizeWithServiceAccount(serviceAccountEmail);
    } else {
        credential = authorizeWithServiceAccount(serviceAccountEmail);
    }

    // Set up and return API client.
    return new AndroidPublisher.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName)
            .build();
}
 
开发者ID:droidchef,项目名称:pubplug,代码行数:31,代码来源:AndroidPublisherHelper.java

示例2: parseJsonRequest

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Parse HttpServletRequest to JSON-RPC request
 * Assumed the request content is encoded with UTF-8
 * @param request HttpServletRequest
 * @return JSONRPC2Request
 * @throws IOException
 */
protected JSONRPC2Request parseJsonRequest(HttpServletRequest request) throws IOException, JSONRPC2ParseException {
    String contentType = request.getHeader("Content-Type");
    Integer contentLength = Ints.tryParse(request.getHeader("Content-Length"));
    Preconditions.checkArgument(requestValidator(contentType, contentLength), "Invalid JSON request");
    BufferedReader reader = request.getReader();
    StringBuffer message = new StringBuffer();
    char[] buffer = new char[contentLength];
    int numRead = 0;
    while (numRead < contentLength) {
        int read = reader.read(buffer, 0, buffer.length);
        String s = new String(buffer, 0, read);
        numRead += s.getBytes(Charsets.UTF_8).length;
        message.append(s);
    }
    return JSONRPC2Request.parse(message.toString(), true, true, true);
}
 
开发者ID:victor-guoyu,项目名称:Review-It,代码行数:24,代码来源:JsonServlet.java

示例3: indexParsedDocument

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
public void indexParsedDocument(ParsedComment document) {
    Preconditions.checkNotNull(indexWriter,
            "The index writer is not initialized");
    Document newDoc = new Document();
    newDoc.add(new TextField(ParsedComment.Fields.SEARCHABLE_TEXT.name(),
            document.fullSearchableText(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.ID.name(),
            document.getId(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.PRODUCT_NAME.name(),
            document.getProductName(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.COMMENT.name(),
            document.getComment(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.URL.name(),
            document.getCommentUrl(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.SOURCE.name(),
            document.getSource().name(), Field.Store.YES));
    newDoc.add(new StringField(ParsedComment.Fields.LABEL.name(),
            document.getCommentLabel(), Field.Store.YES));
    try {
        indexWriter.addDocument(newDoc);
        indexWriter.commit();
    } catch (IOException e) {
        throw new RuntimeException(
                "Could not write new document to the index directory", e);
    }
}
 
开发者ID:victor-guoyu,项目名称:Review-It,代码行数:27,代码来源:Indexer.java

示例4: adapt

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public RowFilter adapt(FilterAdapterContext context, FuzzyRowFilter filter) throws IOException {
  Interleave.Builder interleaveBuilder = Interleave.newBuilder();
  List<Pair<byte[], byte[]>> pairs = extractFuzzyRowFilterPairs(filter);
  if (pairs.isEmpty()) {
    return ALL_VALUES_FILTER;
  }
  for (Pair<byte[], byte[]> pair : pairs) {
    Preconditions.checkArgument(
        pair.getFirst().length == pair.getSecond().length,
        "Fuzzy info and match mask must have the same length");
    interleaveBuilder.addFilters(
        createSingleRowFilter(
            pair.getFirst(), pair.getSecond()));
  }
  return RowFilter.newBuilder().setInterleave(interleaveBuilder).build();
}
 
开发者ID:dmmcerlean,项目名称:cloud-bigtable-client,代码行数:18,代码来源:FuzzyRowFilterAdapter.java

示例5: sync

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Synchronizes the given list of messages with Gmail. When this operation
 * completes, all of the messages will appear in Gmail with the same labels
 * (folers) that they have in the local store. The message state, including
 * read/unread, will also be synchronized, but might not match exactly if
 * the message is already in Gmail.
 *
 * <p>Note that some errors can prevent some messages from being uploaded.
 * In this case, the failure policy dictates what happens.
 *
 * @param messages the list of messages to synchronize. These messages may
 *     or may not already exist in Gmail.
 * @throws IOException if something goes wrong with the connection
 */
public void sync(List<LocalMessage> messages) throws IOException {
  Preconditions.checkState(initialized,
      "GmailSyncer.init() must be called first");
  Multimap<LocalMessage, Message> map = mailbox.mapMessageIds(messages);
  messages.stream()
      .filter(message -> !map.containsKey(message))
      .forEach(message -> {
        try {
          Message gmailMessage = mailbox.uploadMessage(message);
          map.put(message, gmailMessage);
        } catch (GoogleJsonResponseException e) {
          // Message couldn't be uploaded, but we know why
        }
      });
  mailbox.fetchExistingLabels(map.values());
  mailbox.syncLocalLabelsToGmail(map);
}
 
开发者ID:google,项目名称:mail-importer,代码行数:32,代码来源:GmailSyncer.java

示例6: init

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Performs all necessary setup steps for running requests against the API.
 *
 * @param applicationName the name of the application: com.example.app
 * @param serviceAccountEmail the Service Account Email (empty if using
 *            installed application)
 * @return the {@Link AndroidPublisher} service
 * @throws GeneralSecurityException
 * @throws IOException
 */
protected static AndroidPublisher init(String applicationName,
                                       @Nullable String serviceAccountEmail) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName),
            "applicationName cannot be null or empty!");

    // Authorization.
    newTrustedTransport();
    Credential credential;
    if (serviceAccountEmail == null || serviceAccountEmail.isEmpty()) {
        credential = authorizeWithInstalledApplication();
    } else {
        credential = authorizeWithServiceAccount(serviceAccountEmail);
    }

    // Set up and return API client.
    return new AndroidPublisher.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName)
            .build();
}
 
开发者ID:wisobi,项目名称:leanbean,代码行数:30,代码来源:AndroidPublisherHelper.java

示例7: ErrorReportDialog

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
public ErrorReportDialog (Stage owner, Collection<ErrorModel> errs) throws IOException {
	super (owner) ;
	
	Preconditions.checkNotNull(errs);
	
	initStyle(StageStyle.UTILITY);
	setTitle("Error Report");
	initOwner(owner);
	initModality (Modality.WINDOW_MODAL );
	
	final FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/ErrorReportView.fxml"));
	final Parent parent = (Parent) loader.load();
	final ErrorReportViewController controller = loader.<ErrorReportViewController> getController();

	controller.addErrors(errs);
	
	setMinHeight(300.0);
	setMinWidth(400.0);

	setHeight(500.0);
	setWidth(750.0);
	
	setScene(new Scene(parent));
}
 
开发者ID:roikku,项目名称:drive-uploader,代码行数:25,代码来源:ErrorReportDialog.java

示例8: getHttpClient

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
public static CloseableHttpClient getHttpClient (HasProxySettings proxySetting) {
	// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475
	
	CloseableHttpClient httpclient = null ;
	if (proxySetting != null && proxySetting.isActive()) {
		logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")") ;
		CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider()) ;
    	HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
    	DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    	httpclient = HttpClients.custom()
    	        .setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credsProvider)
    	        .build();
	} else {
		httpclient = HttpClients.createDefault();
	}
	return httpclient ;
}
 
开发者ID:roikku,项目名称:drive-uploader,代码行数:18,代码来源:HttpClientUtils.java

示例9: DriveAuth

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
public DriveAuth(boolean useOldApi, HasConfiguration config) throws IOException {
	super () ;
	this.config = Preconditions.checkNotNull(config) ;
	this.proxySetting = config.getHttpProxySettings() ;

    clientSecret = config.getAuthenticationSettings().getClientSecret();
    clientId = config.getAuthenticationSettings().getClientId();
    config.getAuthenticationSettings().getCallBackUrl();
    refreshToken = config.getCredential().getRefreshToken() ;

    int retry = 0;
    boolean tokensOK = false;
    while (!tokensOK && retry < maxRetries) {
        tokensOK = updateAccessToken();
        ++retry;
    }
    if (!tokensOK) {
    	logger.info("Authentication aborted after " + maxRetries + " retries.");
        throw new IllegalStateException () ;
    }
}
 
开发者ID:roikku,项目名称:drive-uploader,代码行数:22,代码来源:DriveAuth.java

示例10: init

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Performs all necessary setup steps for running requests against the API.
 *
 * @param applicationName the name of the application: com.example.app
 * @param serviceAccountEmail the Service Account Email (empty if using
 *            installed application)
 * @return the {@Link AndroidPublisher} service
 * @throws GeneralSecurityException
 * @throws IOException
 */
protected static AndroidPublisher init(String applicationName,
        String serviceAccountEmail, File serviceAccountKeyFile)
throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName),
            "Application name cannot be null or empty!");

    // Authorization.
    newTrustedTransport();
    Credential credential = authorizeWithServiceAccount(serviceAccountEmail, serviceAccountKeyFile);

    // Set up and return API client.
    return new AndroidPublisher.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName)
            .build();
}
 
开发者ID:bluesliverx,项目名称:gradle-android-publisher,代码行数:26,代码来源:AndroidPublisherHelper.java

示例11: getAndVerifyExtension

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
private AndroidPublisherExtension getAndVerifyExtension() {
	AndroidPublisherExtension publisherExtension = getProject().getExtensions()
			.getByType(AndroidPublisherExtension.class);

	Preconditions.checkArgument(!Strings.isNullOrEmpty(
					publisherExtension.getApplicationName()),
			"Application name cannot be null or empty!");
	Preconditions.checkArgument(!Strings.isNullOrEmpty(
					publisherExtension.getTrack()),
			"Track cannot be null or empty!");
	Preconditions.checkArgument(!Strings.isNullOrEmpty(
					publisherExtension.getVariantName()),
			"Variant name cannot be null or empty!");
	Preconditions.checkArgument(!Strings.isNullOrEmpty(
					publisherExtension.getPackageName()),
			"Package name cannot be null or empty!");
	Preconditions.checkArgument(!Strings.isNullOrEmpty(
					publisherExtension.getServiceAccountEmail()),
			"Service account email cannot be null or empty!");
	Preconditions.checkArgument(publisherExtension.getServiceAccountKeyFile() != null,
			"Service account key file cannot be null or empty!");

	return publisherExtension;
}
 
开发者ID:bluesliverx,项目名称:gradle-android-publisher,代码行数:25,代码来源:AndroidPublishTask.java

示例12: getPages

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
@Override
public List<String> getPages(String siteProperty, String startDate, String endDate, String country, int rowLimit,
    List<GoogleWebmasterFilter.Dimension> requestedDimensions, List<ApiDimensionFilter> filters, int startRow)
    throws IOException {
  checkRowLimit(rowLimit);
  Preconditions.checkArgument(requestedDimensions.contains(GoogleWebmasterFilter.Dimension.PAGE));

  SearchAnalyticsQueryResponse rspByCountry =
      createSearchAnalyticsQuery(siteProperty, startDate, endDate, requestedDimensions,
          GoogleWebmasterFilter.andGroupFilters(filters), rowLimit, startRow).execute();

  List<ApiDataRow> pageRows = rspByCountry.getRows();
  List<String> pages = new ArrayList<>(rowLimit);
  if (pageRows != null) {
    int pageIndex = requestedDimensions.indexOf(GoogleWebmasterFilter.Dimension.PAGE);
    for (ApiDataRow row : pageRows) {
      pages.add(row.getKeys().get(pageIndex));
    }
  }
  return pages;
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:22,代码来源:GoogleWebmasterClientImpl.java

示例13: getExtractor

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * As Google Drive extractor needs file system helper, it invokes to initialize file system helper.
 * {@inheritDoc}
 * @see org.apache.gobblin.source.Source#getExtractor(org.apache.gobblin.configuration.WorkUnitState)
 */
@Override
public Extractor<S, D> getExtractor(WorkUnitState state) throws IOException {
  Preconditions.checkNotNull(state, "WorkUnitState should not be null");
  LOG.info("WorkUnitState from getExtractor: " + state);

  try {
    //GoogleDriveExtractor needs GoogleDriveFsHelper
    initFileSystemHelper(state);
  } catch (FileBasedHelperException e) {
    throw new IOException(e);
  }

  Preconditions.checkNotNull(fsHelper, "File system helper should not be null");
  return new GoogleDriveExtractor<>(state, fsHelper);
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:21,代码来源:GoogleDriveSource.java

示例14: initFileSystemHelper

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Initialize file system helper at most once for this instance.
 * {@inheritDoc}
 * @see org.apache.gobblin.source.extractor.filebased.FileBasedSource#initFileSystemHelper(org.apache.gobblin.configuration.State)
 */
@Override
public synchronized void initFileSystemHelper(State state) throws FileBasedHelperException {
  if (fsHelper == null) {
    Credential credential = new GoogleCommon.CredentialBuilder(state.getProp(SOURCE_CONN_PRIVATE_KEY), state.getPropAsList(API_SCOPES))
                                            .fileSystemUri(state.getProp(PRIVATE_KEY_FILESYSTEM_URI))
                                            .proxyUrl(state.getProp(SOURCE_CONN_USE_PROXY_URL))
                                            .port(state.getProp(SOURCE_CONN_USE_PROXY_PORT))
                                            .serviceAccountId(state.getProp(SOURCE_CONN_USERNAME))
                                            .build();

    Drive driveClient = new Drive.Builder(credential.getTransport(),
                                          GoogleCommon.getJsonFactory(),
                                          credential)
                                 .setApplicationName(Preconditions.checkNotNull(state.getProp(APPLICATION_NAME), "ApplicationName is required"))
                                 .build();
    this.fsHelper = closer.register(new GoogleDriveFsHelper(state, driveClient));
  }
}
 
开发者ID:apache,项目名称:incubator-gobblin,代码行数:24,代码来源:GoogleDriveSource.java

示例15: init

import com.google.api.client.repackaged.com.google.common.base.Preconditions; //导入依赖的package包/类
/**
 * Performs all necessary setup steps for running requests against the API.
 *
 * @param applicationName the name of the application: com.example.app
 * @param serviceAccountEmail the Service Account Email (empty if using
 *            installed application)
 * @return the {@Link AndroidPublisher} service
 * @throws GeneralSecurityException
 * @throws IOException
 */
protected static AndroidPublisher init(String applicationName,
        @Nullable String serviceAccountEmail) throws IOException, GeneralSecurityException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(applicationName),
            "applicationName cannot be null or empty!");

    // Authorization.
    newTrustedTransport();
    Credential credential;
    if (serviceAccountEmail == null || serviceAccountEmail.isEmpty()) {
        credential = authorizeWithInstalledApplication();
    } else {
        credential = authorizeWithServiceAccount(serviceAccountEmail);
    }

    // Set up and return API client.
    return new AndroidPublisher.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(applicationName)
            .build();
}
 
开发者ID:rocel,项目名称:playstorepublisher,代码行数:30,代码来源:AndroidPublisherHelper.java


注:本文中的com.google.api.client.repackaged.com.google.common.base.Preconditions类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。