List of usage examples for com.google.common.collect Iterables getFirst
@Nullable public static <T> T getFirst(Iterable<? extends T> iterable, @Nullable T defaultValue)
From source file:br.com.tecsinapse.exporter.importer.parser.FixedLengthFileParser.java
public List<T> parse(InputStream inputStream) throws IOException, ReflectiveOperationException { final List<T> list = new ArrayList<>(); final List<String> lines = FixedLengthFileUtil.getLines(inputStream, ignoreFirstLine, afterLine, ignoreLastLines, eof, charset); @SuppressWarnings("unchecked") final Set<Method> methods = ReflectionUtils.getAllMethods(clazz, ReflectionUtils.<Method>withAnnotation(FixedLengthColumn.class)); @SuppressWarnings("unchecked") Method lineMethod = Iterables.getFirst(ReflectionUtils.getMethods(clazz, ReflectionUtils.<Method>withAnnotation(LineFixedLengthFile.class)), null); final List<AnnotationMethod> methodsAndAnnotations = orderedAnnotationsAndMethods(methods); final Constructor<T> constructor = clazz.getDeclaredConstructor(); constructor.setAccessible(true);/*from w w w . j av a 2 s .co m*/ for (int i = 0; i < lines.size(); i++) { T instance = constructor.newInstance(); String workingLine = lines.get(i); boolean ignoreLine = false; for (AnnotationMethod annotationMethod : methodsAndAnnotations) { if (workingLine.length() == 0) { break; } Method method = annotationMethod.getMethod(); FixedLengthColumn flc = annotationMethod.getFlc(); final boolean naoValidouTamanhoDaLinha = !flc.useLineLength() && workingLine.length() < flc.columnSize() && !ignoreColumnLengthError; if (naoValidouTamanhoDaLinha) { if (ignoreLineWhenError) { ignoreLine = true; break; } else { int line = ignoreFirstLine ? i + 1 : i; throw new IllegalStateException(String.format( "Malformed file or wrong configuration. Line %s size doesn't match the configuration.", line)); } } int length = flc.useLineLength() || workingLine.length() < flc.columnSize() ? workingLine.length() : flc.columnSize(); String value = workingLine.substring(0, length).trim(); if (removeDuplicatedSpaces) { value = value.replaceAll("\\s+", " "); } Converter<?, ?> converter = flc.converter().newInstance(); Object obj; try { obj = converter.apply(value); } catch (Exception e) { if (ignoreLineWhenError) { ignoreLine = true; break; } else { throw e; } } method.invoke(instance, obj); workingLine = workingLine.substring(length, workingLine.length()); } if (lineMethod != null) { lineMethod.invoke(instance, lines.get(i)); } if (!ignoreLine) { list.add(instance); } } return list; }
From source file:com.google.devtools.build.lib.repository.ExternalPackageUtil.java
/** Uses a rule name to fetch the corresponding Rule from the external package. */ @Nullable//ww w . j a v a 2 s .c o m public static Rule getRuleByName(final String ruleName, Environment env) throws ExternalPackageException, InterruptedException { List<Rule> rules = getRules(env, true, new Function<Package, Iterable<Rule>>() { @Nullable @Override public Iterable<Rule> apply(Package externalPackage) { Rule rule = externalPackage.getRule(ruleName); if (rule == null) { return null; } return ImmutableList.of(rule); } }); if (env.valuesMissing()) { return null; } if (rules == null || rules.isEmpty()) { throw new ExternalRuleNotFoundException(ruleName); } return Iterables.getFirst(rules, null); }
From source file:org.vclipse.constraint.scoping.ConstraintScopeProvider.java
private IScope createCsticScope(Iterable<Class> classes) { Class cls = Iterables.getFirst(classes, null); Iterable<Class> restClasses = Iterables.skip(classes, 1); if (cls.getSuperClasses().isEmpty() && Iterables.isEmpty(restClasses)) { return Scopes.scopeFor(cls.getCharacteristics()); } else {//from www .j a v a2 s .c o m return Scopes.scopeFor(cls.getCharacteristics(), createCsticScope(Iterables.concat(cls.getSuperClasses(), restClasses))); } }
From source file:org.sonar.java.checks.CollectionInappropriateCallsCheck.java
@Nullable private static Type getTypeParameter(Type collectionType) { if (collectionType instanceof ParametrizedTypeJavaType) { ParametrizedTypeJavaType parametrizedType = (ParametrizedTypeJavaType) collectionType; TypeVariableJavaType first = Iterables.getFirst(parametrizedType.typeParameters(), null); if (first != null) { return parametrizedType.substitution(first); }//from w w w. ja v a 2s . c o m } return null; }
From source file:org.obm.provisioning.utils.SerializationUtils.java
@VisibleForTesting static ObmHost findMailHostForUser(String hostName, Collection<ObmHost> domainHosts) { for (ObmHost host : domainHosts) { if (host.getName().equals(hostName)) { return host; }//from www . j av a 2s .co m } return Iterables.getFirst(domainHosts, null); }
From source file:org.alloy.metal.xml.merge.MergeXmlConfigResource.java
protected ResourceInputStream merge(List<ResourceInputStream> sources) throws MergeException, MergeManagerSetupException { if (sources.size() <= 1) { return Iterables.getFirst(sources, null); }/*from w w w.j a v a 2s . c o m*/ ResourceInputStream response = null; ResourceInputStream[] pair = new ResourceInputStream[2]; pair[0] = sources.get(0); for (int j = 1; j < sources.size(); j++) { pair[1] = sources.get(j); response = mergeItems(pair[0], pair[1]); try { pair[0].close(); } catch (Throwable e) { LOG.error("Unable to merge source and patch locations", e); } try { pair[1].close(); } catch (Throwable e) { LOG.error("Unable to merge source and patch locations", e); } pair[0] = response; } return response; }
From source file:com.google.gerrit.httpd.rpc.project.ProjectDetailFactory.java
@Override public ProjectDetail call() throws NoSuchProjectException, IOException { final ProjectControl pc = projectControlFactory.validateFor(projectName, ProjectControl.OWNER | ProjectControl.VISIBLE); final ProjectState projectState = pc.getProjectState(); final ProjectDetail detail = new ProjectDetail(); detail.setProject(projectState.getProject()); final boolean userIsOwner = pc.isOwner(); final boolean userIsOwnerAnyRef = pc.isOwnerAnyRef(); detail.setCanModifyAccess(userIsOwnerAnyRef); detail.setCanModifyAgreements(userIsOwner); detail.setCanModifyDescription(userIsOwner); detail.setCanModifyMergeType(userIsOwner); detail.setCanModifyState(userIsOwner); final InheritedBoolean useContributorAgreements = new InheritedBoolean(); final InheritedBoolean useSignedOffBy = new InheritedBoolean(); final InheritedBoolean useContentMerge = new InheritedBoolean(); final InheritedBoolean requireChangeID = new InheritedBoolean(); useContributorAgreements.setValue(projectState.getProject().getUseContributorAgreements()); useSignedOffBy.setValue(projectState.getProject().getUseSignedOffBy()); useContentMerge.setValue(projectState.getProject().getUseContentMerge()); requireChangeID.setValue(projectState.getProject().getRequireChangeID()); ProjectState parentState = Iterables.getFirst(projectState.parents(), null); if (parentState != null) { useContributorAgreements.setInheritedValue(parentState.isUseContributorAgreements()); useSignedOffBy.setInheritedValue(parentState.isUseSignedOffBy()); useContentMerge.setInheritedValue(parentState.isUseContentMerge()); requireChangeID.setInheritedValue(parentState.isRequireChangeID()); }// ww w. j ava2s. c om detail.setUseContributorAgreements(useContributorAgreements); detail.setUseSignedOffBy(useSignedOffBy); detail.setUseContentMerge(useContentMerge); detail.setRequireChangeID(requireChangeID); final Project.NameKey projectName = projectState.getProject().getNameKey(); Repository git; try { git = gitRepositoryManager.openRepository(projectName); } catch (RepositoryNotFoundException err) { throw new NoSuchProjectException(projectName); } try { Ref head = git.getRef(Constants.HEAD); if (head != null && head.isSymbolic() && GitRepositoryManager.REF_CONFIG.equals(head.getLeaf().getName())) { detail.setPermissionOnly(true); } } catch (IOException err) { throw new NoSuchProjectException(projectName); } finally { git.close(); } return detail; }
From source file:com.google.errorprone.RefactoringCollection.java
private static Path buildRootPath() { Path root = Iterables.getFirst(FileSystems.getDefault().getRootDirectories(), null); if (root == null) { throw new RuntimeException("Can't find a root filesystem!"); }//from w ww .j a va 2 s. c om return root; }
From source file:ratpack.server.internal.InferringPublicAddress.java
private HostAndPort getForwardedHostData(Request request) { Headers headers = request.getHeaders(); String forwardedHostHeader = Strings.emptyToNull(headers.get(X_FORWARDED_HOST.toString())); String hostPortString = forwardedHostHeader != null ? Iterables.getFirst(FORWARDED_HOST_SPLITTER.split(forwardedHostHeader), null) : null;/*from www .j a v a 2 s . c o m*/ return hostPortString != null ? HostAndPort.fromString(hostPortString) : null; }
From source file:controllers.modules.CorpusModule.java
public static Result update(UUID corpus) { OpinionCorpus corpusObj = null;// w w w .j ava2s. c om if (corpus != null) { corpusObj = fetchResource(corpus, OpinionCorpus.class); } OpinionCorpusFactory corpusFactory = null; MultipartFormData formData = request().body().asMultipartFormData(); if (formData != null) { // if we have a multi-part form with a file. if (formData.getFiles() != null) { // get either the file named "file" or the first one. FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"), Iterables.getFirst(formData.getFiles(), null)); if (filePart != null) { corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile()) .setFormat(FilenameUtils.getExtension(filePart.getFilename())); } } } else { // otherwise try as a json body. JsonNode json = request().body().asJson(); if (json != null) { OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class); if (optionsVM != null) { corpusFactory = optionsVM.toFactory(); } else { throw new IllegalArgumentException(); } if (optionsVM.grabbers != null) { if (optionsVM.grabbers.twitter != null) { if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) { TwitterFactory tFactory = new TwitterFactory(); Twitter twitter = tFactory.getInstance(); twitter.setOAuthConsumer( Play.application().configuration().getString("twitter4j.oauth.consumerKey"), Play.application().configuration().getString("twitter4j.oauth.consumerSecret")); twitter.setOAuthAccessToken(new AccessToken( Play.application().configuration().getString("twitter4j.oauth.accessToken"), Play.application().configuration() .getString("twitter4j.oauth.accessTokenSecret"))); Query query = new Query(optionsVM.grabbers.twitter.query); query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10)); query.resultType(Query.RECENT); if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) { query.lang(corpusFactory.getLanguage()); } else if (corpusObj != null) { query.lang(corpusObj.getLanguage()); } QueryResult qr; try { qr = twitter.search(query); } catch (TwitterException e) { throw new IllegalArgumentException(); } StringBuilder tweets = new StringBuilder(); for (twitter4j.Status status : qr.getTweets()) { // quote for csv, normalize space, and remove higher unicode characters. String text = StringEscapeUtils.escapeCsv(StringUtils .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", ""))); tweets.append(text + System.lineSeparator()); } corpusFactory.setContent(tweets.toString()); corpusFactory.setFormat("txt"); } } } } else { // if not json, then just create empty. corpusFactory = new OpinionCorpusFactory(); } } if (corpusFactory == null) { throw new IllegalArgumentException(); } if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) { corpusFactory.setTitle("Untitled corpus"); } corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em()); DocumentCorpusModel corpusVM = null; corpusObj = corpusFactory.create(); if (!em().contains(corpusObj)) { em().persist(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return created(corpusVM.asJson()); } for (PersistentObject obj : corpusObj.getDocuments()) { if (em().contains(obj)) { em().merge(obj); } else { em().persist(obj); } } em().merge(corpusObj); corpusVM = (DocumentCorpusModel) createViewModel(corpusObj); corpusVM.populateSize(em(), corpusObj); return ok(corpusVM.asJson()); }