Search in sources :

Example 71 with SocketTimeoutException

use of java.net.SocketTimeoutException in project geode by apache.

the class PRClientServerRegionFunctionExecutionSingleHopDUnitTest method executeFunction.

public static void executeFunction() throws ServerException, InterruptedException {
    Region region = cache.getRegion(PartitionedRegionName);
    assertNotNull(region);
    final HashSet testKeysSet = new HashSet();
    for (int i = (totalNumBuckets.intValue() * 10); i > 0; i--) {
        testKeysSet.add("execKey-" + i);
    }
    DistributedSystem.setThreadsSocketPolicy(false);
    Function function = new TestFunction(true, TEST_FUNCTION2);
    FunctionService.registerFunction(function);
    Execution dataSet = FunctionService.onRegion(region);
    try {
        ResultCollector rc1 = dataSet.withFilter(testKeysSet).setArguments(Boolean.TRUE).execute(function.getId());
        HashMap resultMap = ((HashMap) rc1.getResult());
        assertEquals(3, resultMap.size());
        Iterator mapIterator = resultMap.entrySet().iterator();
        Map.Entry entry = null;
        ArrayList resultListForMember = null;
        while (mapIterator.hasNext()) {
            entry = (Map.Entry) mapIterator.next();
            resultListForMember = (ArrayList) entry.getValue();
            for (Object result : resultListForMember) {
                assertEquals(Boolean.TRUE, result);
            }
        }
    } catch (Exception e) {
        LogWriterUtils.getLogWriter().info("Got an exception : " + e.getMessage());
        assertTrue(e instanceof EOFException || e instanceof SocketException || e instanceof SocketTimeoutException || e instanceof ServerException || e instanceof IOException || e instanceof CacheClosedException);
    }
}
Also used : SocketException(java.net.SocketException) ServerException(java.rmi.ServerException) TestFunction(org.apache.geode.internal.cache.functions.TestFunction) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CacheClosedException(org.apache.geode.cache.CacheClosedException) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) ServerException(java.rmi.ServerException) FunctionException(org.apache.geode.cache.execute.FunctionException) SocketException(java.net.SocketException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SocketTimeoutException(java.net.SocketTimeoutException) DistributedSystemDisconnectedException(org.apache.geode.distributed.DistributedSystemDisconnectedException) IOException(java.io.IOException) EOFException(java.io.EOFException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) Function(org.apache.geode.cache.execute.Function) TestFunction(org.apache.geode.internal.cache.functions.TestFunction) Execution(org.apache.geode.cache.execute.Execution) SocketTimeoutException(java.net.SocketTimeoutException) Iterator(java.util.Iterator) EOFException(java.io.EOFException) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 72 with SocketTimeoutException

use of java.net.SocketTimeoutException in project geode by apache.

the class PRClientServerRegionFunctionExecutionSelectorNoSingleHopDUnitTest method executeFunction.

public static void executeFunction() throws ServerException, InterruptedException {
    Region region = cache.getRegion(PartitionedRegionName);
    assertNotNull(region);
    final HashSet testKeysSet = new HashSet();
    for (int i = (totalNumBuckets.intValue() * 10); i > 0; i--) {
        testKeysSet.add("execKey-" + i);
    }
    DistributedSystem.setThreadsSocketPolicy(false);
    Function function = new TestFunction(true, TEST_FUNCTION2);
    FunctionService.registerFunction(function);
    Execution dataSet = FunctionService.onRegion(region);
    try {
        ResultCollector rc1 = dataSet.withFilter(testKeysSet).setArguments(Boolean.TRUE).execute(function.getId());
        HashMap resultMap = ((HashMap) rc1.getResult());
        assertEquals(3, resultMap.size());
        Iterator mapIterator = resultMap.entrySet().iterator();
        Map.Entry entry = null;
        DistributedMember key = null;
        ArrayList resultListForMember = null;
        while (mapIterator.hasNext()) {
            entry = (Map.Entry) mapIterator.next();
            key = (DistributedMember) entry.getKey();
            resultListForMember = (ArrayList) entry.getValue();
            for (Object result : resultListForMember) {
                assertEquals(Boolean.TRUE, result);
            }
        }
    } catch (Exception e) {
        LogWriterUtils.getLogWriter().info("Got an exception : " + e.getMessage());
        assertTrue(e instanceof EOFException || e instanceof SocketException || e instanceof SocketTimeoutException || e instanceof ServerException || e instanceof IOException || e instanceof CacheClosedException);
    }
}
Also used : SocketException(java.net.SocketException) ServerException(java.rmi.ServerException) TestFunction(org.apache.geode.internal.cache.functions.TestFunction) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CacheClosedException(org.apache.geode.cache.CacheClosedException) FunctionInvocationTargetException(org.apache.geode.cache.execute.FunctionInvocationTargetException) ServerException(java.rmi.ServerException) FunctionException(org.apache.geode.cache.execute.FunctionException) SocketException(java.net.SocketException) CacheClosedException(org.apache.geode.cache.CacheClosedException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) EOFException(java.io.EOFException) IgnoredException(org.apache.geode.test.dunit.IgnoredException) Function(org.apache.geode.cache.execute.Function) TestFunction(org.apache.geode.internal.cache.functions.TestFunction) Execution(org.apache.geode.cache.execute.Execution) SocketTimeoutException(java.net.SocketTimeoutException) Iterator(java.util.Iterator) DistributedMember(org.apache.geode.distributed.DistributedMember) EOFException(java.io.EOFException) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet)

Example 73 with SocketTimeoutException

use of java.net.SocketTimeoutException in project geode by apache.

the class OpExecutorImplJUnitTest method testExecuteOnAllQueueServers.

@Test
public void testExecuteOnAllQueueServers() {
    OpExecutorImpl exec = new OpExecutorImpl(manager, queueManager, endpointManager, riTracker, 3, 10, false, cancelCriterion, null);
    exec.executeOnAllQueueServers(new Op() {

        @Override
        public Object attempt(Connection cnx) throws Exception {
            return "hello";
        }

        @Override
        public boolean useThreadLocalConnection() {
            return true;
        }
    });
    assertEquals(0, invalidateConnections);
    assertEquals(0, serverCrashes);
    assertEquals(1, getPrimary);
    assertEquals(1, getBackups);
    reset();
    queueManager.backups = 3;
    exec.executeOnAllQueueServers(new Op() {

        @Override
        public Object attempt(Connection cnx) throws Exception {
            throw new SocketTimeoutException();
        }

        @Override
        public boolean useThreadLocalConnection() {
            return true;
        }
    });
    assertEquals(4, invalidateConnections);
    assertEquals(0, serverCrashes);
    assertEquals(1, getPrimary);
    assertEquals(1, getBackups);
    reset();
    queueManager.backups = 3;
    Object result = exec.executeOnQueuesAndReturnPrimaryResult(new Op() {

        int i = 0;

        @Override
        public Object attempt(Connection cnx) throws Exception {
            i++;
            if (i < 15) {
                throw new IOException();
            }
            return "hello";
        }

        @Override
        public boolean useThreadLocalConnection() {
            return true;
        }
    });
    assertEquals("hello", result);
    assertEquals(14, serverCrashes);
    assertEquals(14, invalidateConnections);
    assertEquals(12, getPrimary);
    assertEquals(1, getBackups);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException) NoAvailableServersException(org.apache.geode.cache.client.NoAvailableServersException) SocketTimeoutException(java.net.SocketTimeoutException) ServerConnectivityException(org.apache.geode.cache.client.ServerConnectivityException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) IOException(java.io.IOException) UnitTest(org.apache.geode.test.junit.categories.UnitTest) ClientServerTest(org.apache.geode.test.junit.categories.ClientServerTest) Test(org.junit.Test)

Example 74 with SocketTimeoutException

use of java.net.SocketTimeoutException in project poi by apache.

the class TestSignatureInfo method testSignEnvelopingDocument.

@Test
public void testSignEnvelopingDocument() throws Exception {
    String testFile = "hello-world-unsigned.xlsx";
    OPCPackage pkg = OPCPackage.open(copy(testdata.getFile(testFile)), PackageAccess.READ_WRITE);
    initKeyPair("Test", "CN=Test");
    final X509CRL crl = PkiTestUtils.generateCrl(x509, keyPair.getPrivate());
    // setup
    SignatureConfig signatureConfig = new SignatureConfig();
    signatureConfig.setOpcPackage(pkg);
    signatureConfig.setKey(keyPair.getPrivate());
    /*
         * We need at least 2 certificates for the XAdES-C complete certificate
         * refs construction.
         */
    List<X509Certificate> certificateChain = new ArrayList<X509Certificate>();
    certificateChain.add(x509);
    certificateChain.add(x509);
    signatureConfig.setSigningCertificateChain(certificateChain);
    signatureConfig.addSignatureFacet(new EnvelopedSignatureFacet());
    signatureConfig.addSignatureFacet(new KeyInfoSignatureFacet());
    signatureConfig.addSignatureFacet(new XAdESSignatureFacet());
    signatureConfig.addSignatureFacet(new XAdESXLSignatureFacet());
    // check for internet, no error means it works
    boolean mockTsp = (getAccessError("http://timestamp.comodoca.com/rfc3161", true, 10000) != null);
    // http://timestamping.edelweb.fr/service/tsp
    // http://tsa.belgium.be/connect
    // http://timestamp.comodoca.com/authenticode
    // http://timestamp.comodoca.com/rfc3161
    // http://services.globaltrustfinder.com/adss/tsa
    signatureConfig.setTspUrl("http://timestamp.comodoca.com/rfc3161");
    // comodoca request fails, if default policy is set ...
    signatureConfig.setTspRequestPolicy(null);
    signatureConfig.setTspOldProtocol(false);
    //set proxy info if any
    String proxy = System.getProperty("http_proxy");
    if (proxy != null && proxy.trim().length() > 0) {
        signatureConfig.setProxyUrl(proxy);
    }
    if (mockTsp) {
        TimeStampService tspService = new TimeStampService() {

            @Override
            public byte[] timeStamp(byte[] data, RevocationData revocationData) throws Exception {
                revocationData.addCRL(crl);
                return "time-stamp-token".getBytes(LocaleUtil.CHARSET_1252);
            }

            @Override
            public void setSignatureConfig(SignatureConfig config) {
            // empty on purpose
            }
        };
        signatureConfig.setTspService(tspService);
    } else {
        TimeStampServiceValidator tspValidator = new TimeStampServiceValidator() {

            @Override
            public void validate(List<X509Certificate> validateChain, RevocationData revocationData) throws Exception {
                for (X509Certificate certificate : validateChain) {
                    LOG.log(POILogger.DEBUG, "certificate: " + certificate.getSubjectX500Principal());
                    LOG.log(POILogger.DEBUG, "validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter());
                }
            }
        };
        signatureConfig.setTspValidator(tspValidator);
        signatureConfig.setTspOldProtocol(signatureConfig.getTspUrl().contains("edelweb"));
    }
    final RevocationData revocationData = new RevocationData();
    revocationData.addCRL(crl);
    OCSPResp ocspResp = PkiTestUtils.createOcspResp(x509, false, x509, x509, keyPair.getPrivate(), "SHA1withRSA", cal.getTimeInMillis());
    revocationData.addOCSP(ocspResp.getEncoded());
    RevocationDataService revocationDataService = new RevocationDataService() {

        @Override
        public RevocationData getRevocationData(List<X509Certificate> revocationChain) {
            return revocationData;
        }
    };
    signatureConfig.setRevocationDataService(revocationDataService);
    // operate
    SignatureInfo si = new SignatureInfo();
    si.setSignatureConfig(signatureConfig);
    try {
        si.confirmSignature();
    } catch (RuntimeException e) {
        pkg.close();
        // only allow a ConnectException because of timeout, we see this in Jenkins from time to time...
        if (e.getCause() == null) {
            throw e;
        }
        if ((e.getCause() instanceof ConnectException) || (e.getCause() instanceof SocketTimeoutException)) {
            Assume.assumeFalse("Only allowing ConnectException with 'timed out' as message here, but had: " + e, e.getCause().getMessage().contains("timed out"));
        } else if (e.getCause() instanceof IOException) {
            Assume.assumeFalse("Only allowing IOException with 'Error contacting TSP server' as message here, but had: " + e, e.getCause().getMessage().contains("Error contacting TSP server"));
        } else if (e.getCause() instanceof RuntimeException) {
            Assume.assumeFalse("Only allowing RuntimeException with 'This site is cur' as message here, but had: " + e, e.getCause().getMessage().contains("This site is cur"));
        }
        throw e;
    }
    // verify
    Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
    assertTrue("Had: " + si.getSignatureConfig().getOpcPackage().getRelationshipsByType(PackageRelationshipTypes.DIGITAL_SIGNATURE_ORIGIN), spIter.hasNext());
    SignaturePart sp = spIter.next();
    boolean valid = sp.validate();
    assertTrue(valid);
    SignatureDocument sigDoc = sp.getSignatureDocument();
    String declareNS = "declare namespace xades='http://uri.etsi.org/01903/v1.3.2#'; " + "declare namespace ds='http://www.w3.org/2000/09/xmldsig#'; ";
    String digestValXQuery = declareNS + "$this/ds:Signature/ds:SignedInfo/ds:Reference";
    for (ReferenceType rt : (ReferenceType[]) sigDoc.selectPath(digestValXQuery)) {
        assertNotNull(rt.getDigestValue());
        assertEquals(signatureConfig.getDigestMethodUri(), rt.getDigestMethod().getAlgorithm());
    }
    String certDigestXQuery = declareNS + "$this//xades:SigningCertificate/xades:Cert/xades:CertDigest";
    XmlObject[] xoList = sigDoc.selectPath(certDigestXQuery);
    assertEquals(xoList.length, 1);
    DigestAlgAndValueType certDigest = (DigestAlgAndValueType) xoList[0];
    assertNotNull(certDigest.getDigestValue());
    String qualPropXQuery = declareNS + "$this/ds:Signature/ds:Object/xades:QualifyingProperties";
    xoList = sigDoc.selectPath(qualPropXQuery);
    assertEquals(xoList.length, 1);
    QualifyingPropertiesType qualProp = (QualifyingPropertiesType) xoList[0];
    boolean qualPropXsdOk = qualProp.validate();
    assertTrue(qualPropXsdOk);
    pkg.close();
}
Also used : X509CRL(java.security.cert.X509CRL) EnvelopedSignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.EnvelopedSignatureFacet) SignatureDocument(org.w3.x2000.x09.xmldsig.SignatureDocument) ArrayList(java.util.ArrayList) RevocationDataService(org.apache.poi.poifs.crypt.dsig.services.RevocationDataService) XAdESXLSignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.XAdESXLSignatureFacet) ReferenceType(org.w3.x2000.x09.xmldsig.ReferenceType) DigestAlgAndValueType(org.etsi.uri.x01903.v13.DigestAlgAndValueType) OCSPResp(org.bouncycastle.cert.ocsp.OCSPResp) TimeStampService(org.apache.poi.poifs.crypt.dsig.services.TimeStampService) KeyInfoSignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.KeyInfoSignatureFacet) List(java.util.List) ArrayList(java.util.ArrayList) ConnectException(java.net.ConnectException) RevocationData(org.apache.poi.poifs.crypt.dsig.services.RevocationData) SignatureConfig(org.apache.poi.poifs.crypt.dsig.SignatureConfig) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SignatureInfo(org.apache.poi.poifs.crypt.dsig.SignatureInfo) TimeStampServiceValidator(org.apache.poi.poifs.crypt.dsig.services.TimeStampServiceValidator) SocketTimeoutException(java.net.SocketTimeoutException) QualifyingPropertiesType(org.etsi.uri.x01903.v13.QualifyingPropertiesType) XmlObject(org.apache.xmlbeans.XmlObject) SignaturePart(org.apache.poi.poifs.crypt.dsig.SignatureInfo.SignaturePart) OPCPackage(org.apache.poi.openxml4j.opc.OPCPackage) XAdESSignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.XAdESSignatureFacet) Test(org.junit.Test)

Example 75 with SocketTimeoutException

use of java.net.SocketTimeoutException in project beam by apache.

the class RetryHttpRequestInitializerTest method testIOExceptionHandlerIsInvokedOnTimeout.

/**
   * Tests that when RPCs fail with {@link SocketTimeoutException}, the IO exception handler
   * is invoked.
   */
@Test
public void testIOExceptionHandlerIsInvokedOnTimeout() throws Exception {
    // Counts the number of calls to execute the HTTP request.
    final AtomicLong executeCount = new AtomicLong();
    // 10 is a private internal constant in the Google API Client library. See
    // com.google.api.client.http.HttpRequest#setNumberOfRetries
    // TODO: update this test once the private internal constant is public.
    final int defaultNumberOfRetries = 10;
    // A mock HTTP request that always throws SocketTimeoutException.
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(new MockLowLevelHttpRequest() {

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            executeCount.incrementAndGet();
            throw new SocketTimeoutException("Fake forced timeout exception");
        }
    }).build();
    // A sample HTTP request to Google Cloud Storage that uses both default Transport and default
    // RetryHttpInitializer.
    Storage storage = new Storage.Builder(transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer()).build();
    Get getRequest = storage.objects().get("gs://fake", "file");
    try {
        getRequest.execute();
        fail();
    } catch (Throwable e) {
        assertThat(e, Matchers.<Throwable>instanceOf(SocketTimeoutException.class));
        assertEquals(1 + defaultNumberOfRetries, executeCount.get());
    }
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) SocketTimeoutException(java.net.SocketTimeoutException) Storage(com.google.api.services.storage.Storage) Get(com.google.api.services.storage.Storage.Objects.Get) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)721 IOException (java.io.IOException)420 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)70 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)51 EOFException (java.io.EOFException)48 HttpURLConnection (java.net.HttpURLConnection)47 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)42 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 MalformedURLException (java.net.MalformedURLException)38 InputStreamReader (java.io.InputStreamReader)37 HashMap (java.util.HashMap)36 OutputStream (java.io.OutputStream)35