List of usage examples for com.google.common.collect ImmutableList toArray
<T> T[] toArray(T[] a);
From source file:com.quancheng.plugin.common.CommondProtoc.java
public FileDescriptorSet invoke(String protoPath) { Path descriptorPath;//from w w w. j a v a 2s .c om try { descriptorPath = Files.createTempFile("descriptor", ".pb.bin"); ImmutableList<String> protocArgs = ImmutableList.<String>builder()// .add("-I" + discoveryRoot)// .add("--descriptor_set_out=" + descriptorPath.toAbsolutePath().toString())// .add(protoPath)// .build(); int status; String[] protocLogLines; PrintStream stdoutBackup = System.out; try { ByteArrayOutputStream protocStdout = new ByteArrayOutputStream(); System.setOut(new PrintStream(protocStdout)); status = Protoc.runProtoc(protocArgs.toArray(new String[0])); protocLogLines = protocStdout.toString().split("\n"); } catch (IOException | InterruptedException e) { throw new IllegalArgumentException("Unable to execute protoc binary", e); } finally { System.setOut(stdoutBackup); } if (status != 0) { logger.warn("Protoc invocation failed with status: " + status); for (String line : protocLogLines) { logger.warn("[Protoc log] " + line); } throw new IllegalArgumentException( String.format("Got exit code [%d] from protoc with args [%s]", status, protocArgs)); } return FileDescriptorSet.parseFrom(Files.readAllBytes(descriptorPath)); } catch (IOException e) { throw new IllegalArgumentException(e); } }
From source file:com.netxforge.netxstudio.screens.f2.ExpressionSupport.java
/** * Not used.//from w w w . j av a 2 s.com * * @param expression * @param contextList * @param doc * @deprecated * @return */ public List<BaseExpressionResult> testExpression(Expression expression, ImmutableList<IComputationContext> contextList, IXtextDocument doc) { List<BaseExpressionResult> result = null; // final IXtextDocument doc = xtextEditor.getDocument(); assert !documentHasErrors(doc) : "Intepreter cancelled, as errors exist in script: " + doc.get(); final IComputationContext[] contextArray = new IComputationContext[contextList.size()]; if (interpreter instanceof IExternalContextAware) { ((IExternalContextAware) interpreter).setExternalContext(contextList.toArray(contextArray)); } result = doc.readOnly(new IUnitOfWork<List<BaseExpressionResult>, XtextResource>() { public List<BaseExpressionResult> exec(XtextResource resource) throws Exception { if (resource.getContents().isEmpty()) { return null; } try { EObject rootASTElement = resource.getParseResult().getRootASTElement(); if ((rootASTElement instanceof Mod)) { Mod root = (Mod) resource.getContents().get(0); interpreter.evaluate(root); return interpreter.getResult(); } } catch (Throwable t) { // something with t. t.printStackTrace(); } return null; } }); return result; }
From source file:org.dcache.srm.SRM.java
public String[] getProtocols() throws SRMInternalErrorException { List<String> getProtocols = asList(storage.supportedGetProtocols()); List<String> putProtocols = asList(storage.supportedPutProtocols()); ImmutableList<String> protocols = ImmutableSet.copyOf(concat(getProtocols, putProtocols)).asList(); return protocols.toArray(new String[protocols.size()]); }
From source file:org.zanata.client.commands.push.AbstractCommonPushStrategy.java
/** * excludes should already contain paths for translation files that are to * be excluded./*from w ww.jav a 2s.c o m*/ */ public String[] getSrcFiles(File srcDir, ImmutableList<String> includes, ImmutableList<String> excludes, ImmutableList<String> fileExtensions, boolean useDefaultExcludes, boolean isCaseSensitive) { if (includes.isEmpty()) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (String fileExtension : fileExtensions) { builder.add("**/*" + fileExtension); } includes = builder.build(); } DirectoryScanner dirScanner = new DirectoryScanner(); if (useDefaultExcludes) { dirScanner.addDefaultExcludes(); } dirScanner.setBasedir(srcDir); dirScanner.setCaseSensitive(isCaseSensitive); dirScanner.setExcludes(excludes.toArray(new String[excludes.size()])); dirScanner.setIncludes(includes.toArray(new String[includes.size()])); dirScanner.scan(); String[] includedFiles = dirScanner.getIncludedFiles(); for (int i = 0; i < includedFiles.length; i++) { // canonicalise file separator (to handle backslash on Windows) includedFiles[i] = includedFiles[i].replace(File.separator, "/"); } return includedFiles; }
From source file:org.fcrepo.transform.sparql.JQLQueryVisitor.java
/** * Get the ordering of the JCR query// w ww. j a v a2 s. co m * @return */ private Ordering[] getOrderings() { final ImmutableList<Ordering> build = this.orderings.build(); return build.toArray(new Ordering[build.size()]); }
From source file:com.google.testing.i18n.sanitycheck.checkers.TokenizationChecker.java
@Override protected void makeCheck(Placeholder target, ImmutableList<String> tokenizedInput, ULocale locale, String message) {//from w w w . j a va 2 s .c o m StringBuilder untokenizedString = new StringBuilder(); String expected = target.getExpectedValue(); if (expected.isEmpty()) { for (String token : tokenizedInput) { untokenizedString.append(token); } } else { untokenizedString.append(expected); } ImmutableList<String> tokensFromICU = getTokens(untokenizedString.toString(), BreakIterator.getWordInstance(locale)); String errorMessage = message != null ? message : String.format( "The tokenization %s for the text \"%s\" doesn't appear to be valid for %s." + "Should be more like: %s", Arrays.toString(tokenizedInput.toArray(new String[0])), untokenizedString.toString(), locale.getDisplayLanguage(), Arrays.toString(tokensFromICU.toArray(new String[0]))); Assert.assertEquals(errorMessage, tokensFromICU, tokenizedInput); }
From source file:org.eclipse.buildship.core.workspace.internal.DefaultWorkspaceOperations.java
@Override public void removeBuildCommand(IProject project, final String name, IProgressMonitor monitor) { SubMonitor progress = SubMonitor.convert(monitor, 1); try {/*from w ww . j a v a2 s.c o m*/ IProjectDescription description = project.getDescription(); ImmutableList<ICommand> existingCommands = ImmutableList.copyOf(description.getBuildSpec()); // remove the build command based on the name ImmutableList<ICommand> updatedCommands = FluentIterable.from(existingCommands) .filter(new Predicate<ICommand>() { @Override public boolean apply(ICommand command) { return !command.getBuilderName().equals(name); } }).toList(); // only update the project description if the build command to remove exists SubMonitor updateProgress = progress.newChild(1); if (existingCommands.size() != updatedCommands.size()) { description.setBuildSpec(updatedCommands.toArray(new ICommand[updatedCommands.size()])); project.setDescription(description, updateProgress); } } catch (CoreException e) { String message = String.format("Cannot remove build command %s from Eclipse project %s.", name, project.getName()); throw new GradlePluginsRuntimeException(message, e); } }
From source file:com.facebook.buck.jvm.kotlin.JarBackedReflectedKotlinc.java
@Override public int buildWithClasspath(ExecutionContext context, BuildTarget invokingRule, ImmutableList<String> options, ImmutableSortedSet<Path> kotlinSourceFilePaths, Path pathToSrcsList, Optional<Path> workingDirectory, ProjectFilesystem projectFilesystem) { ImmutableList<Path> expandedSources; try {/*from w w w . j av a2 s.c om*/ expandedSources = getExpandedSourcePaths(projectFilesystem, context.getProjectFilesystemFactory(), kotlinSourceFilePaths, workingDirectory); } catch (Throwable throwable) { throwable.printStackTrace(); throw new HumanReadableException("Unable to expand sources for %s into %s", invokingRule, workingDirectory); } ImmutableList<String> args = ImmutableList.<String>builder().addAll(options).addAll( transform(expandedSources, path -> projectFilesystem.resolve(path).toAbsolutePath().toString())) .build(); Set<File> compilerIdPaths = compilerClassPath.stream().map(p -> ((PathSourcePath) p).getRelativePath()) .map(Path::toFile).collect(Collectors.toSet()); try { Object compilerShim = kotlinShims.computeIfAbsent( compilerIdPaths.stream().map(File::getAbsolutePath).collect(Collectors.toSet()), k -> loadCompilerShim(context)); Method compile = compilerShim.getClass().getMethod("exec", PrintStream.class, String[].class); Class<?> exitCodeClass = compilerShim.getClass().getClassLoader().loadClass(EXIT_CODE_CLASS); Method getCode = exitCodeClass.getMethod("getCode"); try (UncloseablePrintStream stdErr = new UncloseablePrintStream(context.getStdErr())) { Object exitCode = compile.invoke(compilerShim, stdErr, args.toArray(new String[0])); return (Integer) getCode.invoke(exitCode); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException | ClassNotFoundException ex) { throw new RuntimeException(ex); } }
From source file:ru.adios.budgeter.activities.BalancesTransferActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { selectedReceiverAccount = savedInstanceState.getInt(KEY_SELECTED_RECEIVER_ACCOUNT, -1); final long[] ids = savedInstanceState.getLongArray(KEY_SUGGESTED_RECEIVERS); if (ids == null) { suggestedReceivers = ImmutableList.of(); } else {/* w w w. j av a 2 s. c o m*/ ImmutableList.Builder<Long> builder = ImmutableList.builder(); for (final long i : ids) { builder.add(i); } suggestedReceivers = builder.build(); } } if (selectedReceiverAccount >= 0) { final ImmutableList<Long> receiversSnapshot = ImmutableList.copyOf(suggestedReceivers); new AsyncTask<Long[], Void, ImmutableList<BalanceAccount>>() { @Override protected ImmutableList<BalanceAccount> doInBackground(Long[]... params) { final Long[] ids = params[0]; final ImmutableList.Builder<BalanceAccount> builder = ImmutableList.builder(); for (final Long i : ids) { final Optional<BalanceAccount> byId = treasury.getById(i); if (byId.isPresent()) { builder.add(byId.get()); } } return builder.build(); } @Override protected void onPostExecute(ImmutableList<BalanceAccount> balanceAccounts) { if (receiversSnapshot.equals(suggestedReceivers)) { fillReceiversSpinner(balanceAccounts); if (receiverAccountSpinner != null) { receiverAccountSpinner.setSelection(selectedReceiverAccount); receiverAccountSpinner.setVisibility(View.VISIBLE); receiverAccountInfo.setVisibility(View.INVISIBLE); } } } }.execute(receiversSnapshot.toArray(new Long[receiversSnapshot.size()])); } collectEssentialViews(); receiverAccountSpinner.setOnItemSelectedListener(new EmptyOnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { selectedReceiverAccount = parent.getAdapter().getCount() > position ? position : -1; } }); transferErrorHighlighter.addElementInfo(BalancesTransferCore.FIELD_RECEIVER_ACCOUNT, receiverAccountInfo); CoreNotifier.addLink(this, receiverAccountSpinner, new CoreNotifier.ArbitraryLinker() { @Override public boolean link(Object data) { final BalanceAccount object = (BalanceAccount) data; final BalanceAccount prev = transferElement.getReceiverAccount(); if ((prev == null && object != null) || (prev != null && !prev.equals(object))) { transferElement.setReceiverAccount(object); return true; } return false; } }); final View infoView = findViewById(R.id.balances_transfer_info); senderAccountInfoProvider.getSubmitInfo(AccountStandardFragment.BUTTON_NEW_ACCOUNT_SUBMIT).errorHighlighter .setGlobalInfoView(infoView); transferErrorHighlighter.setGlobalInfoView(infoView); }
From source file:com.google.devtools.build.lib.rules.objc.ObjcRuleTestCase.java
protected void checkCcDependencyWithProtoDependency(BinaryRuleTypePair ruleTypePair, ConfigurationDistinguisher configurationDistinguisher) throws Exception { MockProtoSupport.setup(mockToolsConfig); useConfiguration("--cpu=ios_i386"); scratch.file("lib/BUILD", "proto_library(", " name = 'protolib',", " srcs = ['foo.proto'],", " cc_api_version = 1,", ")", "", "cc_library(", " name = 'cclib',", " srcs = ['dep.c'],", " deps = [':protolib'],", ")"); ruleTypePair.scratchTargets(scratch, "deps", "['//lib:cclib']"); Action appLipoAction = lipoBinAction("//x:x"); CommandAction binBinAction = (CommandAction) getGeneratingAction( getFirstArtifactEndingWith(appLipoAction.getInputs(), "bin_bin")); String i386Prefix = iosConfigurationCcDepsBin("i386", configurationDistinguisher); ImmutableList<String> archiveFilenames = ImmutableList.of(i386Prefix + "lib/libcclib.a", i386Prefix + "x/libbin.a", i386Prefix + "lib/libprotolib.a", i386Prefix + "net/proto/libproto.a"); verifyObjlist(binBinAction, "x/bin-linker.objlist", archiveFilenames.toArray(new String[archiveFilenames.size()])); assertThat(Artifact.toExecPaths(binBinAction.getInputs())).containsAllIn( ImmutableList.builder().addAll(archiveFilenames).add(i386Prefix + "x/bin-linker.objlist").build()); }