List of usage examples for com.google.common.base Strings emptyToNull
@Nullable public static String emptyToNull(@Nullable String string)
From source file:com.google.appengine.tools.cloudstorage.oauth.AppIdentityURLFetchService.java
private AccessTokenProvider createAccessTokenProvider() { String providerClassName = Strings .emptyToNull(System.getProperty(AccessTokenProvider.SYSTEM_PROPERTY_NAME)); if (providerClassName != null) { try {/* w w w.j av a 2 s . c om*/ @SuppressWarnings("unchecked") Class<AccessTokenProvider> providerClass = (Class<AccessTokenProvider>) Class .forName(providerClassName); return providerClass.newInstance(); } catch (ClassCastException | ClassNotFoundException | InstantiationException | IllegalAccessException e) { logger.warning(String.format( "Unable to create AccessTokenProvider '%s'; falling back to default. Exception: %s\b", providerClassName, e)); } } return new AppIdentityAccessTokenProvider(); }
From source file:org.sonatype.nexus.jmx.internal.ManagedObjectRegistrar.java
/** * Determine {@link ObjectName} for given {@link BeanEntry}. *//* w ww . ja va 2 s . c o m*/ private ObjectName objectName(final ManagedObject descriptor, final BeanEntry<Annotation, Object> entry) throws Exception { Class<?> type = entry.getImplementationClass(); // default domain to package if missing String domain = descriptor.domain(); if (Strings.emptyToNull(domain) == null) { domain = type.getPackage().getName(); } // Hashtable is required by ancient JMX api Hashtable<String, String> entries = new Hashtable<>(); // add custom object-name entries for (ObjectNameEntry kv : descriptor.entries()) { entries.put(kv.name(), kv.value()); } // set object-name 'type' entries.put("type", type(descriptor, entry)); // optionally set object-name 'name' String name = name(descriptor, entry); if (name != null) { entries.put("name", name); } return new ObjectName(domain, entries); }
From source file:com.google.gerrit.server.change.Revert.java
@Override public Object apply(ChangeResource req, Input input) throws Exception { ChangeControl control = req.getControl(); Change change = req.getChange();/*from w ww . j av a2 s. c om*/ if (!control.canAddPatchSet()) { throw new AuthException("revert not permitted"); } else if (change.getStatus() != Status.MERGED) { throw new ResourceConflictException("change is " + status(change)); } final Repository git = gitManager.openRepository(control.getProject().getNameKey()); try { CommitValidators commitValidators = commitValidatorsFactory.create(control.getRefControl(), new NoSshInfo(), git); Change.Id revertedChangeId = ChangeUtil.revert(control.getRefControl(), change.currentPatchSetId(), (IdentifiedUser) control.getCurrentUser(), commitValidators, Strings.emptyToNull(input.message), dbProvider.get(), revertedSenderFactory, hooks, git, patchSetInfoFactory, myIdent, changeInserterFactory); return json.format(revertedChangeId); } catch (InvalidChangeOperationException e) { throw new BadRequestException(e.getMessage()); } finally { git.close(); } }
From source file:org.jclouds.googlecomputeengine.config.GoogleComputeEngineHttpApiModule.java
@Provides @Singleton/* w w w. ja v a2 s . c o m*/ @CurrentProject Supplier<URI> project(@Named(PROJECT_NAME) final String projectName, @Provider Supplier<URI> defaultEndpoint, final UseApiToResolveProjectName useApiToResolveProjectName, @Provider final Supplier<Credentials> creds, AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds) { // Try to avoid a runtime lookup by accepting a project name supplied in context overrides. if (Strings.emptyToNull(projectName) != null) { return Suppliers.memoizeWithExpiration(Suppliers.compose(new Function<URI, URI>() { @Override public URI apply(URI input) { return URI.create(String.format("%s/projects/%s", input, projectName)); } }, defaultEndpoint), seconds, SECONDS); } // If the project name wasn't explicitly supplied, then we lookup via api. // This supplier must be defensive against any auth exception. return MemoizedRetryOnTimeOutButNotOnAuthorizationExceptionSupplier.create(authException, compose(useApiToResolveProjectName, creds), seconds, SECONDS); }
From source file:org.jboss.pressgang.ccms.page.WebDriverFactory.java
private WebDriver configureFirefoxDriver() { final String pathToFirefox = Strings.emptyToNull(PropertiesHolder.properties.getProperty("firefox.path")); FirefoxBinary firefoxBinary = null;/*from w w w .j a va 2 s . c o m*/ if (pathToFirefox != null) { firefoxBinary = new FirefoxBinary(new File(pathToFirefox)); } else { firefoxBinary = new FirefoxBinary(); } /* * TODO: Evaluate current timeout * Timeout the connection in 30 seconds * firefoxBinary.setTimeout(TimeUnit.SECONDS.toMillis(30)); */ firefoxBinary.setEnvironmentProperty("DISPLAY", PropertiesHolder.properties.getProperty("webdriver.display")); return new FirefoxDriver(firefoxBinary, makeFirefoxProfile()); }
From source file:io.sarl.eclipse.properties.RuntimeEnvironmentPropertyPage.java
@Override protected Control createPreferenceContent(Composite composite) { this.sreBlock = new SREConfigurationBlock(true, null, null); Control ctrl = this.sreBlock.createControl(composite); this.sreBlock.initialize(); try {// w ww . ja v a 2 s. c o m String useSystemWide = getProject().getPersistentProperty(qualify(PROPERTY_NAME_USE_SYSTEM_WIDE_SRE)); String sreInstallId = getProject().getPersistentProperty(qualify(PROPERTY_NAME_SRE_INSTALL_ID)); ISREInstall sre = SARLRuntime.getSREFromId(sreInstallId); boolean notify = this.sreBlock.getNotify(); try { this.sreBlock.setNotify(false); this.sreBlock.selectSpecificSRE(sre); if (Boolean.parseBoolean( Objects.firstNonNull(Strings.emptyToNull(useSystemWide), Boolean.TRUE.toString()))) { this.sreBlock.selectSystemWideSRE(); } else { this.sreBlock.selectSpecificSRE(); } } finally { this.sreBlock.setNotify(notify); } } catch (CoreException e) { SARLEclipsePlugin.getDefault().log(e); } return ctrl; }
From source file:com.android.tools.idea.run.editor.EmulatorTargetProvider.java
@Override public DeployTarget<State> getDeployTarget() { return new DeployTarget<State>() { @Override/*www .j a v a2 s. c o m*/ public boolean hasCustomRunProfileState(@NotNull Executor executor) { return false; } @Override public RunProfileState getRunProfileState(@NotNull Executor executor, @NotNull ExecutionEnvironment env, @NotNull State state) throws ExecutionException { return null; } @Nullable @Override public DeviceFutures getDevices(@NotNull State state, @NotNull AndroidFacet facet, @NotNull DeviceCount deviceCount, boolean debug, int runConfigId) { return new EmulatorTargetChooser(facet, Strings.emptyToNull(state.PREFERRED_AVD)) .getDevices(deviceCount); } }; }
From source file:it.anyplace.sync.httprelay.client.HttpRelayConnection.java
protected HttpRelayConnection(String httpRelayServerUrl, String deviceId) { this.httpRelayServerUrl = httpRelayServerUrl; try {/* w w w . ja va2s . c om*/ HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage(HttpRelayProtos.HttpRelayPeerMessage .newBuilder().setMessageType(HttpRelayProtos.HttpRelayPeerMessageType.CONNECT) .setDeviceId(deviceId)); checkArgument(equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.PEER_CONNECTED)); checkNotNull(Strings.emptyToNull(serverMessage.getSessionId())); sessionId = serverMessage.getSessionId(); isServerSocket = serverMessage.getIsServerSocket(); outputStream = new OutputStream() { private ByteArrayOutputStream buffer = new ByteArrayOutputStream(); private long lastFlush = System.currentTimeMillis(); { flusherStreamService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { if (System.currentTimeMillis() - lastFlush > 1000) { try { flush(); } catch (IOException ex) { } } } }, 1, 1, TimeUnit.SECONDS); } @Override public synchronized void write(int i) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(i); } @Override public synchronized void write(byte[] bytes, int offset, int size) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(bytes, offset, size); } @Override public synchronized void flush() throws IOException { final ByteString data = ByteString.copyFrom(buffer.toByteArray()); buffer = new ByteArrayOutputStream(); try { if (!data.isEmpty()) { outgoingExecutorService.submit(new Runnable() { @Override public void run() { try { sendMessage(HttpRelayProtos.HttpRelayPeerMessage.newBuilder() .setMessageType( HttpRelayProtos.HttpRelayPeerMessageType.PEER_TO_RELAY) .setSequence(++peerToRelaySequence).setData(data)); } catch (Exception ex) { if (!isClosed()) { logger.error("error", ex); closeBg(); } throw ex; } } }).get(); } lastFlush = System.currentTimeMillis(); } catch (InterruptedException | ExecutionException ex) { logger.error("error", ex); closeBg(); throw new IOException(ex); } } @Override public synchronized void write(byte[] bytes) throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); buffer.write(bytes); } }; incomingExecutorService.submit(new Runnable() { @Override public void run() { while (!isClosed()) { try { HttpRelayProtos.HttpRelayServerMessage serverMessage = sendMessage( HttpRelayProtos.HttpRelayPeerMessage.newBuilder().setMessageType( HttpRelayProtos.HttpRelayPeerMessageType.WAIT_FOR_DATA)); if (isClosed()) { return; } checkArgument(equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.RELAY_TO_PEER)); checkArgument(serverMessage.getSequence() == relayToPeerSequence + 1); if (!serverMessage.getData().isEmpty()) { incomingDataQueue.add(serverMessage.getData().toByteArray()); } relayToPeerSequence = serverMessage.getSequence(); } catch (Exception ex) { if (!isClosed()) { logger.error("error", ex); closeBg(); } return; } } } }); inputStream = new InputStream() { private boolean noMoreData = false; private ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(new byte[0]); @Override public int read() throws IOException { checkArgument(!HttpRelayConnection.this.isClosed()); if (noMoreData) { return -1; } int bite; while ((bite = byteArrayInputStream.read()) == -1) { try { byte[] data = incomingDataQueue.poll(1, TimeUnit.SECONDS); if (data == null) { //continue } else if (data == STREAM_CLOSED) { noMoreData = true; return -1; } else { byteArrayInputStream = new ByteArrayInputStream(data); } } catch (InterruptedException ex) { } } return bite; } }; socket = new Socket() { @Override public boolean isClosed() { return HttpRelayConnection.this.isClosed(); } @Override public boolean isConnected() { return !isClosed(); } @Override public void shutdownOutput() throws IOException { logger.debug("shutdownOutput"); getOutputStream().flush(); } @Override public void shutdownInput() throws IOException { logger.debug("shutdownInput"); //do nothing } @Override public synchronized void close() throws IOException { logger.debug("received close on socket adapter"); HttpRelayConnection.this.close(); } @Override public OutputStream getOutputStream() throws IOException { return outputStream; } @Override public InputStream getInputStream() throws IOException { return inputStream; } @Override public SocketAddress getRemoteSocketAddress() { return new InetSocketAddress(getInetAddress(), getPort()); } @Override public int getPort() { return 22067; } @Override public InetAddress getInetAddress() { try { return InetAddress .getByName(URI.create(HttpRelayConnection.this.httpRelayServerUrl).getHost()); } catch (UnknownHostException ex) { throw new RuntimeException(ex); } } }; } catch (Exception ex) { close(); throw ex; } }
From source file:org.obm.service.attendee.AttendeeServiceJdbcImpl.java
@Override public ContactAttendee findContactAttendee(String name, String email, boolean createIfNeeded, ObmDomain domain, Integer ownerId) {// w ww .j a va 2s . c o m try { Contact contact = contactDao.findAttendeeContactFromEmailForUser(email, ownerId); if (contact != null) { return attendeeFromContact(contact); } if (createIfNeeded) { String displayedName = Objects.firstNonNull(Strings.emptyToNull(name), email); contact = contactDao.createCollectedContact(displayedName, email, domain, ownerId); return attendeeFromContact(contact); } } catch (Exception e) { throw Throwables.propagate(e); } return null; }
From source file:org.sosy_lab.cpachecker.cfa.types.java.JSimpleType.java
@Override public String toASTString(String pDeclarator) { List<String> parts = new ArrayList<>(); parts.add(Strings.emptyToNull(type.toASTString())); parts.add(Strings.emptyToNull(pDeclarator)); return Joiner.on(' ').skipNulls().join(parts); }