com.google.common.collect.ObjectArrays Java Examples

The following examples show how to use com.google.common.collect.ObjectArrays. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleTimeLimiter.java    From codebuff with 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 #2
Source File: SimpleTimeLimiter.java    From codebuff with 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 #3
Source File: AppPage.java    From teammates with 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 #4
Source File: SimpleTimeLimiter.java    From codebuff with 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
Source File: SimpleTimeLimiter.java    From codebuff with 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 #6
Source File: OptimizedFlywayTestExecutionListener.java    From embedded-database-spring-test with 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 #7
Source File: JarInferTest.java    From NullAway with 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 #8
Source File: AbstractProvider.java    From pnc with 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
Source File: SimpleBackupAgent.java    From science-journal with 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 #10
Source File: AbstractIModeCommand.java    From scheduling with 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 #11
Source File: Proto.java    From immutables with 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 #12
Source File: BaseEntityInternalAccess.java    From cuba with 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 #13
Source File: BaseEntityInternalAccess.java    From cuba with 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 #14
Source File: GrammarElementsInterner.java    From xtext-core with 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 #15
Source File: LBlockHashTableNoSpill.java    From dremio-oss with 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 #16
Source File: QBlockHashTable.java    From dremio-oss with 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 #17
Source File: GrammarElementsInterner.java    From xtext-core with 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 #18
Source File: SmtpSession.java    From NioSmtpClient with 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 #19
Source File: BaseSqoopTestCase.java    From aliyun-maxcompute-data-collectors with 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 #20
Source File: WorldHopperPlugin.java    From plugins with 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 #21
Source File: RowUtils.java    From envelope with 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 #22
Source File: BuildCommandIntegrationTest.java    From buck with 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 #23
Source File: FriendNotesPlugin.java    From runelite with 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 #24
Source File: CombineTwoArrays.java    From levelup-java-examples with 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 #25
Source File: WorldHopperPlugin.java    From runelite with 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 #26
Source File: TrustSource.java    From Dream-Catcher with 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 #27
Source File: ForgeConfigSpec.java    From patchwork-api with 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 #28
Source File: TrustSource.java    From browserup-proxy with 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 #29
Source File: RequestErrorTracker.java    From presto with 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 #30
Source File: PartialFormattingTest.java    From google-java-format with 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();
}