コード例 #1
0
ファイル: MergeCruiseConfigTest.java プロジェクト: xli/gocd
  @Test
  public void shouldFailToAddDuplicatePipelineAlreadyDefinedInConfigRepo() {
    pipelines =
        new BasicPipelineConfigs(
            "group_main", new Authorization(), PipelineConfigMother.pipelineConfig("pipe1"));
    BasicCruiseConfig localCruiseConfig = new BasicCruiseConfig(pipelines);
    cruiseConfig =
        new BasicCruiseConfig(
            localCruiseConfig, PartialConfigMother.withPipelineInGroup("pipe2", "remote_group"));

    PipelineConfig pipe2Dup = PipelineConfigMother.pipelineConfig("pipe2");
    try {
      cruiseConfig.addPipeline("doesNotMatterWhichGroup", pipe2Dup);
    } catch (Exception ex) {
      assertThat(
          ex.getMessage(),
          is(
              "Pipeline called 'pipe2' is already defined in configuration repository http://some.git at 1234fed"));
    }

    assertThat(cruiseConfig.allPipelines().size(), is(2));
    assertThat(cruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipe2")), is(true));

    assertThat(localCruiseConfig.allPipelines().size(), is(1));
    assertThat(localCruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipe1")), is(true));
    assertThat(localCruiseConfig.hasPipelineNamed(new CaseInsensitiveString("pipe2")), is(false));
  }
コード例 #2
0
  public TestWorkflowDataSourceRepository() throws SQLException, FileNotFoundException {
    // set the log levels
    System.setProperty(
        "java.util.logging.config.file",
        new File("./src/main/resources/logging.properties").getAbsolutePath());

    // first load the example configuration
    try {
      System.getProperties().load(new FileInputStream("./src/main/resources/workflow.properties"));
    } catch (Exception e) {
      fail(e.getMessage());
    }

    // get a temp directory
    File tempDir = null;
    File tempFile;

    try {
      tempFile = File.createTempFile("foo", "bar");
      tempFile.deleteOnExit();
      tempDir = tempFile.getParentFile();
    } catch (Exception e) {
      fail(e.getMessage());
    }

    tmpDirPath = tempDir.getAbsolutePath();
  }
コード例 #3
0
  @Test
  public void testErrorMessage() {
    serviceA.registerHandler(
        "sayHelloException",
        new BaseTransportRequestHandler<StringMessageRequest>() {
          @Override
          public StringMessageRequest newInstance() {
            return new StringMessageRequest();
          }

          @Override
          public String executor() {
            return ThreadPool.Names.GENERIC;
          }

          @Override
          public void messageReceived(StringMessageRequest request, TransportChannel channel)
              throws Exception {
            assertThat("moshe", equalTo(request.message));
            throw new RuntimeException("bad message !!!");
          }
        });

    TransportFuture<StringMessageResponse> res =
        serviceB.submitRequest(
            nodeA,
            "sayHelloException",
            new StringMessageRequest("moshe"),
            new BaseTransportResponseHandler<StringMessageResponse>() {
              @Override
              public StringMessageResponse newInstance() {
                return new StringMessageResponse();
              }

              @Override
              public String executor() {
                return ThreadPool.Names.GENERIC;
              }

              @Override
              public void handleResponse(StringMessageResponse response) {
                assertThat("got response instead of exception", false, equalTo(true));
              }

              @Override
              public void handleException(TransportException exp) {
                assertThat("bad message !!!", equalTo(exp.getCause().getMessage()));
              }
            });

    try {
      res.txGet();
      assertThat("exception should be thrown", false, equalTo(true));
    } catch (Exception e) {
      assertThat("bad message !!!", equalTo(e.getCause().getMessage()));
    }

    serviceA.removeHandler("sayHelloException");
  }
コード例 #4
0
 @Theory
 public void testParseDate(TestData data) {
   try {
     assertThat(testee.parseDate(data.getFile()), is(equalTo(data.getExpectedDate())));
   } catch (Exception ex) {
     ex.printStackTrace(System.err);
     throw ex;
   }
 }
コード例 #5
0
 @Test
 public void testMostRecentFile() {
   try {
     assertThat(
         testee.getMostRecent(filesInTestDir), is(equalTo(DataItems.DIR_FILE_2030.getFile())));
   } catch (Exception ex) {
     ex.printStackTrace(System.err);
     throw ex;
   }
 }
コード例 #6
0
 @Test(expected = Exception.class)
 public void runningCommandWithNonExistentAddressResultsInError() throws Exception {
   String[] args = {"-o", "-a", "user:pwd", "-c", "user:pwd:/FitNesse.NonExistentTestCase?test"};
   Arguments arguments = new Arguments(args);
   try {
     Integer exitCode = new FitNesseMain().launchFitNesse(arguments);
   } catch (Exception e) {
     assertEquals("error loading page: 404", e.getMessage());
     throw e;
   }
 }
コード例 #7
0
  @Test
  public void testParseClearScrollRequestWithInvalidJsonThrowsException() throws Exception {
    ClearScrollRequest clearScrollRequest = new ClearScrollRequest();

    try {
      RestClearScrollAction.buildFromContent(new BytesArray("{invalid_json}"), clearScrollRequest);
      fail("expected parseContent failure");
    } catch (Exception e) {
      assertThat(e, instanceOf(IllegalArgumentException.class));
      assertThat(e.getMessage(), equalTo("Failed to parse request body"));
    }
  }
コード例 #8
0
  @Test
  public void testErrorMessage() {
    serviceA.registerHandler(
        "sayHelloException",
        new BaseTransportRequestHandler<StringMessage>() {
          @Override
          public StringMessage newInstance() {
            return new StringMessage();
          }

          @Override
          public void messageReceived(StringMessage request, TransportChannel channel)
              throws Exception {
            System.out.println("got message: " + request.message);
            assertThat("moshe", equalTo(request.message));
            throw new RuntimeException("bad message !!!");
          }
        });

    TransportFuture<StringMessage> res =
        serviceB.submitRequest(
            serviceANode,
            "sayHelloException",
            new StringMessage("moshe"),
            new BaseTransportResponseHandler<StringMessage>() {
              @Override
              public StringMessage newInstance() {
                return new StringMessage();
              }

              @Override
              public void handleResponse(StringMessage response) {
                assertThat("got response instead of exception", false, equalTo(true));
              }

              @Override
              public void handleException(RemoteTransportException exp) {
                assertThat("bad message !!!", equalTo(exp.getCause().getMessage()));
              }
            });

    try {
      res.txGet();
      assertThat("exception should be thrown", false, equalTo(true));
    } catch (Exception e) {
      assertThat("bad message !!!", equalTo(e.getCause().getMessage()));
    }

    serviceA.removeHandler("sayHelloException");

    System.out.println("after ...");
  }
コード例 #9
0
  private static void startWorkflow() {
    XmlRpcWorkflowManagerClient client = null;
    try {
      client = new XmlRpcWorkflowManagerClient(new URL("http://localhost:" + WM_PORT));
    } catch (Exception e) {
      fail(e.getMessage());
    }

    try {
      client.sendEvent("long", new Metadata());
    } catch (Exception e) {
      LOG.log(Level.SEVERE, e.getMessage());
      throw new RuntimeException(e);
    }
  }
コード例 #10
0
  @Test
  public void testMultistatusDuplicateChildFiltering() {

    Exception e1 = new Exception("Stack Trace");
    e1.setStackTrace(
        createStacktraceForClasses(
            "java.lang.Object",
            "org.eclipse.core.internal.jobs.WorkerPool",
            "org.eclipse.core.internal.jobs.WorkerPool",
            "org.eclipse.core.internal.jobs.Worker"));
    IStatus s1 =
        new Status(
            IStatus.ERROR,
            "org.eclipse.ui.monitoring",
            "Thread 'Worker-3' tid=39 (TIMED_WAITING)\n"
                + "Waiting for: org.eclipse.core.internal.jobs.WorkerPool@416dc7fc",
            e1);

    Exception e2 = new Exception("Stack Trace");
    e2.setStackTrace(
        TestReports.createStacktraceForClasses(
            "java.lang.Object",
            "org.eclipse.core.internal.jobs.WorkerPool",
            "org.eclipse.core.internal.jobs.WorkerPool",
            "org.eclipse.core.internal.jobs.Worker"));
    IStatus s2 =
        new Status(
            IStatus.ERROR,
            "org.eclipse.ui.monitoring",
            "Thread 'Worker-2' tid=36 (TIMED_WAITING)\n"
                + "Waiting for: org.eclipse.core.internal.jobs.WorkerPool@416dc7fc",
            e2);

    IStatus multi =
        new MultiStatus(
            "org.eclipse.ui.monitoring",
            0,
            new IStatus[] {s1, s2},
            "UI freeze of 10s at 08:09:02.936",
            new RuntimeException("stand-in-stacktrace"));
    org.eclipse.epp.internal.logging.aeri.ui.model.Status newStatus =
        Reports.newStatus(multi, configuration);
    assertThat(newStatus.getChildren().size(), is(1));
    assertThat(
        newStatus.getMessage(),
        is(
            "UI freeze of 10s at 08:09:02.936 [1 child-status duplicates removed by Error Reporting]"));
  }
コード例 #11
0
  @Test
  public void testAttemptsToStopStartedServicesOnInitFailure() {
    Service s1 = new ParentTestService();
    FancyCacheProvider s2 = new FancyCacheProvider();

    ServiceLocator locator = new ServiceLocator(s1, s2);
    try {
      locator.startAllServices();
      fail();
    } catch (Exception e) {
      // see org.ehcache.spi.ParentTestService.start()
      assertThat(e, instanceOf(RuntimeException.class));
      assertThat(e.getMessage(), is("Implement me!"));
    }
    assertThat(s2.startStopCounter, is(0));
  }
コード例 #12
0
  /** @since OODT-205 */
  @Test
  public void testWorkflowConditions() {
    DataSourceWorkflowRepository repo = new DataSourceWorkflowRepository(ds);

    Workflow w = null;
    try {
      w = repo.getWorkflowById("1");
    } catch (Exception e) {
      fail(e.getMessage());
    }

    assertNotNull(w);
    assertNotNull(w.getConditions());
    assertTrue(w.getConditions().size() > 0);
    assertEquals(w.getConditions().size(), 1);
  }
コード例 #13
0
  private static void startXmlRpcWorkflowManager() {
    System.setProperty(
        "java.util.logging.config.file",
        new File("./src/main/resources/logging.properties").getAbsolutePath());

    try {
      System.getProperties().load(new FileInputStream("./src/main/resources/workflow.properties"));
    } catch (Exception e) {
      fail(e.getMessage());
    }
    try {
      luceneCatLoc = Files.createTempDirectory("repo").toString();
      LOG.log(Level.INFO, "Lucene instance repository: [" + luceneCatLoc + "]");
    } catch (Exception e) {
      fail(e.getMessage());
    }

    if (new File(luceneCatLoc).exists()) {
      // blow away lucene cat
      LOG.log(Level.INFO, "Removing workflow instance repository: [" + luceneCatLoc + "]");
      try {
        FileUtils.deleteDirectory(new File(luceneCatLoc));
      } catch (IOException e) {
        fail(e.getMessage());
      }
    }

    System.setProperty(
        "workflow.engine.instanceRep.factory",
        "org.apache.oodt.cas.workflow.instrepo.LuceneWorkflowInstanceRepositoryFactory");
    System.setProperty("org.apache.oodt.cas.workflow.instanceRep.lucene.idxPath", luceneCatLoc);

    try {
      System.setProperty(
          "org.apache.oodt.cas.workflow.repo.dirs",
          "file://" + new File("./src/main/resources/examples").getCanonicalPath());
      System.setProperty(
          "org.apache.oodt.cas.workflow.lifecycle.filePath",
          new File("./src/main/resources/examples/workflow-lifecycle.xml").getCanonicalPath());
    } catch (Exception e) {
      fail(e.getMessage());
    }

    try {
      wmgr = new XmlRpcWorkflowManager(WM_PORT);
      Thread.sleep(MILLIS);
    } catch (Exception e) {
      LOG.log(Level.SEVERE, e.getMessage());
      fail(e.getMessage());
    }
  }
コード例 #14
0
ファイル: MergeCruiseConfigTest.java プロジェクト: xli/gocd
 @Test
 public void addPipeline_shouldFailToAddPipelineToMainWhenItExistsInPartialConfig() {
   pipelines =
       new BasicPipelineConfigs(
           "group_main", new Authorization(), PipelineConfigMother.pipelineConfig("pipe1"));
   pipelines.setOrigin(new FileConfigOrigin());
   BasicCruiseConfig mainCruiseConfig = new BasicCruiseConfig(pipelines);
   cruiseConfig =
       new BasicCruiseConfig(mainCruiseConfig, PartialConfigMother.withPipeline("pipe2"));
   try {
     cruiseConfig.addPipeline("group_main", PipelineConfigMother.pipelineConfig("pipe2"));
     fail("should have thrown when trying to add pipe2 when it already exists in partial config");
   } catch (Exception ex) {
     assertThat(
         ex.getMessage(),
         containsString("Pipeline called 'pipe2' is already defined in configuration repository"));
   }
 }
コード例 #15
0
  @Test
  public void testParseClearScrollRequestWithUnknownParamThrowsException() throws Exception {
    BytesReference invalidContent =
        XContentFactory.jsonBuilder()
            .startObject()
            .array("scroll_id", "value_1", "value_2")
            .field("unknown", "keyword")
            .endObject()
            .bytes();
    ClearScrollRequest clearScrollRequest = new ClearScrollRequest();

    try {
      RestClearScrollAction.buildFromContent(invalidContent, clearScrollRequest);
      fail("expected parseContent failure");
    } catch (Exception e) {
      assertThat(e, instanceOf(IllegalArgumentException.class));
      assertThat(e.getMessage(), startsWith("Unknown parameter [unknown]"));
    }
  }
コード例 #16
0
 private static boolean hasMapreduce370() {
   try {
     File corelib = findHadoopCoreLib();
     if (corelib != null) {
       String classFile = "org/apache/hadoop/mapreduce/lib/output/MultipleOutputs.class";
       LOG.debug("Searching MultipleOutputs");
       JarFile jar = new JarFile(corelib);
       try {
         boolean found = jar.getJarEntry(classFile) != null;
         LOG.debug("Searched MultipleOutputs: found={}", found);
         return found;
       } finally {
         jar.close();
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return false;
 }
コード例 #17
0
  @Test
  public void testFingerprint() {

    Exception cause = new RuntimeException("cause");
    Exception r1 = new RuntimeException("exception message");

    r1.fillInStackTrace();
    Exception r2 = new RuntimeException("exception message", cause);
    r2.fillInStackTrace();

    IStatus s1 =
        new Status(IStatus.ERROR, "org.eclipse.epp.logging.aeri", "some error message", r1);
    IStatus s2 =
        new Status(IStatus.ERROR, "org.eclipse.epp.logging.aeri", "some error message", r2);

    org.eclipse.epp.internal.logging.aeri.ui.model.Status noCause =
        Reports.newStatus(s1, configuration);
    org.eclipse.epp.internal.logging.aeri.ui.model.Status withCause =
        Reports.newStatus(s2, configuration);

    Assert.assertNotEquals(noCause.getFingerprint(), withCause.getFingerprint());
  }
コード例 #18
0
  @Test
  public void testMultistatusChildFilteringHandlesEmptyStacktrace() {

    Exception e1 = new Exception("Stack Trace 1");
    e1.setStackTrace(new java.lang.StackTraceElement[0]);
    IStatus s1 =
        new Status(
            IStatus.ERROR,
            "org.eclipse.ui.monitoring",
            "Thread 'Signal Dispatcher' tid=4 (RUNNABLE)",
            e1);

    IStatus multi =
        new MultiStatus(
            "org.eclipse.ui.monitoring",
            0,
            new IStatus[] {s1},
            "UI freeze of 10s at 08:09:02.936",
            new RuntimeException("stand-in-stacktrace"));
    org.eclipse.epp.internal.logging.aeri.ui.model.Status newStatus =
        Reports.newStatus(multi, configuration);
    assertThat(newStatus.getChildren().size(), is(0));
  }
コード例 #19
0
  private static void stopXmlRpcWorkflowManager() {
    System.setProperty(
        "java.util.logging.config.file",
        new File("./src/main/resources/logging.properties").getAbsolutePath());

    try {
      System.getProperties().load(new FileInputStream("./src/main/resources/workflow.properties"));
    } catch (Exception e) {
      fail(e.getMessage());
    }
    System.setProperty(
        "workflow.engine.instanceRep.factory",
        "org.apache.oodt.cas.workflow.instrepo.LuceneWorkflowInstanceRepositoryFactory");
    System.setProperty("org.apache.oodt.cas.workflow.instanceRep.lucene.idxPath", luceneCatLoc);

    try {
      System.setProperty(
          "org.apache.oodt.cas.workflow.repo.dirs",
          "file://" + new File("./src/main/resources/examples").getCanonicalPath());
      System.setProperty(
          "org.apache.oodt.cas.workflow.lifecycle.filePath",
          new File("./src/main/resources/examples/workflow-lifecycle.xml").getCanonicalPath());
    } catch (Exception e) {
      fail(e.getMessage());
    }

    try {
      wmgr.shutdown();
    } catch (Exception e) {
      LOG.log(Level.SEVERE, e.getMessage());
      fail(e.getMessage());
    }

    /** Sleep before removing to prevent file not found issues. */
    try {
      Thread.sleep(MILLIS);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    if (new File(luceneCatLoc).exists()) {
      // blow away lucene cat
      LOG.log(Level.INFO, "Removing workflow instance repository: [" + luceneCatLoc + "]");
      try {
        FileUtils.deleteDirectory(new File(luceneCatLoc));
      } catch (IOException e) {
        fail(e.getMessage());
      }
    }
  }
コード例 #20
0
  @Test
  public void testVoidMessageCompressed() {
    serviceA.registerHandler(
        "sayHello",
        new BaseTransportRequestHandler<TransportRequest.Empty>() {
          @Override
          public TransportRequest.Empty newInstance() {
            return TransportRequest.Empty.INSTANCE;
          }

          @Override
          public String executor() {
            return ThreadPool.Names.GENERIC;
          }

          @Override
          public void messageReceived(TransportRequest.Empty request, TransportChannel channel) {
            try {
              channel.sendResponse(
                  TransportResponse.Empty.INSTANCE,
                  TransportResponseOptions.options().withCompress(true));
            } catch (IOException e) {
              e.printStackTrace();
              assertThat(e.getMessage(), false, equalTo(true));
            }
          }
        });

    TransportFuture<TransportResponse.Empty> res =
        serviceB.submitRequest(
            nodeA,
            "sayHello",
            TransportRequest.Empty.INSTANCE,
            TransportRequestOptions.options().withCompress(true),
            new BaseTransportResponseHandler<TransportResponse.Empty>() {
              @Override
              public TransportResponse.Empty newInstance() {
                return TransportResponse.Empty.INSTANCE;
              }

              @Override
              public String executor() {
                return ThreadPool.Names.GENERIC;
              }

              @Override
              public void handleResponse(TransportResponse.Empty response) {}

              @Override
              public void handleException(TransportException exp) {
                exp.printStackTrace();
                assertThat(
                    "got exception instead of a response: " + exp.getMessage(),
                    false,
                    equalTo(true));
              }
            });

    try {
      TransportResponse.Empty message = res.get();
      assertThat(message, notNullValue());
    } catch (Exception e) {
      assertThat(e.getMessage(), false, equalTo(true));
    }

    serviceA.removeHandler("sayHello");
  }
コード例 #21
0
  @Test
  public void testHelloWorld() {
    serviceA.registerHandler(
        "sayHello",
        new BaseTransportRequestHandler<StringMessage>() {
          @Override
          public StringMessage newInstance() {
            return new StringMessage();
          }

          @Override
          public void messageReceived(StringMessage request, TransportChannel channel) {
            System.out.println("got message: " + request.message);
            assertThat("moshe", equalTo(request.message));
            try {
              channel.sendResponse(new StringMessage("hello " + request.message));
            } catch (IOException e) {
              e.printStackTrace();
              assertThat(e.getMessage(), false, equalTo(true));
            }
          }
        });

    TransportFuture<StringMessage> res =
        serviceB.submitRequest(
            serviceANode,
            "sayHello",
            new StringMessage("moshe"),
            new BaseTransportResponseHandler<StringMessage>() {
              @Override
              public StringMessage newInstance() {
                return new StringMessage();
              }

              @Override
              public void handleResponse(StringMessage response) {
                System.out.println("got response: " + response.message);
                assertThat("hello moshe", equalTo(response.message));
              }

              @Override
              public void handleException(RemoteTransportException exp) {
                exp.printStackTrace();
                assertThat(
                    "got exception instead of a response: " + exp.getMessage(),
                    false,
                    equalTo(true));
              }
            });

    try {
      StringMessage message = res.get();
      assertThat("hello moshe", equalTo(message.message));
    } catch (Exception e) {
      assertThat(e.getMessage(), false, equalTo(true));
    }

    serviceA.removeHandler("sayHello");

    System.out.println("after ...");
  }
コード例 #22
0
  @Test
  public void testMultistatusMainStacktracesNotFiltered() {

    Exception e1 = new Exception("Stack Trace");
    java.lang.StackTraceElement[] stackTrace =
        createStacktraceForClasses(
            "java.lang.Thread",
            "org.eclipse.epp.logging.aeri.ui.actions.UiFreezeAction",
            "org.eclipse.ui.internal.PluginAction",
            "org.eclipse.ui.internal.WWinPluginAction",
            "org.eclipse.jface.action.ActionContributionItem",
            "org.eclipse.jface.action.ActionContributionItem",
            "org.eclipse.jface.action.ActionContributionItem",
            "org.eclipse.swt.widgets.EventTable",
            "org.eclipse.swt.widgets.Display",
            "org.eclipse.swt.widgets.Widget",
            "org.eclipse.swt.widgets.Display",
            "org.eclipse.swt.widgets.Display",
            "org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine",
            "org.eclipse.core.databinding.observable.Realm",
            "org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine",
            "org.eclipse.e4.ui.internal.workbench.E4Workbench",
            "org.eclipse.ui.internal.Workbench",
            "org.eclipse.core.databinding.observable.Realm",
            "org.eclipse.ui.internal.Workbench",
            "org.eclipse.ui.PlatformUI",
            "org.eclipse.ui.internal.ide.application.IDEApplication",
            "org.eclipse.equinox.internal.app.EclipseAppHandle",
            "org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher",
            "org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher",
            "org.eclipse.core.runtime.adaptor.EclipseStarter",
            "org.eclipse.core.runtime.adaptor.EclipseStarter",
            "sun.reflect.NativeMethodAccessorImpl",
            "sun.reflect.NativeMethodAccessorImpl",
            "sun.reflect.DelegatingMethodAccessorImpl",
            "java.lang.reflect.Method",
            "org.eclipse.equinox.launcher.Main",
            "org.eclipse.equinox.launcher.Main",
            "org.eclipse.equinox.launcher.Main",
            "org.eclipse.equinox.launcher.Main",
            "org.eclipse.equinox.launcher.Main");
    e1.setStackTrace(stackTrace);
    IStatus s1 =
        new Status(
            IStatus.ERROR,
            "org.eclipse.ui.monitoring",
            "Sample at 11:25:04.447 (+1,331s)\n" + "Thread 'main' tid=1 (TIMED_WAITING)",
            e1);

    IStatus multi =
        new MultiStatus(
            "org.eclipse.ui.monitoring",
            0,
            new IStatus[] {s1},
            "UI freeze of 6,0s at 11:24:59.108",
            new RuntimeException("stand-in-stacktrace"));
    org.eclipse.epp.internal.logging.aeri.ui.model.Status newStatus =
        Reports.newStatus(multi, configuration);
    assertThat(newStatus.getChildren().size(), is(1));
    assertThat(
        newStatus.getChildren().get(0).getException().getStackTrace().size(),
        is(stackTrace.length));
  }
コード例 #23
0
  @Test
  public void testStrictAliasParsingInIndicesCreatedViaTemplates() throws Exception {
    // Indexing into a should succeed, because the field mapping for field 'field' is defined in the
    // test mapping.
    client()
        .admin()
        .indices()
        .preparePutTemplate("template1")
        .setTemplate("a*")
        .setOrder(0)
        .addMapping("test", "field", "type=string")
        .addAlias(new Alias("alias1").filter(termFilter("field", "value")))
        .get();
    // Indexing into b should succeed, because the field mapping for field 'field' is defined in the
    // _default_ mapping and the test type exists.
    client()
        .admin()
        .indices()
        .preparePutTemplate("template2")
        .setTemplate("b*")
        .setOrder(0)
        .addMapping("_default_", "field", "type=string")
        .addMapping("test")
        .addAlias(new Alias("alias2").filter(termFilter("field", "value")))
        .get();
    // Indexing into c should succeed, because the field mapping for field 'field' is defined in the
    // _default_ mapping.
    client()
        .admin()
        .indices()
        .preparePutTemplate("template3")
        .setTemplate("c*")
        .setOrder(0)
        .addMapping("_default_", "field", "type=string")
        .addAlias(new Alias("alias3").filter(termFilter("field", "value")))
        .get();
    // Indexing into d index should fail, since there is field with name 'field' in the mapping
    client()
        .admin()
        .indices()
        .preparePutTemplate("template4")
        .setTemplate("d*")
        .setOrder(0)
        .addAlias(new Alias("alias4").filter(termFilter("field", "value")))
        .get();

    client().prepareIndex("a1", "test", "test").setSource("{}").get();
    BulkResponse response =
        client().prepareBulk().add(new IndexRequest("a2", "test", "test").source("{}")).get();
    assertThat(response.hasFailures(), is(false));
    assertThat(response.getItems()[0].isFailed(), equalTo(false));
    assertThat(response.getItems()[0].getIndex(), equalTo("a2"));
    assertThat(response.getItems()[0].getType(), equalTo("test"));
    assertThat(response.getItems()[0].getId(), equalTo("test"));
    assertThat(response.getItems()[0].getVersion(), equalTo(1l));

    client().prepareIndex("b1", "test", "test").setSource("{}").get();
    response =
        client().prepareBulk().add(new IndexRequest("b2", "test", "test").source("{}")).get();
    assertThat(response.hasFailures(), is(false));
    assertThat(response.getItems()[0].isFailed(), equalTo(false));
    assertThat(response.getItems()[0].getIndex(), equalTo("b2"));
    assertThat(response.getItems()[0].getType(), equalTo("test"));
    assertThat(response.getItems()[0].getId(), equalTo("test"));
    assertThat(response.getItems()[0].getVersion(), equalTo(1l));

    client().prepareIndex("c1", "test", "test").setSource("{}").get();
    response =
        client().prepareBulk().add(new IndexRequest("c2", "test", "test").source("{}")).get();
    assertThat(response.hasFailures(), is(false));
    assertThat(response.getItems()[0].isFailed(), equalTo(false));
    assertThat(response.getItems()[0].getIndex(), equalTo("c2"));
    assertThat(response.getItems()[0].getType(), equalTo("test"));
    assertThat(response.getItems()[0].getId(), equalTo("test"));
    assertThat(response.getItems()[0].getVersion(), equalTo(1l));

    try {
      client().prepareIndex("d1", "test", "test").setSource("{}").get();
      fail();
    } catch (Exception e) {
      assertThat(
          ExceptionsHelper.unwrapCause(e), instanceOf(ElasticsearchIllegalArgumentException.class));
      assertThat(e.getMessage(), containsString("failed to parse filter for alias [alias4]"));
    }
    response =
        client().prepareBulk().add(new IndexRequest("d2", "test", "test").source("{}")).get();
    assertThat(response.hasFailures(), is(true));
    assertThat(response.getItems()[0].isFailed(), equalTo(true));
    assertThat(
        response.getItems()[0].getFailureMessage(),
        containsString("failed to parse filter for alias [alias4]"));
  }
コード例 #24
0
ファイル: EntityWrapper.java プロジェクト: sjones4/eucalyptus
 /**
  * Returns the unique result from the database that exactly matches <code>example</code>. The
  * differences between this method and {@link #getUnique(Object)} are:
  *
  * <ol>
  *   <li>{@link #getUnique(Object)} uses <i><code>enableLike</code></i> match and this method does
  *       not. <i><code>enableLike</code></i> criteria trips hibernate when special characters are
  *       involved. So it has been replaced by exact "=" (equals to)
  *   <li>Unique result logic is correctly implemented in this method. If the query returns more
  *       than one result, this method correctly throws an exception wrapping <code>
  *       NonUniqueResultException</code>. {@link #getUnique(Object)} does not throw an exception
  *       in this case and returns a result as long as it finds one or more matching results
  *       (because of the following properties set on the query: <code>setMaxResults(1)</code>,
  *       <code>setFetchSize(1)</code> and <code>setFirstResult(0)</code>)
  * </ol>
  *
  * @param example
  * @return
  * @throws EucalyptusCloudException
  */
 @SuppressWarnings("unchecked")
 public <T> T getUniqueEscape(final T example) throws EucalyptusCloudException {
   try {
     Object id = null;
     try {
       id =
           this.getEntityManager()
               .getEntityManagerFactory()
               .getPersistenceUnitUtil()
               .getIdentifier(example);
     } catch (final Exception ex) {
     }
     if (id != null) {
       final T res = (T) this.getEntityManager().find(example.getClass(), id);
       if (res == null) {
         throw new NoSuchElementException("@Id: " + id);
       } else {
         return res;
       }
     } else if ((example instanceof HasNaturalId)
         && (((HasNaturalId) example).getNaturalId() != null)) {
       final String natId = ((HasNaturalId) example).getNaturalId();
       final T ret =
           (T)
               this.createCriteria(example.getClass())
                   .setLockMode(LockMode.NONE)
                   .setCacheable(true)
                   .add(Restrictions.naturalId().set("naturalId", natId))
                   .uniqueResult();
       if (ret == null) {
         throw new NoSuchElementException("@NaturalId: " + natId);
       }
       return ret;
     } else {
       final T ret =
           (T)
               this.createCriteria(example.getClass())
                   .setLockMode(LockMode.NONE)
                   .setCacheable(true)
                   .add(Example.create(example))
                   .uniqueResult();
       if (ret == null) {
         throw new NoSuchElementException("example: " + LogUtil.dumpObject(example));
       }
       return ret;
     }
   } catch (final NonUniqueResultException ex) {
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " because "
             + ex.getMessage(),
         ex);
   } catch (final NoSuchElementException ex) {
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " using "
             + ex.getMessage(),
         ex);
   } catch (final Exception ex) {
     final Exception newEx = PersistenceExceptions.throwFiltered(ex);
     throw new EucalyptusCloudException(
         "Get unique failed for "
             + example.getClass().getSimpleName()
             + " because "
             + newEx.getMessage(),
         newEx);
   }
 }
コード例 #25
0
  @Test
  public void testHelloWorldCompressed() {
    serviceA.registerHandler(
        "sayHello",
        new BaseTransportRequestHandler<StringMessageRequest>() {
          @Override
          public StringMessageRequest newInstance() {
            return new StringMessageRequest();
          }

          @Override
          public String executor() {
            return ThreadPool.Names.GENERIC;
          }

          @Override
          public void messageReceived(StringMessageRequest request, TransportChannel channel) {
            assertThat("moshe", equalTo(request.message));
            try {
              channel.sendResponse(
                  new StringMessageResponse("hello " + request.message),
                  TransportResponseOptions.options().withCompress(true));
            } catch (IOException e) {
              e.printStackTrace();
              assertThat(e.getMessage(), false, equalTo(true));
            }
          }
        });

    TransportFuture<StringMessageResponse> res =
        serviceB.submitRequest(
            nodeA,
            "sayHello",
            new StringMessageRequest("moshe"),
            TransportRequestOptions.options().withCompress(true),
            new BaseTransportResponseHandler<StringMessageResponse>() {
              @Override
              public StringMessageResponse newInstance() {
                return new StringMessageResponse();
              }

              @Override
              public String executor() {
                return ThreadPool.Names.GENERIC;
              }

              @Override
              public void handleResponse(StringMessageResponse response) {
                assertThat("hello moshe", equalTo(response.message));
              }

              @Override
              public void handleException(TransportException exp) {
                exp.printStackTrace();
                assertThat(
                    "got exception instead of a response: " + exp.getMessage(),
                    false,
                    equalTo(true));
              }
            });

    try {
      StringMessageResponse message = res.get();
      assertThat("hello moshe", equalTo(message.message));
    } catch (Exception e) {
      assertThat(e.getMessage(), false, equalTo(true));
    }

    serviceA.removeHandler("sayHello");
  }
コード例 #26
0
  @Test
  public void testMockFailToSendNoConnectRule() {
    serviceA.registerHandler(
        "sayHello",
        new BaseTransportRequestHandler<StringMessageRequest>() {
          @Override
          public StringMessageRequest newInstance() {
            return new StringMessageRequest();
          }

          @Override
          public String executor() {
            return ThreadPool.Names.GENERIC;
          }

          @Override
          public void messageReceived(StringMessageRequest request, TransportChannel channel)
              throws Exception {
            assertThat("moshe", equalTo(request.message));
            throw new RuntimeException("bad message !!!");
          }
        });

    serviceB.addFailToSendNoConnectRule(nodeA);

    TransportFuture<StringMessageResponse> res =
        serviceB.submitRequest(
            nodeA,
            "sayHello",
            new StringMessageRequest("moshe"),
            new BaseTransportResponseHandler<StringMessageResponse>() {
              @Override
              public StringMessageResponse newInstance() {
                return new StringMessageResponse();
              }

              @Override
              public String executor() {
                return ThreadPool.Names.GENERIC;
              }

              @Override
              public void handleResponse(StringMessageResponse response) {
                assertThat("got response instead of exception", false, equalTo(true));
              }

              @Override
              public void handleException(TransportException exp) {
                assertThat(exp.getCause().getMessage(), endsWith("DISCONNECT: simulated"));
              }
            });

    try {
      res.txGet();
      assertThat("exception should be thrown", false, equalTo(true));
    } catch (Exception e) {
      assertThat(e.getCause().getMessage(), endsWith("DISCONNECT: simulated"));
    }

    try {
      serviceB.connectToNode(nodeA);
      assertThat("exception should be thrown", false, equalTo(true));
    } catch (ConnectTransportException e) {
      // all is well
    }

    try {
      serviceB.connectToNodeLight(nodeA);
      assertThat("exception should be thrown", false, equalTo(true));
    } catch (ConnectTransportException e) {
      // all is well
    }

    serviceA.removeHandler("sayHello");
  }