Java Code Examples for com.google.common.collect.ObjectArrays

The following examples show how to use com.google.common.collect.ObjectArrays. These examples are extracted from open source projects.
Example 1
Project: NullAway   File: JarInferTest.java    License: MIT License 6 votes vote down vote up
/**
 * Create, compile, and run a unit test.
 *
 * @param testName An useful name for the unit test.
 * @param pkg Qualified package name.
 * @param cls Target class to be analyzed.
 * @param expected Map of 'method signatures' to their 'expected list of NonNull parameters'.
 * @param lines Source lines for the test code.
 */
private void testTemplate(
    String testName,
    String pkg, // in dot syntax
    String cls,
    Map<String, Set<Integer>> expected,
    String... lines)
    throws Exception {
  boolean compileSucceeded =
      compilerUtil
          .addSourceLines(cls + ".java", ObjectArrays.concat("package " + pkg + ";\n", lines))
          .run();
  Assert.assertTrue(
      testName + ": test compilation failed!\n" + compilerUtil.getOutput(), compileSucceeded);
  DefinitelyDerefedParamsDriver driver = new DefinitelyDerefedParamsDriver();
  Map<String, Set<Integer>> result =
      driver.run(
          temporaryFolder.getRoot().getAbsolutePath(), "L" + pkg.replaceAll("\\.", "/"), true);
  Assert.assertTrue(
      testName + ": test failed! \n" + result + " does not match " + expected,
      verify(result, new HashMap<>(expected)));
}
 
Example 2
Project: embedded-database-spring-test   File: OptimizedFlywayTestExecutionListener.java    License: Apache License 2.0 6 votes vote down vote up
protected static DataSource reloadDataSource(FlywayDataSourceContext dataSourceContext, Flyway flywayBean, FlywayTest annotation) throws Exception {
    if (isAppendable(flywayBean, annotation)) {
        return dataSourceContext.reload(flywayBean).get();
    } else {
        String[] oldLocations = getFlywayLocations(flywayBean);
        try {
            if (annotation.overrideLocations()) {
                setFlywayLocations(flywayBean, annotation.locationsForMigrate());
            } else {
                setFlywayLocations(flywayBean, ObjectArrays.concat(oldLocations, annotation.locationsForMigrate(), String.class));
            }
            return dataSourceContext.reload(flywayBean).get();
        } finally {
            setFlywayLocations(flywayBean, oldLocations);
        }
    }
}
 
Example 3
Project: codebuff   File: SimpleTimeLimiter.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
  Throwable cause = e.getCause();
  if (cause == null) {
    throw e;
  }
  if (combineStackTraces) {
    StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
    cause.setStackTrace(combined);
  }
  if (cause instanceof Exception) {
    throw (Exception) cause;
  }
  if (cause instanceof Error) {
    throw (Error) cause;
  }
  // The cause is a weird kind of Throwable, so throw the outer exception.
  throw e;
}
 
Example 4
Project: codebuff   File: SimpleTimeLimiter.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
  Throwable cause = e.getCause();
  if (cause == null) {
    throw e;
  }
  if (combineStackTraces) {
    StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
    cause.setStackTrace(combined);
  }
  if (cause instanceof Exception) {
    throw (Exception) cause;
  }
  if (cause instanceof Error) {
    throw (Error) cause;
  }
  // The cause is a weird kind of Throwable, so throw the outer exception.
  throw e;
}
 
Example 5
Project: teammates   File: AppPage.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Waits and verifies that the texts of user status messages in the page are equal to the expected texts.
 * The check is done multiple times with waiting times in between to account for
 * timing issues due to page load, inconsistencies in Selenium API, etc.
 */
public void waitForTextsForAllStatusMessagesToUserEquals(String firstExpectedText, String... remainingExpectedTexts) {
    List<String> expectedTexts = Arrays.asList(ObjectArrays.concat(firstExpectedText, remainingExpectedTexts));
    try {
        uiRetryManager.runUntilNoRecognizedException(new RetryableTask("Verify status to user") {
            @Override
            public void run() {
                // Scroll to status message because it must be visible in order to get its text
                new Actions(browser.driver).moveToElement(statusMessage).perform();
                waitForElementVisibility(statusMessage);

                assertEquals(expectedTexts, getTextsForAllStatusMessagesToUser());
            }
        }, WebDriverException.class, AssertionError.class);
    } catch (MaximumRetriesExceededException e) {
        assertEquals(expectedTexts, getTextsForAllStatusMessagesToUser());
    }
}
 
Example 6
Project: codebuff   File: SimpleTimeLimiter.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
  Throwable cause = e.getCause();
  if (cause == null) {
    throw e;
  }
  if (combineStackTraces) {
    StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
    cause.setStackTrace(combined);
  }
  if (cause instanceof Exception) {
    throw (Exception) cause;
  }
  if (cause instanceof Error) {
    throw (Error) cause;
  }
  // The cause is a weird kind of Throwable, so throw the outer exception.
  throw e;
}
 
Example 7
Project: codebuff   File: SimpleTimeLimiter.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static Exception throwCause(Exception e, boolean combineStackTraces) throws Exception {
  Throwable cause = e.getCause();
  if (cause == null) {
    throw e;
  }
  if (combineStackTraces) {
    StackTraceElement[] combined =
        ObjectArrays.concat(cause.getStackTrace(), e.getStackTrace(), StackTraceElement.class);
    cause.setStackTrace(combined);
  }
  if (cause instanceof Exception) {
    throw (Exception) cause;
  }
  if (cause instanceof Error) {
    throw (Error) cause;
  }
  // The cause is a weird kind of Throwable, so throw the outer exception.
  throw e;
}
 
Example 8
Project: pnc   File: AbstractProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<DTO> queryForCollection(
        int pageIndex,
        int pageSize,
        String sortingRsql,
        String query,
        Predicate<DB>... predicates) {
    Predicate<DB> rsqlPredicate = rsqlPredicateProducer.getCriteriaPredicate(type, query);
    PageInfo pageInfo = pageInfoProducer.getPageInfo(pageIndex, pageSize);
    SortInfo sortInfo = rsqlPredicateProducer.getSortInfo(type, sortingRsql);
    List<DB> collection = repository
            .queryWithPredicates(pageInfo, sortInfo, ObjectArrays.concat(rsqlPredicate, predicates));
    int totalHits = repository.count(ObjectArrays.concat(rsqlPredicate, predicates));
    int totalPages = (totalHits + pageSize - 1) / pageSize;
    List<DTO> content = nullableStreamOf(collection).map(mapper::toDTO).collect(Collectors.toList());
    return new Page<>(pageIndex, pageSize, totalPages, totalHits, content);
}
 
Example 9
Project: plugins   File: WorldHopperPlugin.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void insertMenuEntry(MenuEntry newEntry, MenuEntry[] entries, boolean after)
{
	MenuEntry[] newMenu = ObjectArrays.concat(entries, newEntry);

	if (after)
	{
		int menuEntryCount = newMenu.length;
		ArrayUtils.swap(newMenu, menuEntryCount - 1, menuEntryCount - 2);
	}

	client.setMenuEntries(newMenu);
}
 
Example 10
Project: presto   File: RequestErrorTracker.java    License: Apache License 2.0 5 votes vote down vote up
static void logError(Throwable t, String format, Object... args)
{
    if (isExpectedError(t)) {
        log.error(format + ": %s", ObjectArrays.concat(args, t));
    }
    else {
        log.error(t, format, args);
    }
}
 
Example 11
Project: browserup-proxy   File: TrustSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new TrustSource containing the same trusted CAs as this TrustSource, plus zero or more additional
 * trusted X509Certificates. If trustedCertificates is null or empty, returns this same TrustSource.
 *
 * @param trustedCertificates X509Certificates of CAs to trust
 * @return a new TrustSource containing this TrustSource's trusted CAs plus the specified CAs
 */
public TrustSource add(X509Certificate... trustedCertificates) {
    if (trustedCertificates == null || trustedCertificates.length == 0) {
        return this;
    }

    X509Certificate[] newTrustedCAs = ObjectArrays.concat(trustedCAs, trustedCertificates, X509Certificate.class);

    return new TrustSource(newTrustedCAs);
}
 
Example 12
Project: patchwork-api   File: ForgeConfigSpec.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public <V extends Comparable<? super V>> ConfigValue<V> defineInRange(List<String> path, Supplier<V> defaultSupplier, V min, V max, Class<V> clazz) {
	Range<V> range = new Range<>(clazz, min, max);
	context.setRange(range);
	context.setComment(ObjectArrays.concat(context.getComment(), "Range: " + range.toString()));

	if (min.compareTo(max) > 0) {
		throw new IllegalArgumentException("Range min most be less then max.");
	}

	return define(path, defaultSupplier, range);
}
 
Example 13
Project: CapturePacket   File: TrustSource.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a new TrustSource containing the same trusted CAs as this TrustSource, plus zero or more additional
 * trusted X509Certificates. If trustedCertificates is null or empty, returns this same TrustSource.
 *
 * @param trustedCertificates X509Certificates of CAs to trust
 * @return a new TrustSource containing this TrustSource's trusted CAs plus the specified CAs
 */
public TrustSource add(X509Certificate... trustedCertificates) {
    if (trustedCertificates == null || trustedCertificates.length == 0) {
        return this;
    }

    X509Certificate[] newTrustedCAs = ObjectArrays.concat(trustedCAs, trustedCertificates, X509Certificate.class);

    return new TrustSource(newTrustedCAs);
}
 
Example 14
Project: bundletool   File: ManifestProtoUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static XmlNode androidManifestForFeature(
    String packageName, ManifestMutator... manifestMutators) {
  return androidManifest(
      packageName,
      ObjectArrays.concat(
          new ManifestMutator[] {withOnDemandAttribute(true), withFusingAttribute(true)},
          manifestMutators,
          ManifestMutator.class));
}
 
Example 15
Project: ProjectAres   File: LaneMatchModule.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private static Block getAdjacentRegionBlock(Region region, Block origin) {
    for(BlockFace face : ObjectArrays.concat(CARDINAL_DIRECTIONS, DIAGONAL_DIRECTIONS, BlockFace.class)) {
        Block adjacent = origin.getRelative(face);
        if(region.contains(BlockUtils.center(adjacent).toVector())) {
            return adjacent;
        }
    }
    return null;
}
 
Example 16
Project: javaide   File: LocalSdk.java    License: GNU General Public License v3.0 5 votes vote down vote up
public IAndroidTarget[] getTargets(boolean includeMissing) {
    IAndroidTarget[] result = getTargets();
    if (includeMissing) {
        result = ObjectArrays.concat(result, getMissingTargets(), IAndroidTarget.class);
    }
    return result;
}
 
Example 17
Project: Elasticsearch   File: GetIndexRequest.java    License: Apache License 2.0 5 votes vote down vote up
public GetIndexRequest addFeatures(Feature... features) {
    if (this.features == DEFAULT_FEATURES) {
        return features(features);
    } else {
        return features(ObjectArrays.concat(featuresAsEnums(), features, Feature.class));
    }
}
 
Example 18
Project: aliyun-maxcompute-data-collectors   File: BaseSqoopTestCase.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new string array with 'moreEntries' appended to the 'entries'
 * array.
 * @param entries initial entries in the array
 * @param moreEntries variable-length additional entries.
 * @return an array containing entries with all of moreEntries appended.
 */
protected String [] newStrArray(String [] entries, String... moreEntries)  {
  if (null == moreEntries) {
    return entries;
  }

  if (null == entries) {
    entries = new String[0];
  }

  return ObjectArrays.concat(entries, moreEntries, String.class);
}
 
Example 19
Project: NioSmtpClient   File: SmtpSession.java    License: Apache License 2.0 5 votes vote down vote up
private SendSequence beginSequence(Optional<SendInterceptor> sequenceInterceptor, int expectedResponses, Object... objects) {
  if (requiresRset) {
    if (ehloResponse.isSupported(Extension.PIPELINING)) {
      return new SendSequence(sequenceInterceptor, expectedResponses + 1, ObjectArrays.concat(SmtpRequests.rset(), objects));
    } else {
      return new SendSequence(sequenceInterceptor, 1,  SmtpRequests.rset()).thenSend(objects);
    }
  } else {
    requiresRset = true;
    return new SendSequence(sequenceInterceptor, expectedResponses, objects);
  }
}
 
Example 20
Project: dremio-oss   File: QBlockHashTable.java    License: Apache License 2.0 5 votes vote down vote up
private void addDataBlocks() {

    try(RollbackCloseable rollbackable = new RollbackCloseable()) {

      // make sure can fit the next batch.
      listener.addBatch();

      {
        FixedBlockVector newFixed = new FixedBlockVector(allocator, pivot.getBlockWidth());
        rollbackable.add(newFixed);
        newFixed.ensureAvailableBlocks(MAX_VALUES_PER_BATCH);
        fixedBlocks = ObjectArrays.concat(fixedBlocks, newFixed);
        tableFixedAddresses = Longs.concat(tableFixedAddresses, new long[]{newFixed.getMemoryAddress()});
      }

      {
        VariableBlockVector newVariable = new VariableBlockVector(allocator, pivot.getVariableCount());
        rollbackable.add(newVariable);
        newVariable.ensureAvailableDataSpace(pivot.getVariableCount() == 0 ? 0 : MAX_VALUES_PER_BATCH * defaultVariableLengthSize);
        variableBlocks = ObjectArrays.concat(variableBlocks, newVariable);
        initVariableAddresses = Longs.concat(initVariableAddresses, new long[]{newVariable.getMemoryAddress()});
        openVariableAddresses = Longs.concat(openVariableAddresses, new long[]{newVariable.getMemoryAddress()});
        maxVariableAddresses = Longs.concat(maxVariableAddresses, new long[]{newVariable.getMaxMemoryAddress()});
      }
      rollbackable.commit();
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
 
Example 21
Project: dremio-oss   File: LBlockHashTableNoSpill.java    License: Apache License 2.0 5 votes vote down vote up
private void addDataBlocks(){

    // make sure can fit the next batch.
    listener.resized(currentOrdinal + MAX_VALUES_PER_BATCH);

    try(RollbackCloseable rollbackable = new RollbackCloseable()) {

      {
        FixedBlockVector newFixed = new FixedBlockVector(allocator, pivot.getBlockWidth());
        rollbackable.add(newFixed);
        newFixed.ensureAvailableBlocks(MAX_VALUES_PER_BATCH);
        fixedBlocks = ObjectArrays.concat(fixedBlocks, newFixed);
        tableFixedAddresses = Longs.concat(tableFixedAddresses, new long[]{newFixed.getMemoryAddress()});
      }

      {
        VariableBlockVector newVariable = new VariableBlockVector(allocator, pivot.getVariableCount());
        rollbackable.add(newVariable);
        newVariable.ensureAvailableDataSpace(pivot.getVariableCount() == 0 ? 0 : MAX_VALUES_PER_BATCH * defaultVariableLengthSize);
        variableBlocks = ObjectArrays.concat(variableBlocks, newVariable);
        initVariableAddresses = Longs.concat(initVariableAddresses, new long[]{newVariable.getMemoryAddress()});
        openVariableAddresses = Longs.concat(openVariableAddresses, new long[]{newVariable.getMemoryAddress()});
        maxVariableAddresses = Longs.concat(maxVariableAddresses, new long[]{newVariable.getMaxMemoryAddress()});
      }
      rollbackable.commit();
    } catch (Exception e) {
      throw Throwables.propagate(e);
    }
  }
 
Example 22
Project: science-journal   File: SimpleBackupAgent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
  Context context = getApplicationContext();
  String defaultPrefsName = getDefaultSharedPreferencesName(context);
  String[] accountsPrefsNames = AccountsUtils.getSharedPreferencesNamesForAllAccounts(context);
  SharedPreferencesBackupHelper helper =
      new SharedPreferencesBackupHelper(
          this, ObjectArrays.concat(defaultPrefsName, accountsPrefsNames));
  addHelper(PREFS_BACKUP_KEY, helper);
}
 
Example 23
Project: buck   File: BuildCommandIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private String[] getCommandArgsForShowOutputOrShowOutputs(
    String showOutputCommand, String... args) {
  if (useShowOutputs) {
    return ObjectArrays.concat(
        SHOW_OUTPUT_TO_SHOW_OUTPUTS.get(showOutputCommand), args, String.class);
  }
  return ObjectArrays.concat(showOutputCommand, args);
}
 
Example 24
Project: runelite   File: FriendNotesPlugin.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Subscribe
public void onMenuEntryAdded(MenuEntryAdded event)
{
	final int groupId = WidgetInfo.TO_GROUP(event.getActionParam1());

	// Look for "Message" on friends list
	if ((groupId == WidgetInfo.FRIENDS_LIST.getGroupId() && event.getOption().equals("Message")) ||
			(groupId == WidgetInfo.IGNORE_LIST.getGroupId() && event.getOption().equals("Delete")))
	{
		// Friends have color tags
		setHoveredFriend(Text.toJagexName(Text.removeTags(event.getTarget())));

		// Build "Add Note" or "Edit Note" menu entry
		final MenuEntry addNote = new MenuEntry();
		addNote.setOption(hoveredFriend == null || hoveredFriend.getNote() == null ? ADD_NOTE : EDIT_NOTE);
		addNote.setType(MenuAction.RUNELITE.getId());
		addNote.setTarget(event.getTarget()); //Preserve color codes here
		addNote.setParam0(event.getActionParam0());
		addNote.setParam1(event.getActionParam1());

		// Add menu entry
		final MenuEntry[] menuEntries = ObjectArrays.concat(client.getMenuEntries(), addNote);
		client.setMenuEntries(menuEntries);
	}
	else if (hoveredFriend != null)
	{
		hoveredFriend = null;
	}
}
 
Example 25
Project: levelup-java-examples   File: CombineTwoArrays.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void join_two_object_arrays_in_java_with_guava() {

	String[] allStateCapitals = ObjectArrays.concat(firstHalfStateCapital,
			secondHalfStateCapital, String.class);

	assertTrue(allStateCapitals.length == 50);
}
 
Example 26
Project: runelite   File: WorldHopperPlugin.java    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void insertMenuEntry(MenuEntry newEntry, MenuEntry[] entries, boolean after)
{
	MenuEntry[] newMenu = ObjectArrays.concat(entries, newEntry);

	if (after)
	{
		int menuEntryCount = newMenu.length;
		ArrayUtils.swap(newMenu, menuEntryCount - 1, menuEntryCount - 2);
	}

	client.setMenuEntries(newMenu);
}
 
Example 27
Project: Dream-Catcher   File: TrustSource.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a new TrustSource containing the same trusted CAs as this TrustSource, plus zero or more additional
 * trusted X509Certificates. If trustedCertificates is null or empty, returns this same TrustSource.
 *
 * @param trustedCertificates X509Certificates of CAs to trust
 * @return a new TrustSource containing this TrustSource's trusted CAs plus the specified CAs
 */
public TrustSource add(X509Certificate... trustedCertificates) {
    if (trustedCertificates == null || trustedCertificates.length == 0) {
        return this;
    }

    X509Certificate[] newTrustedCAs = ObjectArrays.concat(trustedCAs, trustedCertificates, X509Certificate.class);

    return new TrustSource(newTrustedCAs);
}
 
Example 28
Project: envelope   File: RowUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Row append(Row row, String fieldName, DataType fieldType, boolean nullable, Object value) {
  StructType appendedSchema = row.schema().add(fieldName, fieldType, nullable);
  Object[] appendedValues = ObjectArrays.concat(valuesFor(row), value);
  Row appendedRow = new RowWithSchema(appendedSchema, appendedValues);

  return appendedRow;
}
 
Example 29
Project: immutables   File: Proto.java    License: Apache License 2.0 5 votes vote down vote up
static @Nullable String[] concat(@Nullable String[] first, @Nullable String[] second) {
  if (first == null)
    return second;
  if (second == null)
    return first;
  return ObjectArrays.concat(first, second, String.class);
}
 
Example 30
Project: cuba   File: BaseEntityInternalAccess.java    License: Apache License 2.0 5 votes vote down vote up
public static void addRequiredAttributes(SecurityState state, String[] requiredAttributes) {
    if (state.requiredAttributes == null) {
        state.requiredAttributes = requiredAttributes;
    } else {
        state.requiredAttributes =
                ObjectArrays.concat(state.requiredAttributes, requiredAttributes, String.class);
    }
}
 
Example 31
Project: cuba   File: BaseEntityInternalAccess.java    License: Apache License 2.0 5 votes vote down vote up
public static void addHiddenAttributes(SecurityState state, String[] hiddenAttributes) {
    if (state.hiddenAttributes == null) {
        state.hiddenAttributes = hiddenAttributes;
    } else {
        state.hiddenAttributes =
                ObjectArrays.concat(state.hiddenAttributes, hiddenAttributes, String.class);
    }
}
 
Example 32
Project: xtext-core   File: GrammarElementsInterner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
EObject[] prependedGrammarElements() {
	if(grammarElements instanceof EObject) {
		return new EObject[] {grammarElement, (EObject) grammarElements};
	} else {
		return ObjectArrays.concat(grammarElement, (EObject[]) grammarElements);
	}
}
 
Example 33
Project: xtext-core   File: GrammarElementsInterner.java    License: Eclipse Public License 2.0 5 votes vote down vote up
EObject[] appendedGrammarElements() {
	if(grammarElements instanceof EObject) {
		return new EObject[] {(EObject) grammarElements, grammarElement };
	} else {
		return ObjectArrays.concat((EObject[]) grammarElements, grammarElement);
	}
}
 
Example 34
Project: AndroidHttpCapture   File: TrustSource.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a new TrustSource containing the same trusted CAs as this TrustSource, plus zero or more additional
 * trusted X509Certificates. If trustedCertificates is null or empty, returns this same TrustSource.
 *
 * @param trustedCertificates X509Certificates of CAs to trust
 * @return a new TrustSource containing this TrustSource's trusted CAs plus the specified CAs
 */
public TrustSource add(X509Certificate... trustedCertificates) {
    if (trustedCertificates == null || trustedCertificates.length == 0) {
        return this;
    }

    X509Certificate[] newTrustedCAs = ObjectArrays.concat(trustedCAs, trustedCertificates, X509Certificate.class);

    return new TrustSource(newTrustedCAs);
}
 
Example 35
Project: riptide   File: RequestUriTest.java    License: MIT License 5 votes vote down vote up
static List<Arguments> data() {
    final Set<Arguments> methods = allOf(HttpMethod.class).stream()
            .map(Arguments::of)
            .collect(toSet());

    return Sets.cartesianProduct(getCases(), methods).stream()
            .map(arguments -> arguments.stream().map(Arguments::get)
                    .reduce((l, r) -> ObjectArrays.concat(l, r, Object.class))
                    .map(Arguments::of)
                    .orElseThrow(IllegalArgumentException::new))
            .collect(toList());
}
 
Example 36
Project: levelup-java-examples   File: InitializeArray.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void initialize_string_array_java_with_guava_reference_type () {

	String[] nflStadiums = {""};

	String[] nflNorthStadiums = ObjectArrays.newArray(nflStadiums, 4);
	
	nflNorthStadiums[0] = "Lambeau Field";
       nflNorthStadiums[1] = "Soldier Field";
       nflNorthStadiums[2] = "Mall of America Fielddagger";
       nflNorthStadiums[3] = "Ford Fielddagger";
       
       assertEquals(4, nflNorthStadiums.length);
}
 
Example 37
Project: scheduling   File: AbstractIModeCommand.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute(ApplicationContext currentContext) throws CLIException {
    CommandFactory commandFactory = CommandFactory.getCommandFactory(CommandFactory.Type.ALL);
    AbstractDevice console = null;
    try {
        // force the console to JLine to provide commands completion and suggestions
        console = AbstractDevice.getConsole(AbstractDevice.JLINE);
        ((JLineDevice) console).setCommands(ObjectArrays.concat(commandFactory.supportedCommandEntries(),
                                                                CommandSet.INTERACTIVE_COMMANDS,
                                                                CommandSet.Entry.class));
    } catch (IOException e) {
        handleError("An error occurred while initializing the console:", e, currentContext);
    }
    currentContext.setDevice(console);
    currentContext.setProperty(IMODE, true);
    ScriptEngine engine = currentContext.getEngine();
    try {
        // load supported functions
        engine.eval(new InputStreamReader(script()));
    } catch (ScriptException error) {
        throw new CLIException(CLIException.REASON_OTHER, error);
    }

    while (!currentContext.getProperty(TERMINATE, Boolean.TYPE, false)) {
        try {
            String command = readLine(currentContext, "> ");
            if (command == null) {
                break; // EOF, exit interactive shell
            }
            engine.eval(command);
        } catch (ScriptException se) {
            handleError("An error occurred while executing the script:", se, currentContext);
        }
    }
}
 
Example 38
Project: google-java-format   File: PartialFormattingTest.java    License: Apache License 2.0 5 votes vote down vote up
private String formatMain(String input, String... args) throws Exception {
  Path tmpdir = testFolder.newFolder().toPath();
  Path path = tmpdir.resolve("Test.java");
  Files.write(path, input.getBytes(StandardCharsets.UTF_8));

  StringWriter out = new StringWriter();
  StringWriter err = new StringWriter();

  Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in);
  assertThat(main.format(ObjectArrays.concat(args, path.toString()))).isEqualTo(0);
  return out.toString();
}
 
Example 39
Project: google-java-format   File: PartialFormattingTest.java    License: Apache License 2.0 5 votes vote down vote up
private String runFormatter(String input, String[] args) throws IOException, UsageException {
  Path tmpdir = testFolder.newFolder().toPath();
  Path path = tmpdir.resolve("Foo.java");
  Files.write(path, input.getBytes(StandardCharsets.UTF_8));

  StringWriter out = new StringWriter();
  StringWriter err = new StringWriter();

  Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), System.in);
  assertThat(main.format(ObjectArrays.concat(args, path.toString()))).isEqualTo(0);
  return out.toString();
}
 
Example 40
Project: Mixin   File: RedirectInjector.java    License: MIT License 5 votes vote down vote up
RedirectedInvokeData(Target target, MethodInsnNode node) {
    super(target);
    this.node = node;
    this.returnType = Type.getReturnType(node.desc);
    this.targetArgs = Type.getArgumentTypes(node.desc);
    this.handlerArgs = node.getOpcode() == Opcodes.INVOKESTATIC
            ? this.targetArgs
            : ObjectArrays.concat(Type.getObjectType(node.owner), this.targetArgs);
}