List of usage examples for com.google.common.collect ImmutableList isEmpty
boolean isEmpty();
From source file:com.google.devtools.build.lib.rules.proto.BazelProtoLibrary.java
@Override public ConfiguredTarget create(RuleContext ruleContext) throws InterruptedException, RuleErrorException { ImmutableList<Artifact> protoSources = ruleContext.getPrerequisiteArtifacts("srcs", TARGET).list(); NestedSet<Artifact> checkDepsProtoSources = ProtoCommon.getCheckDepsProtoSources(ruleContext, protoSources); ProtoCommon.checkSourceFilesAreInSamePackage(ruleContext); NestedSet<Artifact> transitiveImports = ProtoCommon.collectTransitiveImports(ruleContext, protoSources); NestedSet<Artifact> protosInDirectDeps = areDepsStrict(ruleContext) ? ProtoCommon.computeProtosInDirectDeps(ruleContext) : null;// w w w. jav a 2s . c o m final SupportData supportData = SupportData.create( Predicates.<TransitiveInfoCollection>alwaysTrue() /* nonWeakDepsPredicate */, protoSources, protosInDirectDeps, transitiveImports, !protoSources.isEmpty()); Runfiles.Builder dataRunfiles = ProtoCommon.createDataRunfilesProvider(transitiveImports, ruleContext); RuleConfiguredTargetBuilder result = new RuleConfiguredTargetBuilder(ruleContext); Artifact descriptorSetOutput = null; if (checkDepsProtoSources.isEmpty() || !outputDescriptorSetFlagEnabled(ruleContext)) { result.setFilesToBuild(NestedSetBuilder.<Artifact>create(STABLE_ORDER)); } else { descriptorSetOutput = ruleContext .getGenfilesArtifact(ruleContext.getLabel().getName() + "-descriptor-set.proto.bin"); ProtoCompileActionBuilder.writeDescriptorSet(ruleContext, descriptorSetOutput.getExecPathString(), checkDepsProtoSources, transitiveImports, protosInDirectDeps, ImmutableList.of(descriptorSetOutput), true /* allowServices */); dataRunfiles.addArtifact(descriptorSetOutput); result.setFilesToBuild(NestedSetBuilder.create(STABLE_ORDER, descriptorSetOutput)); } // TODO(bazel-team): this second constructor argument is superfluous and should be removed. ProtoSourcesProvider sourcesProvider = ProtoSourcesProvider.create(transitiveImports, transitiveImports, protoSources, checkDepsProtoSources, descriptorSetOutput); return result.addProvider(RunfilesProvider.withData(Runfiles.EMPTY, dataRunfiles.build())) .addProvider(ProtoSourcesProvider.class, sourcesProvider) .addProvider(ProtoSupportDataProvider.class, new ProtoSupportDataProvider(supportData)) .addSkylarkTransitiveInfo(ProtoSourcesProvider.SKYLARK_NAME, sourcesProvider).build(); }
From source file:org.apache.calcite.sql.SqlOperator.java
protected List<String> constructArgNameList(SqlCall call) { // If any arguments are named, construct a map. final ImmutableList.Builder<String> nameBuilder = ImmutableList.builder(); for (SqlNode operand : call.getOperandList()) { if (operand.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) { final List<SqlNode> operandList = ((SqlCall) operand).getOperandList(); nameBuilder.add(((SqlIdentifier) operandList.get(1)).getSimple()); }//w w w. ja v a2 s . c o m } ImmutableList<String> argNames = nameBuilder.build(); if (argNames.isEmpty()) { return null; } else { return argNames; } }
From source file:com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodecProcessor.java
private ExecutableElement selectInstantiator(TypeElement encodedType) { List<ExecutableElement> constructors = ElementFilter.constructorsIn(encodedType.getEnclosedElements()); Stream<ExecutableElement> factoryMethods = ElementFilter.methodsIn(encodedType.getEnclosedElements()) .stream().filter(AutoCodecProcessor::hasInstantiatorAnnotation) .peek(m -> verifyFactoryMethod(encodedType, m)); ImmutableList<ExecutableElement> markedInstantiators = Stream .concat(constructors.stream().filter(AutoCodecProcessor::hasInstantiatorAnnotation), factoryMethods) .collect(toImmutableList()); if (markedInstantiators.isEmpty()) { // If nothing is marked, see if there is a unique constructor. if (constructors.size() > 1) { throw new IllegalArgumentException(encodedType.getQualifiedName() + " has multiple constructors but no Instantiator annotation."); }//from w w w . j a va 2 s . co m // In Java, every class has at least one constructor, so this never fails. return constructors.get(0); } if (markedInstantiators.size() == 1) { return markedInstantiators.get(0); } throw new IllegalArgumentException( encodedType.getQualifiedName() + " has multiple Instantiator annotations."); }
From source file:dagger.internal.codegen.FactoryGenerator.java
@Override Optional<TypeSpec.Builder> write(ClassName generatedTypeName, ProvisionBinding binding) { // We don't want to write out resolved bindings -- we want to write out the generic version. checkArgument(!binding.unresolved().isPresent()); checkArgument(binding.bindingElement().isPresent()); if (binding.bindingKind().equals(INJECTION) && !injectValidator.isValidType(binding.contributedType())) { return Optional.empty(); }// w w w. j a v a2s . c om TypeName providedTypeName = TypeName.get(binding.contributedType()); ParameterizedTypeName factoryTypeName = factoryOf(providedTypeName); ImmutableList<TypeVariableName> typeParameters = bindingTypeElementTypeVariableNames(binding); TypeSpec.Builder factoryBuilder = classBuilder(generatedTypeName).addModifiers(FINAL); // Use type parameters from the injected type or the module instance *only* if we require it. boolean factoryHasTypeParameters = (binding.bindingKind().equals(INJECTION) || binding.requiresModuleInstance()) && !typeParameters.isEmpty(); if (factoryHasTypeParameters) { factoryBuilder.addTypeVariables(typeParameters); } Optional<MethodSpec.Builder> constructorBuilder = Optional.empty(); UniqueNameSet uniqueFieldNames = new UniqueNameSet(); ImmutableMap.Builder<BindingKey, FieldSpec> fieldsBuilder = ImmutableMap.builder(); switch (binding.factoryCreationStrategy()) { case SINGLETON_INSTANCE: FieldSpec.Builder instanceFieldBuilder = FieldSpec .builder(generatedTypeName, "INSTANCE", PRIVATE, STATIC, FINAL) .initializer("new $T()", generatedTypeName); // if the factory has type parameters, we're ignoring them in the initializer if (factoryHasTypeParameters) { instanceFieldBuilder.addAnnotation(suppressWarnings(RAWTYPES)); } factoryBuilder.addField(instanceFieldBuilder.build()); break; case CLASS_CONSTRUCTOR: constructorBuilder = Optional.of(constructorBuilder().addModifiers(PUBLIC)); if (Util.bindingSupportsTestDelegate(binding)) { addConstructorParameterAndTypeField(getDelegateTypeName(binding.key()), getDelegateFieldName(binding.key()), factoryBuilder, constructorBuilder.get(), false); } if (binding.requiresModuleInstance()) { addConstructorParameterAndTypeField(TypeName.get(binding.bindingTypeElement().get().asType()), "module", factoryBuilder, constructorBuilder.get(), true); } for (Map.Entry<BindingKey, FrameworkField> entry : generateBindingFieldsForDependencies(binding) .entrySet()) { BindingKey bindingKey = entry.getKey(); FrameworkField bindingField = entry.getValue(); FieldSpec field = addConstructorParameterAndTypeField(bindingField.type(), uniqueFieldNames.getUniqueName(bindingField.name()), factoryBuilder, constructorBuilder.get(), true); fieldsBuilder.put(bindingKey, field); } break; case DELEGATE: return Optional.empty(); default: throw new AssertionError(); } ImmutableMap<BindingKey, FieldSpec> fields = fieldsBuilder.build(); factoryBuilder.addModifiers(PUBLIC).addSuperinterface(factoryTypeName); // If constructing a factory for @Inject or @Provides bindings, we use a static create method // so that generated components can avoid having to refer to the generic types // of the factory. (Otherwise they may have visibility problems referring to the types.) Optional<MethodSpec> createMethod; switch (binding.bindingKind()) { case INJECTION: case PROVISION: // The return type is usually the same as the implementing type, except in the case // of enums with type variables (where we cast). MethodSpec.Builder createMethodBuilder = methodBuilder("create").addModifiers(PUBLIC, STATIC) .returns(factoryTypeName); if (factoryHasTypeParameters) { createMethodBuilder.addTypeVariables(typeParameters); } List<ParameterSpec> params = constructorBuilder.isPresent() ? constructorBuilder.get().build().parameters : ImmutableList.of(); createMethodBuilder.addParameters(params); switch (binding.factoryCreationStrategy()) { case SINGLETON_INSTANCE: if (factoryHasTypeParameters) { // We use an unsafe cast here because the types are different. // It's safe because the type is never referenced anywhere. createMethodBuilder.addStatement("return ($T) INSTANCE", TypeNames.FACTORY); createMethodBuilder.addAnnotation(suppressWarnings(RAWTYPES, UNCHECKED)); } else { createMethodBuilder.addStatement("return INSTANCE"); } break; case CLASS_CONSTRUCTOR: createMethodBuilder.addStatement("return new $T($L)", parameterizedGeneratedTypeNameForBinding(binding), makeParametersCodeBlock(Lists.transform(params, input -> CodeBlock.of("$N", input)))); break; default: throw new AssertionError(); } createMethod = Optional.of(createMethodBuilder.build()); break; default: createMethod = Optional.empty(); } if (constructorBuilder.isPresent()) { factoryBuilder.addMethod(constructorBuilder.get().build()); } List<CodeBlock> parameters = Lists.newArrayList(); for (DependencyRequest dependency : binding.explicitDependencies()) { parameters.add(frameworkTypeUsageStatement(CodeBlock.of("$N", fields.get(dependency.bindingKey())), dependency.kind())); } CodeBlock parametersCodeBlock = makeParametersCodeBlock(parameters); MethodSpec.Builder getMethodBuilder = methodBuilder("get").returns(providedTypeName) .addAnnotation(Override.class).addModifiers(PUBLIC); final CodeBlock codeBlock = CodeBlock.of(getDelegateFieldName(binding.key())); if (binding.bindingKind().equals(PROVISION)) { if (Util.bindingSupportsTestDelegate(binding)) { final String delegateFieldName = Util.getDelegateFieldName(binding.key()); getMethodBuilder.beginControlFlow("if ($L != null)", CodeBlock.of(delegateFieldName)); getMethodBuilder.addStatement("return $L.get($L)", CodeBlock.of(delegateFieldName), parametersCodeBlock); getMethodBuilder.nextControlFlow("else"); } CodeBlock.Builder providesMethodInvocationBuilder = CodeBlock.builder(); if (binding.requiresModuleInstance()) { providesMethodInvocationBuilder.add("module"); } else { providesMethodInvocationBuilder.add("$T", ClassName.get(binding.bindingTypeElement().get())); } providesMethodInvocationBuilder.add(".$L($L)", binding.bindingElement().get().getSimpleName(), parametersCodeBlock); CodeBlock providesMethodInvocation = providesMethodInvocationBuilder.build(); getMethodBuilder.addStatement("return $L", providesMethodInvocation); if (Util.bindingSupportsTestDelegate(binding)) { getMethodBuilder.endControlFlow(); } /*if (binding.nullableType().isPresent() || compilerOptions.nullableValidationKind().equals(Diagnostic.Kind.WARNING)) { if (binding.nullableType().isPresent()) { getMethodBuilder.addAnnotation((ClassName) TypeName.get(binding.nullableType().get())); } getMethodBuilder.addStatement("return $L", providesMethodInvocation); } else { getMethodBuilder.addStatement("return $T.checkNotNull($L, $S)", Preconditions.class, providesMethodInvocation, CANNOT_RETURN_NULL_FROM_NON_NULLABLE_PROVIDES_METHOD); }*/ } else if (binding.membersInjectionRequest().isPresent()) { if (Util.bindingSupportsTestDelegate(binding)) { getMethodBuilder.beginControlFlow("if ($L != null)", codeBlock); getMethodBuilder.addStatement("return $T.injectMembers($N, $L.get($L))", MembersInjectors.class, fields.get(binding.membersInjectionRequest().get().bindingKey()), codeBlock, parametersCodeBlock); getMethodBuilder.nextControlFlow("else"); } getMethodBuilder.addStatement("return $T.injectMembers($N, new $T($L))", MembersInjectors.class, fields.get(binding.membersInjectionRequest().get().bindingKey()), providedTypeName, parametersCodeBlock); if (Util.bindingSupportsTestDelegate(binding)) { getMethodBuilder.endControlFlow(); } } else { if (Util.bindingSupportsTestDelegate(binding)) { getMethodBuilder.beginControlFlow("if ($L != null)", codeBlock); getMethodBuilder.addStatement("return $L.get($L)", codeBlock, parametersCodeBlock); getMethodBuilder.nextControlFlow("else"); } getMethodBuilder.addStatement("return new $T($L)", providedTypeName, parametersCodeBlock); if (Util.bindingSupportsTestDelegate(binding)) { getMethodBuilder.endControlFlow(); } } factoryBuilder.addMethod(getMethodBuilder.build()); if (createMethod.isPresent()) { factoryBuilder.addMethod(createMethod.get()); } proxyMethodFor(binding).ifPresent(factoryBuilder::addMethod); gwtIncompatibleAnnotation(binding).ifPresent(factoryBuilder::addAnnotation); return Optional.of(factoryBuilder); }
From source file:de.hpi.bp2013n1.anonymizer.Anonymizer.java
private void copyAndAnonymizeRow(TableRuleMap tableRuleMap, String qualifiedTableName, ResultSetMetaData rsMeta, int columnCount, ResultSetRowReader rowReader, PreparedStatement insertStatement) throws SQLException { boolean retainRow = false; if (foreignKeyDeletions.hasParentRowBeenDeleted(rowReader)) { retainRow = retainService.currentRowShouldBeRetained(config.schemaName, tableRuleMap.tableName, rowReader);//w ww . j a v a 2 s . c om if (retainRow) { anonymizerLogger.warning("Retaining a row in " + qualifiedTableName + " even though its parent row " + "in another table has been deleted!"); } else { // the parent row has been deleted, so delete this row as well // since the foreign key cannot be reestablished and should // possible be kept secret foreignKeyDeletions.rowHasBeenDeleted(rowReader); return; } } // apply rules which have no column name specified first // because these are likely to be retain or delete instructions for (Rule configRule : tableRuleMap.getRules(null)) { if (Iterables.isEmpty(anonymizeValue(null, configRule, rowReader, null, tableRuleMap))) { if (retainRow || retainService.currentRowShouldBeRetained(configRule.getTableField().schema, configRule.getTableField().table, rowReader)) { // skip this transformation which deleted the tuple anonymizerLogger.info("Not deleting a row in " + qualifiedTableName + " because it " + "was previously marked to be " + "retained."); retainRow = true; continue; } foreignKeyDeletions.rowHasBeenDeleted(rowReader); return; } } // apply rules to specific columns List<Iterable<?>> columnValues = new ArrayList<>(columnCount); for (int j = 1; j <= columnCount; j++) { // for all columns String columnName = rsMeta.getColumnName(j); ImmutableList<Rule> appliedRules = tableRuleMap.getRules(columnName); // check if column needs translation if (!appliedRules.isEmpty()) { // fetch translations Iterable<?> currentValues = Lists.newArrayList(rowReader.getObject(j)); for (Rule configRule : appliedRules) { Iterable<Object> newValues = Collections.emptyList(); for (Object intermediateValue : currentValues) { Iterable<?> transformationResults = anonymizeValue(intermediateValue, configRule, rowReader, columnName, tableRuleMap); newValues = Iterables.concat(newValues, transformationResults); } if (!newValues.iterator().hasNext()) { if (retainRow || retainService.currentRowShouldBeRetained(configRule.getTableField().schema, configRule.getTableField().table, rowReader)) { // skip this transformation which deleted the tuple anonymizerLogger.info("Not deleting a row in " + qualifiedTableName + " because it " + "was previously marked to be " + "retained."); retainRow = true; continue; } // if a Strategy returned an empty transformation, the // cross product of all column values will be empty, // the original tuple is lost foreignKeyDeletions.rowHasBeenDeleted(rowReader); return; } currentValues = newValues; } columnValues.add(currentValues); } else { // if column doesn't have to be anonymized, take old value columnValues.add(Lists.newArrayList(rowReader.getObject(j))); } } try { addBatchInserts(insertStatement, columnValues); } catch (SQLException e) { anonymizerLogger.severe("Adding insert statement failed: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.google.errorprone.bugpatterns.threadsafety.ThreadSafety.java
private AnnotationInfo getAnnotation(Symbol sym, VisitorState state, String annotation, @Nullable Class<? extends Annotation> elementAnnotation) { if (sym == null) { return null; }//w w w . jav a2s. c o m Optional<Compound> attr = sym.getRawAttributes().stream() .filter(a -> a.type.tsym.getQualifiedName().contentEquals(annotation)).findAny(); if (attr.isPresent()) { ImmutableList<String> containerElements = containerOf(state, attr.get()); if (elementAnnotation != null && containerElements.isEmpty()) { containerElements = sym.getTypeParameters().stream() .filter(p -> p.getAnnotation(elementAnnotation) != null) .map(p -> p.getSimpleName().toString()).collect(toImmutableList()); } return AnnotationInfo.create(sym.getQualifiedName().toString(), containerElements); } // @ThreadSafe is inherited from supertypes if (!(sym instanceof ClassSymbol)) { return null; } Type superClass = ((ClassSymbol) sym).getSuperclass(); AnnotationInfo superAnnotation = getInheritedAnnotation(superClass.asElement(), state); if (superAnnotation == null) { return null; } // If an annotated super-type was found, look for any type arguments to the super-type that // are in the super-type's containerOf spec, and where the arguments are type parameters // of the current class. // E.g. for `Foo<X> extends Super<X>` if `Super<Y>` is annotated // `@ThreadSafeContainerAnnotation Y` // then `Foo<X>` is has X implicitly annotated `@ThreadSafeContainerAnnotation X` ImmutableList.Builder<String> containerOf = ImmutableList.builder(); for (int i = 0; i < superClass.getTypeArguments().size(); i++) { Type arg = superClass.getTypeArguments().get(i); TypeVariableSymbol formal = superClass.asElement().getTypeParameters().get(i); if (!arg.hasTag(TypeTag.TYPEVAR)) { continue; } TypeSymbol argSym = arg.asElement(); if (argSym.owner == sym && superAnnotation.containerOf().contains(formal.getSimpleName().toString())) { containerOf.add(argSym.getSimpleName().toString()); } } return AnnotationInfo.create(superAnnotation.typeName(), containerOf.build()); }
From source file:com.google.devtools.build.lib.bazel.rules.java.BazelJavaSemantics.java
private void checkMainClass(RuleContext ruleContext, ImmutableList<Artifact> sources) { boolean createExecutable = ruleContext.attributes().get("create_executable", Type.BOOLEAN); String mainClass = getMainClassInternal(ruleContext, sources); if (!createExecutable && !isNullOrEmpty(mainClass)) { ruleContext.ruleError("main class must not be specified when executable is not created"); }/* w ww . j ava 2 s . c om*/ if (createExecutable && isNullOrEmpty(mainClass)) { if (sources.isEmpty()) { ruleContext.ruleError("need at least one of 'main_class' or Java source files"); } mainClass = JavaCommon.determinePrimaryClass(ruleContext, sources); if (mainClass == null) { ruleContext.ruleError("cannot determine main class for launching " + "(found neither a source file '" + ruleContext.getTarget().getName() + ".java', nor a main_class attribute, and package name " + "doesn't include 'java' or 'javatests')"); } } }
From source file:org.geogit.storage.BlueprintsGraphDatabase.java
/** * Adds a commit to the database with the given parents. If a commit with the same id already * exists, it will not be inserted./*from w ww . j a va 2s. com*/ * * @param commitId the commit id to insert * @param parentIds the commit ids of the commit's parents * @return true if the commit id was inserted, false otherwise */ @Override public boolean put(ObjectId commitId, ImmutableList<ObjectId> parentIds) { boolean updated = false; try { // See if it already exists Vertex commitNode = getOrAddNode(commitId); if (parentIds.isEmpty()) { if (!commitNode.getEdges(OUT, CommitRelationshipTypes.TOROOT.name()).iterator().hasNext()) { // Attach this node to the root node commitNode.addEdge(CommitRelationshipTypes.TOROOT.name(), root); updated = true; } } if (!commitNode.getEdges(OUT, CommitRelationshipTypes.PARENT.name()).iterator().hasNext()) { // Don't make relationships if they have been created already for (ObjectId parent : parentIds) { Vertex parentNode = getOrAddNode(parent); commitNode.addEdge(CommitRelationshipTypes.PARENT.name(), parentNode); updated = true; } } this.commit(); } catch (Exception e) { this.rollback(); throw Throwables.propagate(e); } return updated; }
From source file:org.zanata.client.commands.push.RawPushCommand.java
@Override public void run() throws IOException { PushCommand.logOptions(log, getOpts()); consoleInteractor.printfln(DisplayMode.Warning, "Using EXPERIMENTAL project type 'file'."); List<FileTypeInfo> serverAcceptedTypes = fileTypeInfoList(client); if (getOpts().getListFileTypes()) { printFileTypes(serverAcceptedTypes); return;//from ww w . j a v a 2 s . c o m } if (!pushSource() && !pushTrans()) { throw new RuntimeException("Invalid option for push type"); } // only supporting single module for now File sourceDir = getOpts().getSrcDir(); if (!sourceDir.exists()) { boolean enableModules = getOpts().getEnableModules(); // TODO(files) remove warning when modules supported if (enableModules) { consoleInteractor.printfln(DisplayMode.Warning, "enableModules=true but multi-modules not yet supported for this command. Using single module push."); } throw new RuntimeException("directory '" + sourceDir + "' does not exist - check " + getOpts().getSrcDirParameterName() + " option"); } RawPushStrategy strat = new RawPushStrategy(); strat.setPushOptions(getOpts()); ImmutableList<FileTypeInfo> actualFileTypes = getActualFileTypes(serverAcceptedTypes, getOpts().getFileTypes()); if (actualFileTypes.isEmpty()) { log.info("no valid types specified; nothing to do"); return; } ImmutableList.Builder<String> sourceFileExtensionsBuilder = ImmutableList.builder(); actualFileTypes .forEach(fileTypeInfo -> sourceFileExtensionsBuilder.addAll(fileTypeInfo.getSourceExtensions())); ImmutableList<String> sourceFileExtensions = sourceFileExtensionsBuilder.build(); String[] srcFiles = strat.getSrcFiles(sourceDir, getOpts().getIncludes(), getOpts().getExcludes(), sourceFileExtensions, true, getOpts().getCaseSensitive()); SortedSet<String> localDocNames = new TreeSet<String>(Arrays.asList(srcFiles)); // TODO(files) handle obsolete document deletion consoleInteractor.printfln(DisplayMode.Warning, "Obsolete document removal is not yet implemented, no documents will be removed from the server."); SortedSet<String> docsToPush = localDocNames; if (getOpts().getFromDoc() != null) { if (!localDocNames.contains(getOpts().getFromDoc())) { log.error("Document with id {} not found, unable to start push from unknown document. Aborting.", getOpts().getFromDoc()); // FIXME should this be throwing an exception to properly abort? // need to see behaviour with modules return; } docsToPush = localDocNames.tailSet(getOpts().getFromDoc()); int numSkippedDocs = localDocNames.size() - docsToPush.size(); log.info("Skipping {} document(s) before {}.", numSkippedDocs, getOpts().getFromDoc()); } if (docsToPush.isEmpty()) { log.info("no documents in module: {}; nothing to do", getOpts().getCurrentModule()); return; } else { consoleInteractor.printfln("Found source documents:"); for (String docName : localDocNames) { if (docsToPush.contains(docName)) { FileTypeName fileType = getFileTypeNameBySourceExtension(actualFileTypes, FilenameUtils.getExtension(docName)); consoleInteractor.printfln(" " + Messages.format("push.info.documentToPush", docName, fileType.getName())); } else { consoleInteractor.printfln(Messages.format("push.info.skipDocument", docName)); } } } if (pushTrans()) { if (getOpts().getLocaleMapList() == null) throw new ConfigException( "pushType set to '" + getOpts().getPushType() + "', but project has no locales configured"); consoleInteractor.printfln(DisplayMode.Warning, Messages.format("push.warn.overrideTranslations", getOpts().getPushType())); if (getOpts().getPushType() == PushPullType.Both) { confirmWithUser("This will overwrite existing documents AND TRANSLATIONS on the server.\n"); // , and delete obsolete documents.\n"); } else if (getOpts().getPushType() == PushPullType.Trans) { confirmWithUser("This will overwrite existing TRANSLATIONS on the server.\n"); } } else { // confirmWithUser("This will overwrite existing documents on the server, and delete obsolete documents.\n"); confirmWithUser("This will overwrite existing documents on the server.\n"); } boolean hasErrors = false; for (final String localDocName : docsToPush) { try { final String srcExtension = FilenameUtils.getExtension(localDocName); final FileTypeInfo fileType = getFileType(actualFileTypes, srcExtension); final String qualifiedDocName = qualifiedDocName(localDocName); if (pushSource()) { if (!getOpts().isDryRun()) { boolean sourcePushed = pushSourceDocumentToServer(sourceDir, localDocName, qualifiedDocName, fileType.getType().getName()); // ClientUtility.checkResult(putResponse, uri); if (!sourcePushed) { hasErrors = true; } } else { log.info("pushing source doc [qualifiedname={}] to server (skipped due to dry run)", qualifiedDocName); } } if (pushTrans()) { Optional<String> translationFileExtension = getTranslationFileExtension(fileType, srcExtension); strat.visitTranslationFiles(localDocName, new TranslationFilesVisitor() { @Override public void visit(LocaleMapping locale, File translatedDoc) { log.info("pushing {} translation of {}", locale.getLocale(), qualifiedDocName); pushDocumentToServer(qualifiedDocName, fileType.getType().getName(), locale.getLocale(), translatedDoc); } }, translationFileExtension); } } catch (IOException | RuntimeException e) { log.error( "Operation failed: " + e.getMessage() + "\n\n" + " To retry from the last document, please add the option: {}\n", getOpts().buildFromDocArgument(localDocName)); throw new RuntimeException(e.getMessage(), e); } } if (hasErrors) { throw new RuntimeException("Push completed with errors, see log for details."); } }
From source file:com.squareup.wire.java.TypeWriter.java
public TypeSpec registryType(ClassName javaTypeName, Schema schema) { TypeSpec.Builder builder = TypeSpec.classBuilder(javaTypeName.simpleName()).addModifiers(PUBLIC, FINAL); ImmutableSet.Builder<TypeName> extensionClassesBuilder = ImmutableSet.builder(); for (ProtoFile protoFile : schema.protoFiles()) { if (!protoFile.extendList().isEmpty()) { extensionClassesBuilder.add(javaGenerator.extensionsClass(protoFile)); }/*from w w w .ja v a2 s. c om*/ } ImmutableList<TypeName> extensionClasses = extensionClassesBuilder.build().asList(); CodeBlock.Builder initializer = CodeBlock.builder(); if (extensionClasses.isEmpty()) { initializer.add("$T.emptyList()", Collections.class); } else { initializer.add("$>$>$T.unmodifiableList($T.asList(", Collections.class, Arrays.class); for (int i = 0, size = extensionClasses.size(); i < size; i++) { TypeName typeName = extensionClasses.get(i); initializer.add("\n$T.class", typeName); if (i + 1 < extensionClasses.size()) initializer.add(","); } initializer.add("))$<$<"); } TypeName wildcard = extensionClasses.size() == 1 ? extensionClasses.get(0) : WildcardTypeName.subtypeOf(Object.class); TypeName listType = JavaGenerator.listOf(ParameterizedTypeName.get(ClassName.get(Class.class), wildcard)); builder.addField(FieldSpec.builder(listType, "EXTENSIONS", PUBLIC, STATIC, FINAL) .initializer(initializer.build()).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class) .addMember("value", "$S", "unchecked").build()) .build()); // Private no-args constructor builder.addMethod(MethodSpec.constructorBuilder().addModifiers(PRIVATE).build()); return builder.build(); }