Example usage for com.google.common.base Strings emptyToNull

List of usage examples for com.google.common.base Strings emptyToNull

Introduction

In this page you can find the example usage for com.google.common.base Strings emptyToNull.

Prototype

@Nullable
public static String emptyToNull(@Nullable String string) 

Source Link

Document

Returns the given string if it is nonempty; null otherwise.

Usage

From source file:com.eucalyptus.imaging.backend.ImagingTasks.java

public static ImportInstanceImagingTask createImportInstanceTask(final ImportInstanceType request)
        throws ImagingServiceException {
    // verify the input
    final ImportInstanceLaunchSpecification launchSpec = request.getLaunchSpecification();
    if (launchSpec == null)
        throw new ImagingServiceException("Launch specification is required");
    if (launchSpec.getArchitecture() == null
            || !("i386".equals(launchSpec.getArchitecture()) || "x86_64".equals(launchSpec.getArchitecture())))
        throw new ImagingServiceException("Architecture should be either i386 or x86_64");
    if (launchSpec.getInstanceType() == null)
        throw new ImagingServiceException("Instance type is required");

    if (launchSpec.getKeyName() != null && launchSpec.getKeyName().length() > 0) {
        try {/*from   w w  w .jav a  2 s.c  o m*/
            final List<DescribeKeyPairsResponseItemType> keys = Ec2Client.getInstance().describeKeyPairs(
                    Contexts.lookup().getUser().getUserId(), Lists.newArrayList(launchSpec.getKeyName()));
            if (!launchSpec.getKeyName().equals(keys.get(0).getKeyName()))
                throw new Exception();
        } catch (final Exception ex) {
            throw new ImagingServiceException("Key " + launchSpec.getKeyName() + " is not found");
        }
    }

    String availabilityZone = null;
    if (Strings.emptyToNull(launchSpec.getSubnetId()) != null) {
        try {
            final List<SubnetType> subnets = Ec2Client.getInstance().describeSubnets(
                    Contexts.lookup().getUser().getUserId(), Lists.newArrayList(launchSpec.getSubnetId()));
            if (subnets.size() != 1) {
                throw new ImagingServiceException("Subnet " + launchSpec.getSubnetId() + " not found");
            }
            availabilityZone = subnets.get(0).getAvailabilityZone();
            final String cidr = subnets.get(0).getCidrBlock();
            final String privateIp = Strings.emptyToNull(launchSpec.getPrivateIpAddress());
            if (privateIp != null && !Cidr.parse(cidr).contains(privateIp)) {
                throw new ImagingServiceException(
                        "Private IP " + privateIp + " not valid for subnet " + launchSpec.getSubnetId());
            }
        } catch (final Exception ex) {
            Exceptions.findAndRethrow(ex, ImagingServiceException.class);
            throw new ImagingServiceException("Subnet " + launchSpec.getSubnetId() + " not found");
        }
    }

    final List<String> clusters;
    try {
        clusters = ImagingServiceProperties.listConfiguredZones();
    } catch (final Exception ex) {
        throw new ImagingServiceException(ImagingServiceException.INTERNAL_SERVER_ERROR,
                "Failed to verify availability zones");
    }

    if (availabilityZone == null) {
        if (launchSpec.getPlacement() != null) {
            availabilityZone = launchSpec.getPlacement().getAvailabilityZone();
        } else if (clusters.size() > 0) { //Default: Amazon EC2 chooses a zone for you.
            availabilityZone = clusters.get(0);
        } else {
            throw new ImagingServiceException(ImagingServiceException.INTERNAL_SERVER_ERROR,
                    "No availability zone is found in the Cloud");
        }
    }
    if (!clusters.contains(availabilityZone)) {
        throw new ImagingServiceException(
                String.format("The availability zone %s is not configured for import", availabilityZone));
    }
    if (request.getLaunchSpecification().getPlacement() == null)
        request.getLaunchSpecification().setPlacement(new InstancePlacement());
    request.getLaunchSpecification().getPlacement().setAvailabilityZone(availabilityZone);

    List<DiskImage> disks = request.getDiskImageSet();
    if (disks == null || disks.size() <= 0)
        throw new ImagingServiceException("Disk images are required");

    for (final DiskImage disk : disks) {
        final DiskImageDetail imageDetail = disk.getImage();
        final String format = imageDetail.getFormat();
        if (format == null || format.length() <= 0)
            throw new ImagingServiceException("Image format is required");
        try {
            final IMAGE_FORMAT imgFormat = IMAGE_FORMAT.valueOf(format.toUpperCase());
        } catch (final Exception ex) {
            throw new ImagingServiceException("Unsupported image format: " + format);
        }
        if (imageDetail.getImportManifestUrl() == null)
            throw new ImagingServiceException("Import manifest url is required");
        // TODO: manifest at S3
        final DiskImageVolume volumeDetail = disk.getVolume();
        if (volumeDetail == null)
            throw new ImagingServiceException("Volume detail is required for disk image");

        try {
            /// TODO: should we assume the converted image is always larger than or equal to the uploaded image
            final int volumeSize = volumeDetail.getSize();
            if (getMaxVolumeSize(availabilityZone) < volumeSize)
                throw new ImagingServiceException("Requested volume size exceeds max allowed volume size");
            final long imageBytes = imageDetail.getBytes();
            final long volumeSizeInBytes = (volumeSize * (long) Math.pow(1024, 3));
            if (imageBytes > volumeSizeInBytes)
                throw new ImagingServiceException("Requested volume size is not enough to hold the image");
        } catch (final ImagingServiceException ex) {
            throw ex;
        } catch (final Exception ex) {
            throw new ImagingServiceException(ImagingServiceException.INTERNAL_SERVER_ERROR,
                    "Failed to verify the requested volume size");
        }
    }
    final ImportInstanceImagingTask transform = TypeMappers.transform(request, ImportInstanceImagingTask.class);
    try (final TransactionResource db = Entities.transactionFor(ImportInstanceImagingTask.class)) {
        try {
            Entities.persist(transform);
            db.commit();
        } catch (final Exception ex) {
            throw new ImagingServiceException(ImagingServiceException.INTERNAL_SERVER_ERROR,
                    "Failed to persist InstanceImagingTask", ex);
        }
    }
    return transform;
}

From source file:com.kik.config.ice.internal.ConfigDescriptorFactory.java

private Optional<String> getMethodDefaultValue(Method method) {
    DefaultValue defaultValue = method.getAnnotation(DefaultValue.class);
    return defaultValue == null ? Optional.empty()
            : Optional.ofNullable(Strings.emptyToNull(defaultValue.value()));
}

From source file:fr.aliacom.obm.common.contact.UserDao.java

private String buildFullStreetAddressFromResultSet(ResultSet rs) throws SQLException {
    return Joiner.on(" ").skipNulls().join(Strings.emptyToNull(rs.getString("userobm_address1")),
            Strings.emptyToNull(rs.getString("userobm_address2")),
            Strings.emptyToNull(rs.getString("userobm_address3")));
}

From source file:de.schildbach.wallet.ui.EncryptKeysDialogFragment.java

private void handleGo() {
    final String oldPassword = Strings.emptyToNull(oldPasswordView.getText().toString().trim());
    final String newPassword = Strings.emptyToNull(newPasswordView.getText().toString().trim());

    if (oldPassword != null && newPassword != null)
        log.info("changing spending password");
    else if (newPassword != null)
        log.info("setting spending password");
    else if (oldPassword != null)
        log.info("removing spending password");
    else/*from   w  w w .j a va2s.co  m*/
        throw new IllegalStateException();

    state = State.CRYPTING;
    updateView();

    backgroundHandler.post(new Runnable() {
        @Override
        public void run() {
            // For the old key, we use the key crypter that was used to derive the password in the first
            // place.
            final KeyParameter oldKey = oldPassword != null ? wallet.getKeyCrypter().deriveKey(oldPassword)
                    : null;

            // For the new key, we create a new key crypter according to the desired parameters.
            final KeyCrypterScrypt keyCrypter = new KeyCrypterScrypt(application.scryptIterationsTarget());
            final KeyParameter newKey = newPassword != null ? keyCrypter.deriveKey(newPassword) : null;

            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (wallet.isEncrypted()) {
                        if (oldKey == null) {
                            log.info("wallet is encrypted, but did not provide spending password");
                            state = State.INPUT;
                            oldPasswordView.requestFocus();
                        } else {
                            try {
                                wallet.decrypt(oldKey);

                                state = State.DONE;
                                log.info("wallet successfully decrypted");
                            } catch (final KeyCrypterException x) {
                                log.info("wallet decryption failed: " + x.getMessage());
                                badPasswordView.setVisibility(View.VISIBLE);
                                state = State.INPUT;
                                oldPasswordView.requestFocus();
                            }
                        }
                    }

                    if (newKey != null && !wallet.isEncrypted()) {
                        wallet.encrypt(keyCrypter, newKey);

                        log.info(
                                "wallet successfully encrypted, using key derived by new spending password ({} scrypt iterations)",
                                keyCrypter.getScryptParameters().getN());
                        state = State.DONE;
                    }

                    updateView();

                    if (state == State.DONE) {
                        application.backupWallet();
                        delayedDismiss();
                    }
                }

                private void delayedDismiss() {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            dismiss();
                        }
                    }, 2000);
                }
            });
        }
    });
}

From source file:org.sonatype.nexus.jmx.internal.ManagedObjectRegistrar.java

/**
 * Construct mbean for given {@link BeanEntry} discovering its attributes and operations.
 *//*from  w w  w.  j  a v a  2  s. c  o m*/
private MBean mbean(final ManagedObject descriptor, final BeanEntry<Annotation, Object> entry)
        throws Exception {
    Class<?> type = entry.getImplementationClass();

    ReflectionMBeanBuilder builder = new ReflectionMBeanBuilder(type);

    // attach manged target
    builder.target(new Supplier() {
        @Override
        public Object get() {
            return entry.getProvider().get();
        }
    });

    // allow custom description, or expose what sisu tells us
    String description = Strings.emptyToNull(descriptor.description());
    if (description == null) {
        description = entry.getDescription();
    }
    builder.description(description);

    // discover managed members
    builder.discover();

    // expose additional information we have about the bean
    builder.attribute(new SuppliedMBeanAttribute.Builder().name("sisu.key").description("Sisu bean-key")
            .value(entry.getKey().toString()).build());
    builder.attribute(new SuppliedMBeanAttribute.Builder().name("sisu.rank").description("Sisu bean-rank")
            .value(entry.getRank()).build());
    builder.attribute(new SuppliedMBeanAttribute.Builder().name("sisu.source").description("Sisu bean-source")
            .value(entry.getSource().toString()).build());
    builder.attribute(new SuppliedMBeanAttribute.Builder().name("sisu.description")
            .description("Sisu bean-description").type(String.class).value(entry.getDescription()).build());

    return builder.build();
}

From source file:de.schildbach.pte.InvgProvider.java

@Override
public QueryDeparturesResult queryDepartures(final String stationId, final @Nullable Date time,
        final int maxDepartures, final boolean equivs) throws IOException {
    checkNotNull(Strings.emptyToNull(stationId));

    final ResultHeader header = new ResultHeader(network, SERVER_PRODUCT);
    final QueryDeparturesResult result = new QueryDeparturesResult(header);

    // scrape page
    final HttpUrl.Builder url = stationBoardEndpoint.newBuilder().addPathSegment(apiLanguage);
    appendXmlStationBoardParameters(url, time, stationId, maxDepartures, false, null);
    final CharSequence page = httpClient.get(url.build());

    // parse page
    final Matcher mHeadCoarse = P_DEPARTURES_HEAD_COARSE.matcher(page);
    if (mHeadCoarse.matches()) {
        // messages
        if (mHeadCoarse.group(4) != null) {
            result.stationDepartures.add(new StationDepartures(new Location(LocationType.STATION, stationId),
                    Collections.<Departure>emptyList(), null));
            return result;
        } else if (mHeadCoarse.group(5) != null)
            return new QueryDeparturesResult(header, Status.INVALID_STATION);
        else if (mHeadCoarse.group(6) != null)
            return new QueryDeparturesResult(header, Status.SERVICE_DOWN);

        final String locationId = mHeadCoarse.group(2);

        final Matcher mHeadFine = P_DEPARTURES_HEAD_FINE.matcher(mHeadCoarse.group(1));
        if (mHeadFine.matches()) {
            final String[] placeAndName = splitStationName(ParserUtils.resolveEntities(mHeadFine.group(1)));
            final Calendar currentTime = new GregorianCalendar(timeZone);
            currentTime.clear();//from  w  w  w  . j  a va2s.  c  o m
            ParserUtils.parseGermanDate(currentTime, mHeadFine.group(2));
            ParserUtils.parseEuropeanTime(currentTime, mHeadFine.group(3));
            final List<Departure> departures = new ArrayList<>(8);
            String oldZebra = null;

            final Matcher mDepCoarse = P_DEPARTURES_COARSE.matcher(mHeadCoarse.group(3));
            while (mDepCoarse.find()) {
                final String zebra = mDepCoarse.group(1);
                if (oldZebra != null && zebra.equals(oldZebra))
                    throw new IllegalArgumentException("missed row? last:" + zebra);
                else
                    oldZebra = zebra;

                final Matcher mDepFine = P_DEPARTURES_FINE.matcher(mDepCoarse.group(2));
                if (mDepFine.matches()) {
                    final Calendar plannedTime = new GregorianCalendar(timeZone);
                    plannedTime.setTimeInMillis(currentTime.getTimeInMillis());
                    ParserUtils.parseEuropeanTime(plannedTime, mDepFine.group(1));

                    if (plannedTime.getTimeInMillis()
                            - currentTime.getTimeInMillis() < -PARSER_DAY_ROLLOVER_THRESHOLD_MS)
                        plannedTime.add(Calendar.DAY_OF_MONTH, 1);

                    final Calendar predictedTime;
                    final String prognosis = ParserUtils.resolveEntities(mDepFine.group(2));
                    if (prognosis != null) {
                        predictedTime = new GregorianCalendar(timeZone);
                        if (prognosis.equals("pnktlich")) {
                            predictedTime.setTimeInMillis(plannedTime.getTimeInMillis());
                        } else {
                            predictedTime.setTimeInMillis(currentTime.getTimeInMillis());
                            ParserUtils.parseEuropeanTime(predictedTime, prognosis);
                        }
                    } else {
                        predictedTime = null;
                    }

                    final String lineType = mDepFine.group(3);

                    final Line line = parseLine(lineType, ParserUtils.resolveEntities(mDepFine.group(4)),
                            false);

                    final String destinationId = mDepFine.group(5);
                    final String destinationName = ParserUtils.resolveEntities(mDepFine.group(6));
                    final Location destination;
                    if (destinationId != null) {
                        final String[] destinationPlaceAndName = splitStationName(destinationName);
                        destination = new Location(LocationType.STATION, destinationId,
                                destinationPlaceAndName[0], destinationPlaceAndName[1]);
                    } else {
                        destination = new Location(LocationType.ANY, null, null, destinationName);
                    }

                    final Position position = parsePosition(ParserUtils.resolveEntities(mDepFine.group(7)));

                    final Departure dep = new Departure(plannedTime.getTime(),
                            predictedTime != null ? predictedTime.getTime() : null, line, position, destination,
                            null, null);

                    if (!departures.contains(dep))
                        departures.add(dep);
                } else {
                    throw new IllegalArgumentException(
                            "cannot parse '" + mDepCoarse.group(2) + "' on " + stationId);
                }
            }

            result.stationDepartures.add(new StationDepartures(
                    new Location(LocationType.STATION, locationId, placeAndName[0], placeAndName[1]),
                    departures, null));
            return result;
        } else {
            throw new IllegalArgumentException("cannot parse '" + mHeadCoarse.group(1) + "' on " + stationId);
        }
    } else {
        throw new IllegalArgumentException("cannot parse '" + page + "' on " + stationId);
    }
}

From source file:io.druid.query.groupby.epinephelinae.RowBasedGrouperHelper.java

public static CloseableGrouperIterator<RowBasedKey, Row> makeGrouperIterator(final Grouper<RowBasedKey> grouper,
        final GroupByQuery query, final Closeable closeable) {
    return new CloseableGrouperIterator<>(grouper, true, new Function<Grouper.Entry<RowBasedKey>, Row>() {
        @Override//ww  w. ja  v a 2s .c om
        public Row apply(Grouper.Entry<RowBasedKey> entry) {
            Map<String, Object> theMap = Maps.newLinkedHashMap();

            // Add dimensions.
            for (int i = 0; i < entry.getKey().getDimensions().length; i++) {
                theMap.put(query.getDimensions().get(i).getOutputName(),
                        Strings.emptyToNull(entry.getKey().getDimensions()[i]));
            }

            // Add aggregations.
            for (int i = 0; i < entry.getValues().length; i++) {
                theMap.put(query.getAggregatorSpecs().get(i).getName(), entry.getValues()[i]);
            }

            return new MapBasedRow(query.getGranularity().toDateTime(entry.getKey().getTimestamp()), theMap);
        }
    }, closeable);
}

From source file:com.reprezen.swagedit.schema.SwaggerSchema.java

protected JsonSchema getSchema(String id) {
    return Strings.emptyToNull(id) == null ? swaggerType : schemas.get(id);
}

From source file:google.registry.model.server.Lock.java

/**
 * Acquire one or more locks and execute a Void {@link Callable} on a thread that will be
 * killed if it doesn't complete before the lease expires.
 *
 * <p>If the requester isn't null, this will join each lock's queue before attempting to acquire
 * that lock. Clients that are concerned with starvation should specify a requester and those that
 * aren't shouldn't.//from  w  ww  . ja v a 2s.co  m
 *
 * <p>Note that locks are specific either to a given tld or to the entire system (in which case
 * tld should be passed as null).
 *
 * @return whether all locks were acquired and the callable was run.
 */
public static boolean executeWithLocks(final Callable<Void> callable, @Nullable Class<?> requester,
        @Nullable String tld, Duration leaseLength, String... lockNames) {
    try {
        return AppEngineTimeLimiter.create().callWithTimeout(
                new LockingCallable(callable, requester, Strings.emptyToNull(tld), leaseLength, lockNames),
                leaseLength.minus(LOCK_TIMEOUT_FUDGE).getMillis(), TimeUnit.MILLISECONDS, true);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}