本文整理汇总了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();
}
示例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);
}
示例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);
}
}
示例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();
}
示例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);
}
示例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();
}
示例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));
}
示例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 ;
}
示例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 () ;
}
}
示例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();
}
示例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;
}
示例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;
}
示例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);
}
示例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));
}
}
示例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();
}