Example usage for java.util Collections singletonMap

List of usage examples for java.util Collections singletonMap

Introduction

In this page you can find the example usage for java.util Collections singletonMap.

Prototype

public static <K, V> Map<K, V> singletonMap(K key, V value) 

Source Link

Document

Returns an immutable map, mapping only the specified key to the specified value.

Usage

From source file:ch.cyberduck.core.cryptomator.MoveWorkerTest.java

@Test
public void testMoveSameFolderCryptomator() throws Exception {
    final Host host = new Host(new SFTPProtocol(), "test.cyberduck.ch",
            new Credentials(System.getProperties().getProperty("sftp.user"),
                    System.getProperties().getProperty("sftp.password")));
    final SFTPSession session = new SFTPSession(host);
    session.open(new DisabledHostKeyCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final Path home = new SFTPHomeDirectoryService(session).find();
    final Path vault = new Path(home, UUID.randomUUID().toString(), EnumSet.of(Path.Type.directory));
    final Path source = new Path(vault, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final Path target = new Path(vault, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final CryptoVault cryptomator = new CryptoVault(vault, new DisabledPasswordStore());
    cryptomator.create(session, null, new VaultCredentials("test"));
    session.withRegistry(/*w w  w  .  ja  va2 s .  c o  m*/
            new DefaultVaultRegistry(new DisabledPasswordStore(), new DisabledPasswordCallback(), cryptomator));
    final byte[] content = RandomUtils.nextBytes(40500);
    final TransferStatus status = new TransferStatus();
    new CryptoBulkFeature<>(session, new DisabledBulkFeature(), new SFTPDeleteFeature(session), cryptomator)
            .pre(Transfer.Type.upload, Collections.singletonMap(source, status),
                    new DisabledConnectionCallback());
    new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content),
            new CryptoWriteFeature<>(session, new SFTPWriteFeature(session), cryptomator).write(source,
                    status.length(content.length), new DisabledConnectionCallback()));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    final MoveWorker worker = new MoveWorker(Collections.singletonMap(source, target),
            new DisabledProgressListener(), PathCache.empty(), new DisabledConnectionCallback());
    worker.run(session);
    assertFalse(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(source));
    assertTrue(new CryptoFindFeature(session, new DefaultFindFeature(session), cryptomator).find(target));
    final ByteArrayOutputStream out = new ByteArrayOutputStream(content.length);
    assertEquals(content.length,
            IOUtils.copy(
                    new CryptoReadFeature(session, new SFTPReadFeature(session), cryptomator).read(target,
                            new TransferStatus().length(content.length), new DisabledConnectionCallback()),
                    out));
    assertArrayEquals(content, out.toByteArray());
    new CryptoDeleteFeature(session, new SFTPDeleteFeature(session), cryptomator)
            .delete(Arrays.asList(target, vault), new DisabledLoginCallback(), new Delete.DisabledCallback());
    session.close();
}

From source file:fr.free.nrw.commons.Media.java

/**
 * Creating Media object from MWQueryPage.
 * Earlier only basic details were set for the media object but going forward,
 * a full media object(with categories, descriptions, coordinates etc) can be constructed using this method
 *
 * @param page response from the API//  w w w  .j  av a  2  s.  c om
 * @return Media object
 */
@Nullable
public static Media from(MwQueryPage page) {
    ImageInfo imageInfo = page.imageInfo();
    if (imageInfo == null) {
        return null;
    }
    ExtMetadata metadata = imageInfo.getMetadata();
    if (metadata == null) {
        Media media = new Media(null, imageInfo.getOriginalUrl(), page.title(), "", 0, null, null, null);
        if (!StringUtils.isBlank(imageInfo.getThumbUrl())) {
            media.setThumbUrl(imageInfo.getThumbUrl());
        }
        return media;
    }

    Media media = new Media(null, imageInfo.getOriginalUrl(), page.title(), "", 0,
            safeParseDate(metadata.dateTimeOriginal().value()), safeParseDate(metadata.dateTime().value()),
            StringUtil.fromHtml(metadata.artist().value()).toString());

    if (!StringUtils.isBlank(imageInfo.getThumbUrl())) {
        media.setThumbUrl(imageInfo.getThumbUrl());
    }

    String language = Locale.getDefault().getLanguage();
    if (StringUtils.isBlank(language)) {
        language = "default";
    }

    media.setDescriptions(Collections.singletonMap(language, metadata.imageDescription().value()));
    media.setCategories(MediaDataExtractorUtil.extractCategoriesFromList(metadata.categories().value()));
    String latitude = metadata.gpsLatitude().value();
    String longitude = metadata.gpsLongitude().value();

    if (!StringUtils.isBlank(latitude) && !StringUtils.isBlank(longitude)) {
        LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude), 0);
        media.setCoordinates(latLng);
    }

    media.setLicenseInformation(metadata.licenseShortName().value(), metadata.licenseUrl().value());
    return media;
}

From source file:com.haulmont.cuba.core.sys.serialization.KryoSerialization.java

protected Kryo newKryoInstance() {
    Kryo kryo = new Kryo();
    kryo.setInstantiatorStrategy(new CubaInstantiatorStrategy());
    if (onlySerializable) {
        kryo.setDefaultSerializer(CubaFieldSerializer.class);
    }/*from ww w. j a va  2 s.c  o  m*/

    //To work properly must itself be loaded by the application classloader (i.e. by classloader capable of loading
    //all the other application classes). For web application it means placing this class inside webapp folder.
    kryo.setClassLoader(KryoSerialization.class.getClassLoader());

    kryo.register(Arrays.asList("").getClass(), new ArraysAsListSerializer());
    kryo.register(Collections.EMPTY_LIST.getClass(), new CollectionsEmptyListSerializer());
    kryo.register(Collections.EMPTY_MAP.getClass(), new CollectionsEmptyMapSerializer());
    kryo.register(Collections.EMPTY_SET.getClass(), new CollectionsEmptySetSerializer());
    kryo.register(Collections.singletonList("").getClass(), new CollectionsSingletonListSerializer());
    kryo.register(Collections.singleton("").getClass(), new CollectionsSingletonSetSerializer());
    kryo.register(Collections.singletonMap("", "").getClass(), new CollectionsSingletonMapSerializer());
    kryo.register(BitSet.class, new BitSetSerializer());
    kryo.register(GregorianCalendar.class, new GregorianCalendarSerializer());
    kryo.register(InvocationHandler.class, new JdkProxySerializer());
    UnmodifiableCollectionsSerializer.registerSerializers(kryo);
    SynchronizedCollectionsSerializer.registerSerializers(kryo);

    kryo.register(CGLibProxySerializer.CGLibProxyMarker.class, new CGLibProxySerializer());
    ImmutableListSerializer.registerSerializers(kryo);
    ImmutableSetSerializer.registerSerializers(kryo);
    ImmutableMapSerializer.registerSerializers(kryo);
    ImmutableMultimapSerializer.registerSerializers(kryo);
    kryo.register(IndirectList.class, new IndirectContainerSerializer());
    kryo.register(IndirectMap.class, new IndirectContainerSerializer());
    kryo.register(IndirectSet.class, new IndirectContainerSerializer());

    kryo.register(org.eclipse.persistence.indirection.IndirectList.class, new IndirectContainerSerializer());
    kryo.register(org.eclipse.persistence.indirection.IndirectMap.class, new IndirectContainerSerializer());
    kryo.register(org.eclipse.persistence.indirection.IndirectSet.class, new IndirectContainerSerializer());

    //classes with custom serialization methods
    kryo.register(HashMultimap.class, new CubaJavaSerializer());
    kryo.register(ArrayListMultimap.class, new CubaJavaSerializer());
    kryo.register(MetaClassImpl.class, new CubaJavaSerializer());
    kryo.register(MetaPropertyImpl.class, new CubaJavaSerializer());
    kryo.register(UnitOfWorkQueryValueHolder.class, new UnitOfWorkQueryValueHolderSerializer(kryo));

    return kryo;
}

From source file:com.sinet.gage.provision.controller.DomainController.java

/**
 * Returns all state domains//w w  w  . j  av a2  s  .c om
 * 
 * @return
 */
@RequestMapping(value = "/list/state", method = RequestMethod.GET)
@ResponseBody
public Message getAllStates(@RequestHeader(value = "token", required = false) String token)
        throws InterruptedException {
    List<DomainResponse> listOfDomainResponse = domainService.findAllStateDomains(token, 0);
    if (!CollectionUtils.isEmpty(listOfDomainResponse)) {
        LOGGER.debug("Found " + listOfDomainResponse.size() + " state domains");
        return messageUtil.createMessageWithPayload(MessageConstants.DOMAINS_FOUND, listOfDomainResponse,
                Collections.singletonMap("dataModels", "domains"), DomainResponse.class);
    } else {
        LOGGER.debug("No state domains available");
        return messageUtil.createMessage(MessageConstants.DOMAINS_NOT_FOUND, Boolean.FALSE);
    }
}

From source file:org.zenoss.zep.dao.impl.EventArchiveDaoImpl.java

@Override
@TransactionalReadOnly/*from  ww  w.ja  v  a 2 s.  c  o  m*/
@Timed
public EventSummary findByUuid(String uuid) throws ZepException {
    final Map<String, Object> fields = Collections.singletonMap(COLUMN_UUID,
            uuidConverter.toDatabaseType(uuid));
    List<EventSummary> summaries = this.template.query("SELECT * FROM event_archive WHERE uuid=:uuid",
            new EventArchiveRowMapper(this.eventDaoHelper, databaseCompatibility), fields);
    return (summaries.size() > 0) ? summaries.get(0) : null;
}

From source file:marshalsec.SnakeYAML.java

/**
 * {@inheritDoc}/*  w  w  w .j  av a2s.c  o m*/
 *
 * @see marshalsec.gadgets.SpringPropertyPathFactory#makePropertyPathFactory(marshalsec.UtilFactory,
 *      java.lang.String[])
 */
@Override
@Args(minArgs = 1, args = { "jndiUrl" }, defaultArgs = { MarshallerBase.defaultJNDIUrl })
public Object makePropertyPathFactory(UtilFactory uf, String[] args) throws Exception {
    Map<String, String> properties = new LinkedHashMap<>();
    String jndiUrl = args[0];
    properties.put("targetBeanName", writeString(jndiUrl));
    properties.put("propertyPath", "foo");
    properties.put("beanFactory", writeObject(SimpleJndiBeanFactory.class,
            Collections.singletonMap("shareableResources", writeArray(writeString(jndiUrl))), 1));
    return writeObject(PropertyPathFactoryBean.class, properties);
}

From source file:ru.mystamps.web.dao.impl.JdbcCategoryDao.java

@Override
public long countAddedSince(Date date) {
    return jdbcTemplate.queryForObject(countCategoriesAddedSinceSql, Collections.singletonMap("date", date),
            Long.class);
}

From source file:info.bluefoot.winter.controller.PlaylistController.java

@RequestMapping(value = { "/playlist/delete" }, method = RequestMethod.POST, produces = "application/json")
public @ResponseBody ResponseEntity<Map<String, String>> removePlaylist(Integer playlistId,
        HttpServletResponse response) {//  w  w w.j a  v a 2 s.  co m
    try {
        playlistService.removePlaylistAndVideos(playlistId);
    } catch (Exception e) {
        String errorId = RandomStringUtils.randomAlphanumeric(6).toUpperCase();
        logger.error("[" + errorId + "] Can't delete playlist", e);
        return new ResponseEntity<Map<String, String>>(
                Collections.singletonMap("error",
                        "Can't delete playlist. Try again later. Error id: " + errorId + "."),
                HttpStatus.INTERNAL_SERVER_ERROR);
    }
    return new ResponseEntity<Map<String, String>>(Collections.singletonMap("sucess", "true"), HttpStatus.OK);
}

From source file:com.netflix.genie.web.configs.MvcConfig.java

/**
 * Get RetryTemplate.//from w  ww . j  a  va2 s  . co m
 *
 * @param noOfRetries     number of retries
 * @param initialInterval initial interval for the back-off policy
 * @param maxInterval     maximum interval for the back-off policy
 * @return The retry template to use
 */
@Bean(name = "genieRetryTemplate")
public RetryTemplate retryTemplate(@Value("${genie.retry.noOfRetries:5}") final int noOfRetries,
        @Value("${genie.retry.initialInterval:10000}") final int initialInterval,
        @Value("${genie.retry.maxInterval:60000}") final int maxInterval) {
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(
            new SimpleRetryPolicy(noOfRetries, Collections.singletonMap(Exception.class, true)));
    final ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(initialInterval);
    backOffPolicy.setMaxInterval(maxInterval);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    return retryTemplate;
}