Java Code Examples for java.util.Arrays

The following are top voted examples for showing how to use java.util.Arrays. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hadoop   File: TestLinuxContainerExecutorWithMocks.java   View source code 7 votes vote down vote up
@Test
public void testContainerKill() throws IOException {
  String appSubmitter = "nobody";
  String cmd = String.valueOf(
      PrivilegedOperation.RunAsUserCommand.SIGNAL_CONTAINER.getValue());
  ContainerExecutor.Signal signal = ContainerExecutor.Signal.QUIT;
  String sigVal = String.valueOf(signal.getValue());

  Container container = mock(Container.class);
  ContainerId cId = mock(ContainerId.class);
  ContainerLaunchContext context = mock(ContainerLaunchContext.class);

  when(container.getContainerId()).thenReturn(cId);
  when(container.getLaunchContext()).thenReturn(context);

  mockExec.signalContainer(new ContainerSignalContext.Builder()
      .setContainer(container)
      .setUser(appSubmitter)
      .setPid("1000")
      .setSignal(signal)
      .build());
  assertEquals(Arrays.asList(YarnConfiguration.DEFAULT_NM_NONSECURE_MODE_LOCAL_USER,
      appSubmitter, cmd, "1000", sigVal),
      readMockParams());
}
 
Example 2
Project: patient-portal   File: LoggingAspect.java   View source code 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example 3
Project: AndroidMuseumBleManager   File: BluetoothUuidCompat.java   View source code 6 votes vote down vote up
/**
 * Returns true if there any common ParcelUuids in uuidA and uuidB.
 *
 * @param uuidA - List of ParcelUuids
 * @param uuidB - List of ParcelUuids
 */
public static boolean containsAnyUuid(ParcelUuid[] uuidA, ParcelUuid[] uuidB) {
    if (uuidA == null && uuidB == null) return true;

    if (uuidA == null) {
        return uuidB.length == 0;
    }

    if (uuidB == null) {
        return uuidA.length == 0;
    }

    HashSet<ParcelUuid> uuidSet = new HashSet<>(Arrays.asList(uuidA));
    for (ParcelUuid uuid : uuidB) {
        if (uuidSet.contains(uuid)) return true;
    }
    return false;
}
 
Example 4
Project: xcc   File: TLongHashSet.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
    boolean changed = false;
    Arrays.sort( array );
    long[] set = _set;
    byte[] states = _states;

    _autoCompactTemporaryDisable = true;
    for ( int i = set.length; i-- > 0; ) {
        if ( states[i] == FULL && ( Arrays.binarySearch( array, set[i] ) < 0) ) {
            removeAt( i );
            changed = true;
        }
    }
    _autoCompactTemporaryDisable = false;

    return changed;
}
 
Example 5
Project: jdk8u-jdk   File: LambdaFormBuffer.java   View source code 6 votes vote down vote up
/** Create a private, writable copy of names.
 *  Preserve the original copy, for reference.
 */
void startEdit() {
    assert(verifyArity());
    int oc = ownedCount();
    assert(!inTrans());  // no nested transactions
    flags |= F_TRANS;
    Name[] oldNames = names;
    Name[] ownBuffer = (oc == 2 ? originalNames : null);
    assert(ownBuffer != oldNames);
    if (ownBuffer != null && ownBuffer.length >= length) {
        names = copyNamesInto(ownBuffer);
    } else {
        // make a new buffer to hold the names
        final int SLOP = 2;
        names = Arrays.copyOf(oldNames, Math.max(length + SLOP, oldNames.length));
        if (oc < 2)  ++flags;
        assert(ownedCount() == oc + 1);
    }
    originalNames = oldNames;
    assert(originalNames != names);
    firstChange = length;
    assert(inTrans());
}
 
Example 6
Project: dockerunit   File: VolumeExtensionInterpreter.java   View source code 6 votes vote down vote up
@Override
public CreateContainerCmd build(TestDescriptor td, CreateContainerCmd cmd, Volume v) {
	Bind[] binds = cmd.getBinds();
	
	String hostPath = v.useClasspath() 
			? Thread.currentThread().getContextClassLoader()
					.getResource(v.host()).getPath()
			: v.host();
	
	Bind bind = new Bind(hostPath, 
			new com.github.dockerjava.api.model.Volume(v.container()), 
			AccessMode.fromBoolean(v.accessMode().equals(Volume.AccessMode.RW)));
	
	List<Bind> bindsList = new ArrayList<>();
	if(binds != null) {
		bindsList.addAll(Arrays.asList(binds));
	} 
	bindsList.add(bind);  	
    return cmd.withBinds(bindsList);
}
 
Example 7
Project: cerebro   File: NotificationHandlerTest.java   View source code 6 votes vote down vote up
@Test
public void sendAlarmOnlyOnMailSubscriptionTarget() {
    Alarm alarm = TestUtils.getDefaultAlarm();
    Subscription s1 = TestUtils.getDefaultSubscription();
    Subscription s2 = TestUtils.getDefaultSubscription();
    s2.setTarget("/dev/null");
    s2.setType(SubscriptionType.SHELL);

    alarm.setSubscriptions(Arrays.asList(s1, s2));

    Map<String, String> model = new HashMap<>();
    model.put("status", "disabled");
    model.put("alert", alarm.getName());
    model.put("link", dashboardTestBaseUrl + "/notifications/" + alarm.getId());

    List<String> recipients = Collections.singletonList(s1.getTarget());

    notificationHandler.sendAlarmHasBeenDeactivated(alarm);

    verify(senderMock).send("One of your alerts has been disabled",notificationHandler.processTemplate("checkModified.vm", model),recipients);
}
 
Example 8
Project: cci   File: RotateMatrixAbstractTest.java   View source code 6 votes vote down vote up
@Test
public void rotate4() throws Exception {
    int[][] input = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
    };

    int[][] expected = {
            {13, 9, 5, 1},
            {14, 10, 6, 2},
            {15, 11, 7, 3},
            {16, 12, 8, 4}
    };

    int[][] output = testInstance.rotate(input);

    assertTrue(Arrays.deepEquals(expected, output));
}
 
Example 9
Project: incubator-netbeans   File: InterceptorTest.java   View source code 6 votes vote down vote up
public void testRenameFileChangeCase_DO () throws Exception {
    // prepare
    File fromFile = createFile("file");
    File toFile = new File(getWorkTreeDir(), "FILE");
    commit(fromFile);
    
    // move
    renameDO(fromFile, toFile.getName());
    
    // test
    if (Utilities.isWindows() || Utilities.isMac()) {
        assertTrue(Arrays.asList(toFile.getParentFile().list()).contains(toFile.getName()));
        assertFalse(Arrays.asList(fromFile.getParentFile().list()).contains(fromFile.getName()));
    } else {
        assertFalse(fromFile.exists());
        assertTrue(toFile.exists());
        assertEquals(FileInformation.STATUS_VERSIONED_REMOVEDLOCALLY, getCache().refresh(fromFile).getStatus());
        assertEquals(FileInformation.STATUS_VERSIONED_ADDEDLOCALLY, getCache().refresh(toFile).getStatus());
    }
}
 
Example 10
Project: incubator-netbeans   File: WorkingCopyDetails.java   View source code 6 votes vote down vote up
public boolean propertiesModified() throws IOException {        
    Map<String, byte[]> baseProps = getBaseSvnProperties();
    Map<String, byte[]> props = getWorkingSvnProperties();
    if ((baseProps == null) && (props != null)) {
        return true;
    }
    if ((baseProps != null) && (props == null)) {
        return true;
    }
    if ((baseProps == null) && (props == null)) {
        return false;
    }        
    if(baseProps.size() != props.size()) {
        return true;
    }
    for(Map.Entry<String, byte[]> baseEntry : baseProps.entrySet()) {
        byte[] propsValue = props.get(baseEntry.getKey());            
        if(propsValue == null || !Arrays.equals(propsValue, baseEntry.getValue())) {
            return true;
        }                        
    }
    return false;
}
 
Example 11
Project: FlashLib   File: LocalShell.java   View source code 6 votes vote down vote up
@Override
public void newData(byte[] data) {
	tracker.updateData = false;
	if(data[0] == EXECUTE_START){
		String command = new String(data, 1, data.length - 1);
		
		newCommand = command;
		newCommandReceived = true;
	}else if(data[0] == EXECUTE_STOP){
		stopExecution = true;
	}
	else if(data[0] == OUTPUT_STREAM_UPDATE){
		outputStreamData = Arrays.copyOfRange(data, 1, outputStreamData.length - 1);
		outputStreamUpdated = true;
	}
	tracker.updateData = true;
}
 
Example 12
Project: MinecraftServerSync   File: FTPSyncClient.java   View source code 6 votes vote down vote up
private boolean hasEqualMd5(Path localFile, byte[] md5) {
	try {
		Path relativeToBase = appConfig.getSyncPath().relativize(localFile);
		LOGGER.debug("Comparing MD5s for file '{}'...", localFile);
		byte[] localMd5 = computeMd5(localFile);
		if (Arrays.equals(md5, localMd5)) {
			LOGGER.debug("Equal MD5s, skipping upload/download.");
			return false;
		}
	} catch (IOException e) {
		LOGGER.debug("Error while computing MD5...");
		LogUtil.stacktrace(LOGGER, e);
	}
	LOGGER.debug("Differing MD5s, uploading/downloading...");
	return true;
}
 
Example 13
Project: incubator-netbeans   File: LibrariesNode.java   View source code 6 votes vote down vote up
/**
 * Creates new LibrariesNode named displayName displaying classPathProperty classpath
 * and optionaly Java platform.
 * @param displayName the display name of the node
 * @param eval {@link PropertyEvaluator} used for listening
 * @param helper {@link UpdateHelper} used for reading and updating project's metadata
 * @param refHelper {@link ReferenceHelper} used for destroying unused references
 * @param classPathProperty the ant property name of classpath which should be visualized
 * @param classPathIgnoreRef the array of ant property names which should not be displayed, may be
 * an empty array but not null
 * @param platformProperty the ant name property holding the Web platform system name or null
 * if the platform should not be displayed
 * @param librariesNodeActions actions which should be available on the created node.
 */
public LibrariesNode (String displayName, Project project, PropertyEvaluator eval, UpdateHelper helper, ReferenceHelper refHelper,
               String classPathProperty, String[] classPathIgnoreRef, String platformProperty,
               Action[] librariesNodeActions, String webModuleElementName, ClassPathSupport cs,
               Callback extraKeys) {
    this(
        displayName,
        project,
        eval,
        helper,
        refHelper,
        Collections.singletonList(classPathProperty),
        Arrays.asList(classPathIgnoreRef),
        platformProperty == null ?
            null :
            Pair.<Pair<String,String>,ClassPath>of(Pair.<String,String>of(platformProperty, null),null),
        null,
        Collections.emptySet(),
        librariesNodeActions,
        webModuleElementName,
        cs,
        extraKeys,
        null,
        null);
}
 
Example 14
Project: openjdk-jdk10   File: CipherCore.java   View source code 6 votes vote down vote up
/**
 * Continues a multiple-part encryption or decryption operation
 * (depending on how this cipher was initialized), processing another data
 * part.
 *
 * <p>The first <code>inputLen</code> bytes in the <code>input</code>
 * buffer, starting at <code>inputOffset</code>, are processed, and the
 * result is stored in a new buffer.
 *
 * @param input the input buffer
 * @param inputOffset the offset in <code>input</code> where the input
 * starts
 * @param inputLen the input length
 *
 * @return the new buffer with the result
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 */
byte[] update(byte[] input, int inputOffset, int inputLen) {
    if (requireReinit) {
        throw new IllegalStateException
            ("Must use either different key or iv for GCM encryption");
    }

    byte[] output = null;
    try {
        output = new byte[getOutputSizeByOperation(inputLen, false)];
        int len = update(input, inputOffset, inputLen, output,
                         0);
        if (len == output.length) {
            return output;
        } else {
            return Arrays.copyOf(output, len);
        }
    } catch (ShortBufferException e) {
        // should never happen
        throw new ProviderException("Unexpected exception", e);
    }
}
 
Example 15
Project: spring-cloud-performance-tuning   File: StockEntryRepositoryTest.java   View source code 6 votes vote down vote up
private Long persistStockEntries() {
    Stock stock = testEntityManager.persist(new Stock().setName("STOCK_NAME"));

    StockEntry[] entries = {
            buildStockEntry(stock, 1l, 1, 1.1),
            buildStockEntry(stock, 1l, 2, 1.2),
            buildStockEntry(stock, 2l, 3, 1.3),
            buildStockEntry(stock, 2l, 4, 1.4),
            buildStockEntry(stock, 3l, 0, 1.5),
            buildStockEntry(stock, 3l, 0, 1.6)
    };

    Arrays.stream(entries).forEach(testEntityManager::persist);

    return stock.getId();
}
 
Example 16
Project: sweiproject-tg2b-1   File: PasswordMatchesValidatorTest.java   View source code 6 votes vote down vote up
@Parameters(name = "\"{0}\", \"{1}\" => {2}")
public static Iterable<Object[]> generate() {

    final String maxX = Stream.of('x')
            .limit(Integer.MAX_VALUE)
            .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
            .toString();

    final String bar = "bar";

    final String foo = bar;


    return Arrays.asList(new Object[][]{
            {"", "", true},
            {" ", " ", true},
            {"", null, false},
            {"bla", "bla", true},
            {"x", "x", true},
            {maxX, maxX, true},
            {bar, bar, true},
            {foo, bar.substring(0, foo.length()), true},
            {bar, "bar", true},
            {foo, "bar", true}
    });
}
 
Example 17
Project: Hydrograph   File: UniqueSequenceEntity.java   View source code 6 votes vote down vote up
/**
 * Returns a string with the values for all the members of this entity
 * object.
 * <p>
 * Use cautiously as this is a very heavy operation.
 * 
 * @see hydrograph.engine.core.component.entity.base.AssemblyEntityBase#toString()
 */
@Override
public String toString() {

	StringBuilder str = new StringBuilder(
			"Unique sequence entity information\n");
	str.append(super.toString());

	if (isOperationPresent()) {
		str.append(getNumOperations()
				+ " operation(s) present, Operation info: ");
		if (getOperationsList() != null) {
			str.append(Arrays.toString(getOperationsList().toArray()));
		}
	} else {
		str.append("Operation not present\n");
	}

	str.append("\nOut socket(s): ");
	if (getOutSocketList() != null) {
		str.append(Arrays.toString(getOutSocketList().toArray()));
	}
	return str.toString();
}
 
Example 18
Project: pac4j-async   File: DefaultAsyncMatchingChecker.java   View source code 6 votes vote down vote up
@Override
public CompletableFuture<Boolean> matches(AsyncWebContext context, String matcherNames, Map<String, AsyncMatcher> matchersMap) {

    // if we have a matcher name (which may be a list of matchers names)
    if (CommonHelper.isNotBlank(matcherNames)) {

        // we must have matchers
        CommonHelper.assertNotNull("matchersMap", matchersMap);
        final String[] names = matcherNames.split(Pac4jConstants.ELEMENT_SEPRATOR);

        final List<AsyncMatcher> matchers = Arrays.stream(names)
                .map(n -> matchersMap.entrySet().stream()
                        .filter(e -> CommonHelper.areEqualsIgnoreCaseAndTrim(e.getKey(), n))
                        .peek(e -> CommonHelper.assertNotNull("matchersMap['" + n + "']", e))
                        .findFirst().map(e -> e.getValue()).orElse(null))
                .collect(Collectors.toList());

        return shortCircuitedFuture(matchers.stream()
                    .map(m -> () -> m.matches(context)), false);
    }

    return CompletableFuture.completedFuture(true);
}
 
Example 19
Project: elements-of-programming-interviews   File: NearestRepeatedTest.java   View source code 6 votes vote down vote up
@Test
public void findNearest3() throws Exception {
    list = Arrays.asList(
            "Mark",
            "Steve",
            "Mason",
            "Joan",
            "Jordan",
            "Dylan",
            "Robert",
            "Garth",
            "Mark",
            "Daisy",
            "Greg",
            "Marcus"
    );
    expected = 8;

    test(expected, list);
}
 
Example 20
Project: PixelDungeonTC   File: LastLevel.java   View source code 6 votes vote down vote up
@Override
protected boolean build() {

	Arrays.fill( map, Terrain.WALL );
	Painter.fill( this, 1, 1, SIZE, SIZE, Terrain.WATER );
	Painter.fill( this, 2, 2, SIZE-2, SIZE-2, Terrain.EMPTY );
	Painter.fill( this, SIZE/2, SIZE/2, 3, 3, Terrain.EMPTY_SP );
	
	entrance = SIZE * WIDTH + SIZE / 2 + 1;
	map[entrance] = Terrain.ENTRANCE;
	
	exit = entrance - WIDTH * SIZE;
	map[exit] = Terrain.LOCKED_EXIT;
	
	pedestal = (SIZE / 2 + 1) * (WIDTH + 1);
	map[pedestal] = Terrain.PEDESTAL;
	map[pedestal-1] = map[pedestal+1] = Terrain.STATUE_SP;
	
	feeling = Feeling.NONE;
	
	return true;
}
 
Example 21
Project: webDemo   File: WebLogAspect.java   View source code 5 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    logger.debug("***************请求开始***************");
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    CommLogger commLogger = new CommLogger();
    commLogger.setActionUrlAll(request.getRequestURL().toString());
    commLogger.setActionUrlTail(request.getServletPath());
    commLogger.setRequestParams(JSON.toJSONString(request.getParameterMap()));
    commLogger.setIp(IPUtil.getRealIP(request));
    commLogger.setReqStartTime(new Date());
    commLoggerThreadLocal.set(commLogger);

    // 记录下请求内容
    logger.debug("URL : " + request.getRequestURL().toString());
    logger.debug("HTTP_METHOD : " + request.getMethod());
    logger.debug("IP : " + IPUtil.getRealIP(request));
    logger.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    logger.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    logger.debug("params : " + JSON.toJSONString(request.getParameterMap()));

}
 
Example 22
Project: MaxSim   File: InputGraphTest.java   View source code 5 votes vote down vote up
/**
 * Test of findAllIngoingEdges method, of class InputGraph.
 */
@Test
public void testFindAllIngoingEdges() {
    assertTrue(emptyGraph.findAllIngoingEdges().isEmpty());

    Map<InputNode, List<InputEdge>> result = referenceGraph.findAllIngoingEdges();
    assertTrue(result.size() == 5);
    assertEquals(result.get(N1), Arrays.asList());
    assertEquals(result.get(N2), Arrays.asList(E12));
    assertEquals(result.get(N3), Arrays.asList(E13));
    assertEquals(result.get(N4), Arrays.asList(E24, E34, E54));
    assertEquals(result.get(N5), Arrays.asList());
}
 
Example 23
Project: openrouteservice   File: HeavyVehicleGraphStorageBuilder.java   View source code 5 votes vote down vote up
public HeavyVehicleGraphStorageBuilder()
{
	_motorVehicleRestrictions.addAll(Arrays.asList("motorcar", "motor_vehicle", "vehicle", "access"));

	_motorVehicleRestrictedValues.add("private");
	_motorVehicleRestrictedValues.add("no");
	_motorVehicleRestrictedValues.add("restricted");
	_motorVehicleRestrictedValues.add("military");
	
	_patternHeight = Pattern.compile("(?:\\s*(\\d+)\\s*(?:feet|ft\\.|ft|'))?(?:(\\d+)\\s*(?:inches|in\\.|in|''|\"))?");
}
 
Example 24
Project: majx   File: LocationTests.java   View source code 5 votes vote down vote up
@Parameterized.Parameters(name = "{index}: {0}")
public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][]{
            {
                    "deep mixed location",
                    "location/deepMixed/actual.json",
                    "location/deepMixed/pattern.json",
                    "$.obj1.array1[1].array2[0][0].expected"

            }
    });
}
 
Example 25
Project: advent-of-code-2017   File: Bank.java   View source code 5 votes vote down vote up
@Override
public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + Arrays.hashCode(blocks);
	return result;
}
 
Example 26
Project: mcc   File: SimpleCompilerTest.java   View source code 5 votes vote down vote up
@Test
public void testLoadClasspath() throws IOException {
    String path = Paths.get(new File(".").getCanonicalPath(), "src", "test", "resources", "gson-2.2.4.jar").toString();
    SourceClass sourceClass = new SourceClass("teste", "Teste", "package teste; import com.google.gson.Gson; public class Teste {}");
    MemoryClassCompiler compiler = new MemoryClassCompiler(Arrays.asList(path));
    try {
        compiler.compile(sourceClass);
    } catch (Exception ex) {
        Assert.assertFalse(true);
    }
}
 
Example 27
Project: ditb   File: MDIndex.java   View source code 5 votes vote down vote up
/**
 * @param dropIfExists
 */
public void createTable(boolean dropIfExists) throws IOException {
  if (admin.tableExists(secondaryTableName)) {
    if (dropIfExists) {
      admin.disableTable(bucketTableName);
      admin.deleteTable(bucketTableName);
      admin.disableTable(secondaryTableName);
      admin.deleteTable(secondaryTableName);
    } else {
      secondaryTable = conn.getTable(secondaryTableName);
      bucketTable = conn.getTable(bucketTableName);
      return;
    }
  }
  // secondary table
  HTableDescriptor secondaryDesc = new HTableDescriptor(secondaryTableName);
  secondaryDesc
      .addFamily(IndexTableRelation.getDefaultColumnDescriptor(MDHBaseAdmin.SECONDARY_FAMILY));
  admin.createTable(secondaryDesc);
  secondaryTable = conn.getTable(secondaryTableName);
  // bucket table
  HTableDescriptor bucketDesc = new HTableDescriptor(bucketTableName);
  bucketDesc.addFamily(IndexTableRelation.getDefaultColumnDescriptor(MDHBaseAdmin.BUCKET_FAMILY));
  admin.createTable(bucketDesc);
  bucketTable = conn.getTable(bucketTableName);
  // init when init
  int[] starts = new int[dimensions];
  Arrays.fill(starts, 0);
  Put put = new Put(MDUtils.bitwiseZip(starts, dimensions));
  put.addColumn(MDHBaseAdmin.BUCKET_FAMILY, MDHBaseAdmin.BUCKET_PREFIX_LEN_QUALIFIER,
      Bytes.toBytes(dimensions));
  put.addColumn(MDHBaseAdmin.BUCKET_FAMILY, MDHBaseAdmin.BUCKET_SIZE_QUALIFIER,
      Bytes.toBytes(0L));
  bucketTable.put(put);
}
 
Example 28
Project: elasticsearch_my   File: ReindexPlugin.java   View source code 5 votes vote down vote up
@Override
public List<RestHandler> getRestHandlers(Settings settings, RestController restController, ClusterSettings clusterSettings,
        IndexScopedSettings indexScopedSettings, SettingsFilter settingsFilter, IndexNameExpressionResolver indexNameExpressionResolver,
        Supplier<DiscoveryNodes> nodesInCluster) {
    return Arrays.asList(
            new RestReindexAction(settings, restController),
            new RestUpdateByQueryAction(settings, restController),
            new RestDeleteByQueryAction(settings, restController),
            new RestRethrottleAction(settings, restController, nodesInCluster));
}
 
Example 29
Project: syndesis   File: ConnectionActionHandlerTest.java   View source code 5 votes vote down vote up
@Test
public void shouldElicitActionPropertySuggestions() {
    @SuppressWarnings({"unchecked", "rawtypes"})
    final Class<Entity<Map<String, Object>>> entityType = (Class) Entity.class;
    final ArgumentCaptor<Entity<Map<String, Object>>> entity = ArgumentCaptor.forClass(entityType);

    final DynamicActionMetadata suggestions = new DynamicActionMetadata.Builder()
        .putProperty("sObjectName",
            Collections
                .singletonList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Contact", "Contact")))
        .putProperty("sObjectIdName",
            Arrays.asList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("ID", "Contact ID"),
                DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Email", "Email"),
                DynamicActionMetadata.ActionPropertySuggestion.Builder.of("TwitterScreenName__c",
                    "Twitter Screen Name")))
        .build();
    when(invocationBuilder.post(entity.capture(), eq(DynamicActionMetadata.class))).thenReturn(suggestions);

    final ConnectorDescriptor enrichedDefinitioin = new ConnectorDescriptor.Builder()
        .createFrom(createOrUpdateSalesforceObjectDescriptor)
        .replaceConfigurationProperty("sObjectName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Contact", "Contact")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("ID", "Contact ID")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Email", "Email")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(
                ConfigurationProperty.PropertyValue.Builder.of("TwitterScreenName__c", "Twitter Screen Name")))
        .build();

    final Map<String, String> parameters = new HashMap<>();
    parameters.put("sObjectName", "Contact");

    assertThat(handler.enrichWithMetadata(SALESFORCE_CREATE_OR_UPDATE, parameters)).isEqualTo(enrichedDefinitioin);

    assertThat(entity.getValue().getEntity()).contains(entry("clientId", "some-clientId"),
        entry("sObjectIdName", null), entry("sObjectName", "Contact"));
}
 
Example 30
Project: Higher-Cloud-Computing-Project   File: AbstractVector.java   View source code 5 votes vote down vote up
/** {@inheritDoc} */
@Override public Vector sort() {
    if (isArrayBased())
        Arrays.parallelSort(sto.data());
    else
        throw new UnsupportedOperationException();

    return this;
}
 
Example 31
Project: uavstack   File: DataConvertHelper.java   View source code 5 votes vote down vote up
/**
 * String to List<String>
 * 
 * @param str
 * @param seperator
 * @return
 */
public static List<String> toList(String str, String seperator) {

    if (StringHelper.isEmpty(str)) {
        return Collections.emptyList();
    }

    String[] strs = str.split(seperator);

    return Arrays.asList(strs);
}
 
Example 32
Project: monarch   File: CacheXml66DUnitTest.java   View source code 5 votes vote down vote up
/**
 * Tests multiple transaction listeners
 * 
 * @since GemFire 5.0
 */
@Test
public void testMultipleTXListener() throws CacheException {
  CacheCreation cache = new CacheCreation();
  CacheTransactionManagerCreation txMgrCreation = new CacheTransactionManagerCreation();
  TransactionListener l1 = new MyTestTransactionListener();
  TransactionListener l2 = new MySecondTestTransactionListener();
  txMgrCreation.addListener(l1);
  txMgrCreation.addListener(l2);
  cache.addCacheTransactionManagerCreation(txMgrCreation);
  testXml(cache);
  {
    CacheTransactionManager tm = getCache().getCacheTransactionManager();
    assertEquals(Arrays.asList(new TransactionListener[] {l1, l2}),
        Arrays.asList(tm.getListeners()));
    tm.removeListener(l2);
    assertEquals(Arrays.asList(new TransactionListener[] {l1}), Arrays.asList(tm.getListeners()));
    tm.removeListener(l1);
    assertEquals(Arrays.asList(new TransactionListener[] {}), Arrays.asList(tm.getListeners()));
    tm.addListener(l1);
    assertEquals(Arrays.asList(new TransactionListener[] {l1}), Arrays.asList(tm.getListeners()));
    tm.addListener(l1);
    assertEquals(Arrays.asList(new TransactionListener[] {l1}), Arrays.asList(tm.getListeners()));
    tm.addListener(l2);
    assertEquals(Arrays.asList(new TransactionListener[] {l1, l2}),
        Arrays.asList(tm.getListeners()));
    tm.removeListener(l1);
    assertEquals(Arrays.asList(new TransactionListener[] {l2}), Arrays.asList(tm.getListeners()));
    tm.removeListener(l1);
    assertEquals(Arrays.asList(new TransactionListener[] {l2}), Arrays.asList(tm.getListeners()));
    tm.initListeners(new TransactionListener[] {l1, l2});
    assertEquals(Arrays.asList(new TransactionListener[] {l1, l2}),
        Arrays.asList(tm.getListeners()));
  }
}
 
Example 33
Project: MobiRNN-EMDL17   File: MatrixTest.java   View source code 5 votes vote down vote up
@Test
public void addVec() throws Exception {
    float[][] a = {{1, 2, 3}, {4, 5, 6}};
    float[] b = {7, 8, 9};
    float[][] c = {{8, 10, 12}, {11, 13, 15}};
    assertTrue(Arrays.deepEquals(Matrix.addVec(a, b), c));
}
 
Example 34
Project: oscm   File: IdentityServiceWSTest.java   View source code 5 votes vote down vote up
@Test(expected = UserActiveException.class)
public void requestResetOfUserPassword_ActiveSession() throws Exception {
    WebserviceTestBase.getMailReader().deleteMails();
    // create another user
    VOUserDetails u = createUniqueUser();
    is.createUser(u, Arrays.asList(UserRoleType.SERVICE_MANAGER), null);
    // read key and reset password
    String userKey = WebserviceTestBase.readLastMailAndSetCommonPassword();
    // get session service ...
    SessionService ss = ServiceFactory.getDefault().getSessionService(
            userKey, WebserviceTestBase.DEFAULT_PASSWORD);
    String sessionId = String.valueOf(System.currentTimeMillis());
    // ... and create a session for the new user
    ss.createPlatformSession(sessionId);
    u = is.getUserDetails(u);
    assertEquals(UserAccountStatus.ACTIVE, u.getStatus());
    try {
        is.requestResetOfUserPassword(u, null);
    } catch (UserActiveException e) {
        validateException(u.getUserId(), e);
        u = is.getUserDetails(u);
        assertEquals(UserAccountStatus.ACTIVE, u.getStatus());
        throw e;
    } finally {
        ss.deletePlatformSession(sessionId);
        is.deleteUser(u, null);
    }
}
 
Example 35
Project: GitHub   File: HpackTest.java   View source code 5 votes vote down vote up
@Test public void noDynamicTableSizeUpdateWhenSizeIsEqual() throws IOException {
  int currentSize = hpackWriter.headerTableSizeSetting;
  hpackWriter.setHeaderTableSizeSetting(currentSize);
  hpackWriter.writeHeaders(Arrays.asList(new Header("foo", "bar")));

  assertBytes(0x40, 3, 'f', 'o', 'o', 3, 'b', 'a', 'r');
}
 
Example 36
Project: Reer   File: InProcessGradleExecuter.java   View source code 5 votes vote down vote up
public ExecutionResult assertTasksNotSkipped(String... taskPaths) {
    if (GradleContextualExecuter.isParallel()) {
        return this;
    }
    Set<String> expected = new HashSet<String>(Arrays.asList(taskPaths));
    Set<String> notSkipped = getNotSkippedTasks();
    assertThat(notSkipped, equalTo(expected));
    outputResult.assertTasksNotSkipped(taskPaths);
    return this;
}
 
Example 37
Project: jpromise   File: Promise.java   View source code 5 votes vote down vote up
public static Promise all(List<Promise> promises) {
    return new Promise((resolve, reject) -> {
        final int size = promises.size();
        AtomicInteger remaining = new AtomicInteger(size);
        AtomicReference error = new AtomicReference();
        Object[] result = new Object[size];

        for (int i = 0; i < size; i++) {
            final int index = i;
            promises.get(i).then(value -> {
                if (error.get() != null) {
                    return value;
                }
                result[index] = value;
                if (remaining.decrementAndGet() == 0) {
                    resolve.apply(Arrays.asList(result));
                }
                return value;
            }).fail(err -> {
                if (error.get() == null) {
                    error.set(err);
                    reject.apply(error.get());
                }
                return err;
            });
        }
    });
}
 
Example 38
Project: airgram   File: AudioCapabilities.java   View source code 5 votes vote down vote up
@Override
public boolean equals(Object other) {
  if (this == other) {
    return true;
  }
  if (!(other instanceof AudioCapabilities)) {
    return false;
  }
  AudioCapabilities audioCapabilities = (AudioCapabilities) other;
  return Arrays.equals(supportedEncodings, audioCapabilities.supportedEncodings)
      && maxChannelCount == audioCapabilities.maxChannelCount;
}
 
Example 39
Project: dagger-test-example   File: PermissionResult.java   View source code 5 votes vote down vote up
@Override
public boolean equals(Object o)
{
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    PermissionResult that = (PermissionResult) o;

    if (requestCode != that.requestCode) return false;
    // Probably incorrect - comparing Object[] arrays with Arrays.equals
    if (!Arrays.equals(permissions, that.permissions)) return false;
    return Arrays.equals(grantResults, that.grantResults);

}
 
Example 40
Project: oscm   File: ServiceInstanceTest.java   View source code 5 votes vote down vote up
@Test
public void testGetParameterForKey() {
    final InstanceParameter p = new InstanceParameter();
    p.setParameterKey("param1");
    p.setParameterValue("value1");
    instance.setInstanceParameters(Arrays.asList(p));
    assertEquals("value1", instance.getParameterForKey("param1")
            .getParameterValue());
}