List of usage examples for com.google.common.base Optional toString
@Override public abstract String toString();
From source file:extrabiomes.handlers.BiomeHandler.java
public static void enableBiomes() { final Set<WorldType> worldTypes = BiomeHelper.discoverWorldTypes(); for (final BiomeSettings setting : BiomeSettings.values()) { final Optional<? extends BiomeGenBase> biome = setting.getBiome(); if (!setting.isVanilla()) { if (setting.isEnabled() && biome.isPresent()) { BiomeHelper.enableBiome(worldTypes, biome.get()); } else { LogHelper.fine("Custom biome %s disabled.", setting.toString()); }/*from w w w . j a va 2s . c o m*/ } else if (!setting.isEnabled()) { Extrabiomes.proxy.removeBiome(BiomeHelper.settingToBiomeGenBase(setting)); LogHelper.fine("Vanilla biome %s disabled.", biome.toString()); } if (setting.allowVillages() && biome.isPresent()) { BiomeManager.addVillageBiome(biome.get(), true); LogHelper.fine("Village spawning enabled for custom biome %s.", setting.toString()); } } }
From source file:org.knight.examples.guava.basic.UsingAvoidingNullExamples.java
public void run() { Optional<String> o1 = Optional.of("Guava-library"); if (o1.isPresent()) { log("o1: " + o1.get()); } else {/*from ww w . j a v a2s . c o m*/ log("o1: " + o1.toString()); } Optional<String> o2 = Optional.absent(); try { //will cause a IllegalStateException log("o2: " + o2.get()); } catch (IllegalStateException e) { log("o2 is absent, use get() will cause a IllegalStateException."); } Optional<String> o3 = Optional.fromNullable(null); log("o3 present = " + o3.isPresent()); try { //will cause a IllegalStateException log("o3: " + o3.get()); } catch (IllegalStateException e) { log("o3 is absent, use get() will cause a IllegalStateException."); } if (o3.orNull() == null) { log("o3 is absent, so orNull() returns null."); } Optional<String> o4 = Optional.fromNullable("Hello World"); log("o4: " + o4.or("o4 is present, so this default value will not be printed.")); Optional<Book> o5 = Optional.of(Book.generateBook()); log("o5: " + o5.get().toString()); }
From source file:org.mayocat.theme.internal.DefaultThemeFileResolver.java
private String generateTemplateId(String layoutName, Optional<Breakpoint> breakpoint) { String themeName = context.getTheme().getDefinition().getName(); String templateId = themeName.length() + themeName + "_" + breakpoint.toString().length() + breakpoint.toString() + "_" + layoutName.length() + layoutName; return "" + templateId.hashCode(); }
From source file:net.caseif.flint.common.metadata.persist.CommonPersistentMetadata.java
@Override @SuppressWarnings("unchecked") public <T> Optional<T> get(String key) throws ClassCastException { Optional<Object> value = super.get(key); if (value.isPresent() && value.get() instanceof String) { return Optional.of(new SimpleMetadataSerializer<T>().deserialize(value.toString())); }//from ww w . j a v a2 s.com return (Optional<T>) value; }
From source file:com.cybozu.labs.langdetect.CommandLineInterface.java
/** * Batch Test of Language Detection (--batchtest option) * /*from w ww. j a va 2 s . c o m*/ * <pre> * usage: --batchtest -d [profile directory] -a [alpha] -s [seed] [test data(s)] * </pre> * * The format of test data(s): * <pre> * [correct language name]\t[text body for test]\n * </pre> * */ public void batchTest() throws IOException { LanguageDetector languageDetector = makeDetector(); TextObjectFactory textObjectFactory = CommonTextObjectFactories.forDetectingOnLargeText(); Map<String, List<String>> result = new HashMap<>(); for (String filename : arglist) { try (BufferedReader is = new BufferedReader( new InputStreamReader(new FileInputStream(filename), "utf-8"))) { while (is.ready()) { String line = is.readLine(); int idx = line.indexOf('\t'); if (idx <= 0) continue; String correctLang = line.substring(0, idx); String text = line.substring(idx + 1); TextObject textObject = textObjectFactory.forText(text); Optional<LdLocale> lang = languageDetector.detect(textObject); if (!result.containsKey(correctLang)) result.put(correctLang, new ArrayList<String>()); if (lang.isPresent()) { result.get(correctLang).add(lang.toString()); } else { result.get(correctLang).add("unknown"); } if (hasParam("--debug")) System.out.println(correctLang + "," + lang + "," + (text.length() > 100 ? text.substring(0, 100) : text)); } } List<String> langList = new ArrayList<>(result.keySet()); Collections.sort(langList); int totalCount = 0, totalCorrect = 0; for (String lang : langList) { Map<String, Integer> resultCount = new HashMap<>(); int count = 0; List<String> list = result.get(lang); for (String detectedLang : list) { ++count; if (resultCount.containsKey(detectedLang)) { resultCount.put(detectedLang, resultCount.get(detectedLang) + 1); } else { resultCount.put(detectedLang, 1); } } int correct = resultCount.containsKey(lang) ? resultCount.get(lang) : 0; double rate = correct / (double) count; System.out.println(String.format("%s (%d/%d=%.2f): %s", lang, correct, count, rate, resultCount)); totalCorrect += correct; totalCount += count; } System.out.println(String.format("total: %d/%d = %.3f", totalCorrect, totalCount, totalCorrect / (double) totalCount)); } }
From source file:cz.cuni.mff.ms.brodecva.botnicek.ide.utils.swing.components.hinters.HintingDocument.java
@Override public void remove(final int offset, final int length) throws BadLocationException { Preconditions.checkArgument(offset >= 0); Preconditions.checkArgument(length >= 0); final int selectionStart = this.selectionBoundsProvider.getStart(); final int ultimateSelectionStart; if (selectionStart > 0) { ultimateSelectionStart = selectionStart - 1; } else {/*from w ww. j av a 2 s. com*/ ultimateSelectionStart = selectionStart; } final Optional<E> matched = match(getText(0, ultimateSelectionStart)); if (!matched.isPresent()) { if (this.strict) { super.remove(0, getLength()); } else { super.remove(offset, length); } } else { super.remove(0, getLength()); super.insertString(0, matched.toString(), Intended.<AttributeSet>nullReference()); fireHintEvent(matched.get()); } fireSelectionChangedEvent(ultimateSelectionStart, getLength()); }
From source file:com.vmware.photon.controller.apife.backends.NetworkXenonBackend.java
@Override public NetworkService.State filterNetworkByPortGroup(Optional<String> portGroup) throws PortGroupRepeatedInMultipleNetworksException { ServiceDocumentQueryResult queryResult = filterServiceDocuments(Optional.absent(), portGroup, Optional.absent());//from ww w . j a v a2 s.c om ResourceList<NetworkService.State> networksList = PaginationUtils .xenonQueryResultToResourceList(NetworkService.State.class, queryResult); if (networksList == null || networksList.getItems() == null || networksList.getItems().size() == 0) { return null; } else if (networksList.getItems().size() > 1) { Map<String, List<NetworkService.State>> violations = new HashMap<>(); violations.put(portGroup.toString(), networksList.getItems()); throw new PortGroupRepeatedInMultipleNetworksException(violations); } else { return networksList.getItems().get(0); } }
From source file:org.dswarm.graph.Neo4jProcessor.java
public String generateStatementHash(final String predicateName, final Optional<NodeType> optionalSubjectNodeType, final Optional<NodeType> optionalObjectNodeType, final Optional<String> optionalSubjectIdentifier, final Optional<String> optionalObjectIdentifier) throws DMPGraphException { if (!optionalSubjectNodeType.isPresent() || !optionalObjectNodeType.isPresent() || !optionalSubjectIdentifier.isPresent() || !optionalObjectIdentifier.isPresent()) { final String message = "cannot generate statement hash, because the subject node type or object node type or subject identifier or object identifier is not present"; Neo4jProcessor.LOG.error(message); throw new DMPGraphException(message); }// ww w . j a v a 2 s. co m final StringBuilder sb = new StringBuilder(); sb.append(optionalSubjectNodeType.toString()).append(":").append(optionalSubjectIdentifier.get()) .append(" ").append(predicateName).append(" ").append(optionalObjectNodeType.toString()).append(":") .append(optionalObjectIdentifier.get()).append(" "); MessageDigest messageDigest = null; try { messageDigest = MessageDigest.getInstance("SHA-256"); } catch (final NoSuchAlgorithmException e) { throw new DMPGraphException("couldn't instantiate hash algo"); } messageDigest.update(sb.toString().getBytes()); return new String(messageDigest.digest()); }
From source file:org.dswarm.graph.batch.Neo4jProcessor.java
public long generateStatementHash(final String predicateName, final Optional<NodeType> optionalSubjectNodeType, final Optional<NodeType> optionalObjectNodeType, final Optional<String> optionalSubjectIdentifier, final Optional<String> optionalObjectIdentifier) throws DMPGraphException { if (!optionalSubjectNodeType.isPresent() || !optionalObjectNodeType.isPresent() || !optionalSubjectIdentifier.isPresent() || !optionalObjectIdentifier.isPresent()) { final String message = "cannot generate statement hash, because the subject node type or object node type or subject identifier or object identifier is not present"; Neo4jProcessor.LOG.error(message); throw new DMPGraphException(message); }//from www .java 2 s.com final String hashString = optionalSubjectNodeType.toString() + ":" + optionalSubjectIdentifier.get() + " " + predicateName + " " + optionalObjectNodeType.toString() + ":" + optionalObjectIdentifier.get() + " "; return SipHash.digest(Neo4jProcessor.SPEC_KEY, hashString.getBytes(Charsets.UTF_8)); }
From source file:com.dowdandassociates.gentoo.bootstrap.DefaultBootstrapCommandInformationProvider.java
public BootstrapCommandInformation get() { if (!sessionInfo.getSession().isPresent() || !processedTemplate.getPath().isPresent()) { processedTemplate.cleanup();//from w ww.ja v a 2 s . com Optional<String> command = Optional.absent(); return new BootstrapCommandInformation().withSessionInfo(sessionInfo).withCommand(command); } try { Session session = sessionInfo.getSession().get(); Path path = processedTemplate.getPath().get(); String filename = directory.get() + "/" + scriptName.get(); log.info("Openning channel"); ChannelExec channel = (ChannelExec) session.openChannel("exec"); log.info("Setting command"); channel.setCommand("scp -t " + filename); log.info("Getting input and output streams"); OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); log.info("Connecting channel"); channel.connect(); log.info("Check ack after connect"); if (checkAck(in) != 0) { throw new IOException("checkAck failed after connect"); } StringBuilder command = new StringBuilder(); command.append("C0755 "); command.append((Long) Files.getAttribute(path, "basic:size")); command.append(' '); if (filename.lastIndexOf('/') > 0) { command.append(filename.substring(filename.lastIndexOf('/') + 1)); } else { command.append(filename); } command.append('\n'); log.info("scp command: " + command.toString()); log.info("writing scp command"); out.write(command.toString().getBytes()); out.flush(); log.info("check ack after scp command"); if (checkAck(in) != 0) { throw new IOException("checkAck failed after scp command"); } log.info("writing content"); InputStream is = Files.newInputStream(path); byte[] buf = new byte[1024]; while (true) { int len = is.read(buf, 0, buf.length); if (len <= 0) { break; } out.write(buf, 0, len); } is.close(); buf[0] = 0; out.write(buf, 0, 1); out.flush(); log.info("check after writing content"); if (checkAck(in) != 0) { throw new IOException("checkAck failed after file write"); } log.info("closing scp connection"); in.close(); out.close(); channel.disconnect(); return new BootstrapCommandInformation().withSessionInfo(sessionInfo).withCommand(filename); } catch (IllegalArgumentException | IOException | JSchException | SecurityException | UnsupportedOperationException e) { log.error(e.getMessage(), e); Optional<String> command = Optional.absent(); return new BootstrapCommandInformation().withSessionInfo(sessionInfo).withCommand(command); } finally { processedTemplate.cleanup(); } }