org.mockito.internal.util.io.IOUtil Java Examples

The following examples show how to use org.mockito.internal.util.io.IOUtil. 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: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationFailsCorrectKeystorePasswdBlankKeypasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("'Key Password' validated against '' is invalid because Key Password cannot be empty")) {
            notificationServiceFailed = true;
        }
    }

    assertTrue(notificationServiceFailed);
}
 
Example #2
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationFailsBlankKeystorePasswdCorrectKeypasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_BLANK_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("'Keystore Password' validated against '' is invalid because Keystore Password cannot be empty")) {
            notificationServiceFailed = true;
        }
    }

    assertTrue(notificationServiceFailed);
}
 
Example #3
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationSucceedsNoKeyPasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEY_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
            notificationServiceFailed = true;
        }
    }

    assertFalse(notificationServiceFailed);
}
 
Example #4
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotificationSucceedsNoKeystorePasswd() throws ParserConfigurationException, SAXException, IOException {
    Logger notificationServiceLogger = (Logger) LoggerFactory.getLogger(NotificationServiceManager.class);
    ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
    listAppender.start();
    notificationServiceLogger.addAppender(listAppender);

    String configFileOutput = CONFIGURATION_FILE_TEXT_NO_KEYSTORE_PASSWORD.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));

    List<ILoggingEvent> logsList = listAppender.list;
    boolean notificationServiceFailed = false;
    for (ILoggingEvent logMessage : logsList) {
        if (logMessage.getFormattedMessage().contains("is not valid for the following reasons")) {
            notificationServiceFailed = true;
        }
    }

    assertFalse(notificationServiceFailed);
}
 
Example #5
Source File: TestHttpNotificationServiceSSL.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Before
public void startServer() throws IOException, TlsException {
    tempConfigFilePath = "./target/TestHttpNotificationService-config.xml";

    Files.deleteIfExists(Paths.get(tempConfigFilePath));

    mockWebServer = new MockWebServer();

    TlsConfiguration tlsConfiguration = new TlsConfiguration("./src/test/resources/keystore.jks", "passwordpassword", null, "JKS",
            "./src/test/resources/truststore.jks", "passwordpassword", "JKS", CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    final SSLContext sslContext = SslContextFactory.createSslContext(tlsConfiguration, SslContextFactory.ClientAuth.REQUIRED);
    mockWebServer.useHttps(sslContext.getSocketFactory(), false);

    String configFileOutput = CONFIGURATION_FILE_TEXT.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
}
 
Example #6
Source File: NetUtilTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void portDetect() throws UnknownHostException, IOException {
	int port = NetUtil.findRandomAvailablePort(20000, 20100);
	assertThat(port).isBetween(20000, 20100);
	System.out.println("random port:" + port);

	assertThat(NetUtil.isPortAvailable(port)).isTrue();

	int port2 = NetUtil.findAvailablePortFrom(port);
	assertThat(port2).isEqualTo(port);

	int port3 = NetUtil.findRandomAvailablePort();

	assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
	System.out.println("random port:" + port3);

	// 尝试占住一个端口
	ServerSocket serverSocket = null;
	try {
		serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
				InetAddress.getByName("localhost"));

		assertThat(NetUtil.isPortAvailable(port)).isFalse();

		int port4 = NetUtil.findAvailablePortFrom(port);
		assertThat(port4).isEqualTo(port + 1);

		try {
			int port5 = NetUtil.findRandomAvailablePort(port, port);
			fail("should fail before");
		} catch (Throwable t) {
			assertThat(t).isInstanceOf(IllegalStateException.class);
		}

	} finally {
		IOUtil.close(serverSocket);
	}

}
 
Example #7
Source File: TestHttpNotificationService.java    From nifi with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void startServer() throws IOException {
    tempConfigFilePath = "./target/TestHttpNotificationService-config.xml";

    Files.deleteIfExists(Paths.get(tempConfigFilePath));

    mockWebServer = new MockWebServer();

    String configFileOutput = CONFIGURATION_FILE_TEXT.replace("${test.server}", String.valueOf(mockWebServer.url("/")));
    IOUtil.writeText(configFileOutput, new File(tempConfigFilePath));
}
 
Example #8
Source File: GATKReadFilterPluginDescriptorTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void traverse() {
    String readFilters = getCommandLineParser()
            .getPluginDescriptor(GATKReadFilterPluginDescriptor.class)
            .getResolvedInstances()
            .stream()
            .map(a -> a.getClass().getSimpleName())
            .collect(Collectors.joining("\n"));
    IOUtil.writeText(readFilters, new File(output));
}
 
Example #9
Source File: GATKAnnotationPluginDescriptorUnitTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void traverse() {
    String annotations = makeVariantAnnotations().stream()
            .map(a -> a.getClass().getSimpleName())
            .collect(Collectors.joining("\n"));
    IOUtil.writeText(annotations, new File(output));
}
 
Example #10
Source File: AccessTokenBuilderTest.java    From tokens with Apache License 2.0 5 votes vote down vote up
@Before
public void createCredentials() throws IOException {
	File tempDir = tempFolder.newFolder();
	File clientJson = new File(tempDir, "client.json");
	IOUtil.writeText("{\"client_id\":\"abcdefg \",\"client_secret\":\"geheim\"}", clientJson);
	File userJson = new File(tempDir, "user.json");
	IOUtil.writeText("{\"application_username\":\"klaus \",\"application_password\":\"geheim\"}", userJson);
	System.setProperty(CREDENTIALS_DIR, tempDir.getAbsolutePath());
}
 
Example #11
Source File: MutationTool.java    From sstable-tools with Apache License 2.0 5 votes vote down vote up
public void run() {
    try {
        try {
            if (!cmd.hasOption(SILENT_OPTION)) {
                System.out.printf("%sLoading schema from %s:%s%s", ANSI_RED, host, port, ANSI_RESET);
                System.out.flush();
            }
            String cfids = cmd.getOptionValue(CFID_OPTION, "");
            cluster = CassandraUtils.loadTablesFromRemote(host, port, cfids);
        } finally {
            System.out.print(ANSI_RESET);
        }
            for (String target : cmd.getArgs()) {
                File targetFile = new File(target);
                if (!targetFile.exists()) {
                    if (!cmd.hasOption(SILENT_OPTION)) {
                        System.out.print("\r" + ANSI_RESET + Strings.repeat(" ", 60) + "\r");
                    }
                    System.err.println("Non-existant target provided: " + target);
                } else {
                    if (!cmd.hasOption(SILENT_OPTION)) {
                        System.out.print("\r" + ANSI_RESET + Strings.repeat(" ", 60) + "\r");
                        System.out.println("\u001B[1;34m" + targetFile.getAbsolutePath());
                        System.out.println(ANSI_CYAN + Strings.repeat("=", targetFile.getAbsolutePath().length()));
                        System.out.print(ANSI_RESET);
                    }
                    MutationReplayer replayer = null;
                    if (cmd.hasOption(REPLAY_OPTION)) {
                        replayer = new MutationReplayer(cluster);
                    }
                    walkMutations(targetFile, System.out, replayer);
                }
            }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtil.closeQuietly(cluster);
    }
}
 
Example #12
Source File: NetUtilTest.java    From vjtools with Apache License 2.0 5 votes vote down vote up
@Test
public void portDetect() throws UnknownHostException, IOException {
	int port = NetUtil.findRandomAvailablePort(20000, 20100);
	assertThat(port).isBetween(20000, 20100);
	System.out.println("random port:" + port);

	assertThat(NetUtil.isPortAvailable(port)).isTrue();

	int port2 = NetUtil.findAvailablePortFrom(port);
	assertThat(port2).isEqualTo(port);

	int port3 = NetUtil.findRandomAvailablePort();

	assertThat(port3).isBetween(NetUtil.PORT_RANGE_MIN, NetUtil.PORT_RANGE_MAX);
	System.out.println("random port:" + port3);

	// 尝试占住一个端口
	ServerSocket serverSocket = null;
	try {
		serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1,
				InetAddress.getByName("localhost"));

		assertThat(NetUtil.isPortAvailable(port)).isFalse();

		int port4 = NetUtil.findAvailablePortFrom(port);
		assertThat(port4).isEqualTo(port + 1);

		try {
			int port5 = NetUtil.findRandomAvailablePort(port, port);
			fail("should fail before");
		} catch (Throwable t) {
			assertThat(t).isInstanceOf(IllegalStateException.class);
		}

	} finally {
		IOUtil.close(serverSocket);
	}

}
 
Example #13
Source File: AccessTokenRefresherRunTest.java    From tokens with Apache License 2.0 4 votes vote down vote up
@Test
public void runAccessTokenRefresher() throws IOException, InterruptedException {
	File tempDir = tempFolder.newFolder();
	File clientJson = new File(tempDir, "client.json");
	IOUtil.writeText("{\"client_id\":\"abcdefg \",\"client_secret\":\"geheim\"}", clientJson);
	File userJson = new File(tempDir, "user.json");
	IOUtil.writeText("{\"application_username\":\"klaus \",\"application_password\":\"geheim\"}", userJson);
	System.setProperty(CREDENTIALS_DIR, tempDir.getAbsolutePath());

	ClientCredentialsProvider ccp = new JsonFileBackedClientCredentialsProvider(clientJson);
	UserCredentialsProvider ucp = new JsonFileBackedUserCredentialsProvider(userJson);
	HttpProviderFactory hpf = Mockito.mock(HttpProviderFactory.class);

	AccessTokensBuilder accessTokenBuilder = Tokens.createAccessTokensWithUri(uri)
	                                               .usingClientCredentialsProvider(ccp)
	                                               .usingUserCredentialsProvider(ucp)
	                                               .usingHttpProviderFactory(hpf)
	                                               .manageToken("TR_TEST")
	                                               .done()
	                                               .manageToken("TR_TEST_1")
	                                               .done()
	                                               .manageToken("TR_TEST_2")
                                                      .done();

	HttpProvider httpProvider = Mockito.mock(HttpProvider.class);

	Mockito.when(hpf.create(Mockito.any(ClientCredentials.class), Mockito.any(UserCredentials.class),
			Mockito.any(URI.class), Mockito.any(HttpConfig.class))).thenReturn(httpProvider);

	Mockito.when(httpProvider.createToken(Mockito.any(AccessTokenConfiguration.class)))
               .thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
               .thenThrow(new RuntimeException("DO NOT FAIL ALL CONFIGURATIONS"))
               .thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
               .thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)))
               .thenThrow(new RuntimeException("DO NOT FAIL ALL CONFIGURATIONS"))
               .thenReturn(new AccessToken("123456789", "BEARER", 2, new Date(System.currentTimeMillis() + 15000)));
	accessTokens = accessTokenBuilder.start();
	Assertions.assertThat(accessTokens).isNotNull();

	TimeUnit.SECONDS.sleep(30);

	Mockito.verify(httpProvider, Mockito.atLeastOnce()).createToken(Mockito.any(AccessTokenConfiguration.class));

}
 
Example #14
Source File: MockSimplePojoSerializer.java    From gridgo with MIT License 4 votes vote down vote up
@Override
public BElement deserialize(InputStream in) {
    return BReference.of(new SimplePojo(IOUtil.readLines(in).iterator().next()));
}
 
Example #15
Source File: MockRawSerializer.java    From gridgo with MIT License 4 votes vote down vote up
@Override
public BElement deserialize(InputStream in) {
    return BElement.ofAny(IOUtil.readLines(in).iterator().next());
}
 
Example #16
Source File: MockSimplePojoBObjectSerializer.java    From gridgo with MIT License 4 votes vote down vote up
@Override
public BElement deserialize(InputStream in) {
    return BObject.of("name", IOUtil.readLines(in).iterator().next());
}
 
Example #17
Source File: MockRawSerializer.java    From gridgo with MIT License 4 votes vote down vote up
@Override
public BElement deserialize(InputStream in) {
    return BElement.ofAny(IOUtil.readLines(in).iterator().next());
}