Ejemplo n.º 1
2
  @Override
  public void setResponse(Response response) {
    this.isCommitted = false;
    this.out = null;
    this.response = response = (response != null) ? response : Responses.noContent().build();
    this.mappedThrowable = null;

    if (response instanceof ResponseImpl) {
      final ResponseImpl responseImpl = (ResponseImpl) response;
      setStatusType(responseImpl.getStatusType());
      setHeaders(response.getMetadata());
      setEntity(responseImpl.getEntity(), responseImpl.getEntityType());
    } else {
      setStatus(response.getStatus());
      setHeaders(response.getMetadata());
      setEntity(response.getEntity());
    }
  }
  @Test
  public void testMetadataImportExport()
      throws PlatformInitializationException, IOException, PlatformImportException {
    List<MimeType> mimeTypeList = new ArrayList<MimeType>();
    mimeTypeList.add(new MimeType("Metadata", ".xmi"));

    File metadata = new File("test-res/dsw/testData/metadata.xmi");
    RepositoryFile repoMetadataFile =
        new RepositoryFile.Builder(metadata.getName()).folder(false).hidden(false).build();
    MetadataImportHandler metadataImportHandler =
        new MetadataImportHandler(
            mimeTypeList,
            (IPentahoMetadataDomainRepositoryImporter)
                PentahoSystem.get(IMetadataDomainRepository.class));
    RepositoryFileImportBundle bundle1 =
        new RepositoryFileImportBundle.Builder()
            .file(repoMetadataFile)
            .charSet("UTF-8")
            .input(new FileInputStream(metadata))
            .mime(".xmi")
            .withParam("domain-id", "SalesData")
            .build();
    metadataImportHandler.importFile(bundle1);

    final Response salesData = new DatasourceResource().doGetDSWFilesAsDownload("SalesData");
    Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode());
    Assert.assertNotNull(salesData.getMetadata());
    Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition"));
    Assert.assertEquals(
        salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class);
    Assert.assertTrue(
        ((String) salesData.getMetadata().getFirst("Content-Disposition")).endsWith(".xmi\""));
  }
Ejemplo n.º 3
0
 @Test
 public void testMultipleRootResources() throws Exception {
   WadlGenerator wg = new WadlGenerator();
   wg.setDefaultMediaType(WadlGenerator.WADL_TYPE.toString());
   ClassResourceInfo cri1 =
       ResourceUtils.createClassResourceInfo(BookStore.class, BookStore.class, true, true);
   ClassResourceInfo cri2 =
       ResourceUtils.createClassResourceInfo(Orders.class, Orders.class, true, true);
   List<ClassResourceInfo> cris = new ArrayList<ClassResourceInfo>();
   cris.add(cri1);
   cris.add(cri2);
   Message m = mockMessage("http://localhost:8080/baz", "", WadlGenerator.WADL_QUERY, cris);
   Response r = handleRequest(wg, m);
   assertEquals(
       WadlGenerator.WADL_TYPE.toString(),
       r.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE).toString());
   String wadl = r.getEntity().toString();
   Document doc = StaxUtils.read(new StringReader(wadl));
   checkGrammars(
       doc.getDocumentElement(), "thebook", "books", "thebook2s", "thebook2", "thechapter");
   List<Element> els = getWadlResourcesInfo(doc, "http://localhost:8080/baz", 2);
   checkBookStoreInfo(els.get(0), "prefix1:thebook", "prefix1:thebook2", "prefix1:thechapter");
   Element orderResource = els.get(1);
   assertEquals("/orders", orderResource.getAttribute("path"));
 }
Ejemplo n.º 4
0
    private void doInvoke(String actualBookName, String actualHeaderName) throws Exception {
      Response response = client.post(actualBookName);

      assertEquals(actualHeaderName, response.getMetadata().getFirst("CustomHeader").toString());
      String responseValue = IOUtils.readStringFromStream((InputStream) response.getEntity());
      assertEquals(actualBookName, responseValue);
    }
 @Test
 public void shouldLodgeAPagingTraverserAndTraverseTheFirstPageBeforeRespondingWith201() {
   Response response = createAPagedTraverser();
   assertEquals(201, response.getStatus());
   String responseUri = response.getMetadata().get("Location").get(0).toString();
   assertThat(responseUri, containsString("/node/0/paged/traverse/node/"));
   assertNotNull(response.getEntity());
   assertThat(new String((byte[]) response.getEntity()), containsString("\"name\" : \"19\""));
 }
Ejemplo n.º 6
0
  @Test
  public void content_type_and_content_length_in_response() throws Exception {
    final String data = "person";
    final String help = null;
    final String nnew = null;
    final String diff = null;
    final String redirect = null;
    final String source = "test";
    final String contentType = "text/plain; charset=US-ASCII";

    final Response response =
        subject.doGet(request, source, data, help, nnew, diff, redirect, contentType);

    List<Object> contentLengthResponse = response.getMetadata().get(HttpHeaders.CONTENT_TYPE);
    assertThat(contentLengthResponse.size(), is(1));
    assertThat(contentLengthResponse.get(0).toString(), is("text/plain"));
    List<Object> contentTypeResponse = response.getMetadata().get(HttpHeaders.CONTENT_LENGTH);
    assertThat(contentTypeResponse.size(), is(1));
    assertThat(contentTypeResponse.get(0).toString(), is("2"));
  }
Ejemplo n.º 7
0
 private void checkResponse(Response r) throws Exception {
   assertNotNull(r);
   assertEquals(
       MediaType.APPLICATION_XML, r.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE).toString());
   //        File f = new File("test.xml");
   //        f.delete();
   //        f.createNewFile();
   //        System.out.println(f.getAbsolutePath());
   //        FileOutputStream fos = new FileOutputStream(f);
   //        fos.write(r.getEntity().toString().getBytes());
   //        fos.flush();
   //        fos.close();
 }
Ejemplo n.º 8
0
  protected void writeJaxrsResponse(
      HttpRequest request, HttpResponse response, Response jaxrsResponse) throws WriterException {
    Object type = jaxrsResponse.getMetadata().getFirst(HttpHeaderNames.CONTENT_TYPE);
    if (type == null && jaxrsResponse.getEntity() != null) {
      ResourceMethod method = (ResourceMethod) request.getAttribute(ResourceMethod.class.getName());
      if (method != null) {
        jaxrsResponse
            .getMetadata()
            .putSingle(
                HttpHeaderNames.CONTENT_TYPE,
                method.resolveContentType(request, jaxrsResponse.getEntity()));
      } else {
        MediaType contentType =
            resolveContentTypeByAccept(
                request.getHttpHeaders().getAcceptableMediaTypes(), jaxrsResponse.getEntity());
        jaxrsResponse.getMetadata().putSingle(HttpHeaderNames.CONTENT_TYPE, contentType);
      }
    }

    ServerResponseWriter.writeResponse(
        (BuiltResponse) jaxrsResponse, request, response, providerFactory);
  }
  @Test
  public void createInstance() {
    CassandraInstance instance = createMock(CassandraInstance.class);
    service.save(RING_NAME, instance);
    expect(instance.getId()).andReturn(CASSANDRA_ID);
    replayAll();

    Response response = resource.createInstance(instance);
    assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
    assertEquals(
        String.valueOf(CASSANDRA_ID),
        response.getMetadata().getFirst(HttpHeaders.LOCATION).toString());
  }
Ejemplo n.º 10
0
  @Test
  public void logoutResourceDeletesSessionCookie() throws Exception {
    NewCookie cookie =
        cookieFactory.getSessionCookie(User.named("Me"), ZonedDateTime.now(clock).plusDays(1));
    Response response = sessionLogoutResource.logout(cookie);

    assertThat(response.getStatus()).isEqualTo(303);

    String resultCookie = response.getMetadata().getFirst("Set-Cookie").toString();
    assertThat(resultCookie)
        .contains("HttpOnly")
        .contains("Secure")
        .contains("Path=/admin;")
        .contains("session=expired;");
  }
Ejemplo n.º 11
0
  @Test
  public void testPeersVersionNegotiationDowngrade() throws Exception {
    final HttpServletRequest req = mock(HttpServletRequest.class);
    doReturn("999").when(req).getHeader(eq(HttpHeaders.PROTOCOL_VERSION));

    final NiFiServiceFacade serviceFacade = mock(NiFiServiceFacade.class);

    final SiteToSiteResource resource = getSiteToSiteResource(serviceFacade);

    final Response response = resource.getPeers(req);

    PeersEntity resultEntity = (PeersEntity) response.getEntity();

    assertEquals(200, response.getStatus());
    assertEquals(1, resultEntity.getPeers().size());
    assertEquals(new Integer(1), response.getMetadata().getFirst(HttpHeaders.PROTOCOL_VERSION));
  }
  private void assertOkResponse(Response response, SlotLifecycleState state, UUID... slotIds) {
    assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());

    AgentStatus agentStatus = coordinator.getAgentByAgentId(agentId);
    Builder<SlotStatusRepresentation> builder = ImmutableList.builder();
    for (UUID slotId : slotIds) {
      SlotStatus slotStatus = agentStatus.getSlotStatus(slotId);
      builder.add(
          SlotStatusRepresentation.from(slotStatus.changeState(state), prefixSize, MOCK_REPO));
      assertEquals(slotStatus.getAssignment(), APPLE_ASSIGNMENT);
    }
    assertEqualsNoOrder((Collection<?>) response.getEntity(), builder.build());
    assertNull(
        response
            .getMetadata()
            .get("Content-Type")); // content type is set by jersey based on @Produces
  }
Ejemplo n.º 13
0
  @Test
  public void handle_invalid_content_type() throws Exception {
    final String data = "person";
    final String help = null;
    final String nnew = null;
    final String diff = null;
    final String redirect = null;
    final String source = "test";
    final String contentType = "invalid";

    final Response response =
        subject.doGet(request, source, data, help, nnew, diff, redirect, contentType);

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_OK));
    assertThat(response.getEntity().toString(), is("OK"));
    List<Object> contentLengthResponse = response.getMetadata().get(HttpHeaders.CONTENT_TYPE);
    assertThat(contentLengthResponse.size(), is(1));
    assertThat(contentLengthResponse.get(0).toString(), is("text/plain"));
  }
Ejemplo n.º 14
0
  @Test
  public void testCreateReport() {
    // Setup
    Integer jobId = 1;
    CommandRegistry mockCommandRegistry = createMockCommandRegistry();
    ReportCommand reportCommand = createReportCommand();
    expect(mockCommandRegistry.<ReportCommandOptions>newCommand(reportCommand.getName()))
        .andReturn(reportCommand)
        .atLeastOnce();

    CommandJobService mockCommandJobService = createMockCommandJobService();
    expect(
            mockCommandJobService.launchCommand(
                eqCommandJob(createCommandJob(jobId, reportCommand, null))))
        .andReturn(jobId)
        .atLeastOnce();

    WebShellResource sut = new WebShellResource();
    sut.setCommandJobService(mockCommandJobService);
    sut.setCommandRegistry(mockCommandRegistry);

    replay(mockCommandRegistry, mockCommandJobService);

    // Exercise
    ReportCommandOptionsDto optionsDto = createReportCommandOptionsDto("test report", "project1");
    Response response = sut.createReport(optionsDto);

    // Verify mocks
    verify(mockCommandRegistry, mockCommandJobService);

    // Verify that the options in the dto were applied to the launched command
    ReportCommandOptions importOptions = reportCommand.getOptions();
    assertThat(optionsDto.getName()).isEqualTo(importOptions.getName());

    // Verify that the HTTP response code was CREATED (201) and that the "Location"
    // header was set to '/shell/command/{jobId}'.
    assertThat(response.getStatus()).isEqualTo(Response.Status.CREATED.getStatusCode());
    assertThat(response.getMetadata().getFirst("Location").toString())
        .isEqualTo("/shell/command/" + jobId);
  }
  protected void executeReadTest(String content, String fileName, Long size, String mimeType)
      throws IOException, MimeTypeParseException, ContentFrameworkException,
          MimeTypeResolutionException {

    ContentFramework framework = mock(ContentFramework.class);
    ReadResponse readResponse = mock(ReadResponse.class);

    ContentItem contentItem =
        getMockGoodContentItem(content, fileName, "contentIdValue", size, mimeType);
    when(readResponse.getContentItem()).thenReturn(contentItem);

    when(framework.read(isA(ReadRequest.class))).thenReturn(readResponse);

    ContentEndpoint endpoint = new ContentEndpoint(framework, getMockMimeTypeMapper());
    Response response = endpoint.read(anyString());

    // Assertions for all valid headers returned
    assertThat(response.getStatus(), equalTo(200));
    assertThat(IOUtils.toString((InputStream) response.getEntity()), equalTo(content));

    if (fileName != null) {
      assertThat(
          (String) response.getMetadata().getFirst(CONTENT_DISPOSITION),
          equalToIgnoringWhiteSpace("inline; filename=" + fileName));
    } else {
      assertThat(response.getMetadata().getFirst(CONTENT_DISPOSITION), is(nullValue()));
    }

    if (mimeType != null) {
      assertThat(
          (String) response.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE), equalTo(mimeType));
    } else {
      assertThat(
          (String) response.getMetadata().getFirst(HttpHeaders.CONTENT_TYPE),
          equalTo(MediaType.APPLICATION_OCTET_STREAM));
    }

    if (size != null) {
      assertThat(
          (String) response.getMetadata().getFirst(HttpHeaders.CONTENT_LENGTH),
          equalTo(String.valueOf(size)));
    } else {
      assertThat(response.getMetadata().getFirst(HttpHeaders.CONTENT_LENGTH), is(nullValue()));
    }
  }
  protected BuiltResponse invokeOnTarget(
      HttpRequest request, HttpResponse response, Object target) {
    ResteasyProviderFactory.pushContext(
        ResourceInfo.class, resourceInfo); // we don't pop so writer interceptors can get at this

    PostMatchContainerRequestContext requestContext =
        new PostMatchContainerRequestContext(request, this);
    for (ContainerRequestFilter filter : requestFilters) {
      try {
        filter.filter(requestContext);
      } catch (IOException e) {
        throw new ApplicationException(e);
      }
      BuiltResponse serverResponse = (BuiltResponse) requestContext.getResponseAbortedWith();
      if (serverResponse != null) {
        return serverResponse;
      }
    }

    if (validator != null) {
      if (isValidatable) {
        validator.validate(request, target);
      }
      if (methodIsValidatable) {
        request.setAttribute(GeneralValidator.class.getName(), validator);
      } else if (isValidatable) {
        validator.checkViolations(request);
      }
    }

    Object rtn = null;
    try {
      rtn = methodInjector.invoke(request, response, target);
    } catch (RuntimeException ex) {
      if (request.getAsyncContext().isSuspended()) {
        try {
          request.getAsyncContext().getAsyncResponse().resume(ex);
        } catch (Exception e) {
          logger.error("Error resuming failed async operation", e);
        }
        return null;
      } else {
        throw ex;
      }
    }

    if (request.getAsyncContext().isSuspended() || request.wasForwarded()) {
      return null;
    }
    if (rtn == null || method.getReturnType().equals(void.class)) {
      BuiltResponse build = (BuiltResponse) Response.noContent().build();
      build.addMethodAnnotations(method.getAnnotatedMethod());
      return build;
    }
    if (Response.class.isAssignableFrom(method.getReturnType()) || rtn instanceof Response) {
      if (!(rtn instanceof BuiltResponse)) {
        Response r = (Response) rtn;
        Headers<Object> metadata = new Headers<Object>();
        metadata.putAll(r.getMetadata());
        rtn = new BuiltResponse(r.getStatus(), metadata, r.getEntity(), null);
      }
      BuiltResponse rtn1 = (BuiltResponse) rtn;
      rtn1.addMethodAnnotations(method.getAnnotatedMethod());
      if (rtn1.getGenericType() == null) {
        if (getMethod().getReturnType().equals(Response.class)) {
          rtn1.setGenericType(rtn1.getEntityClass());
        } else {
          rtn1.setGenericType(method.getGenericReturnType());
        }
      }
      return rtn1;
    }

    Response.ResponseBuilder builder = Response.ok(rtn);
    BuiltResponse jaxrsResponse = (BuiltResponse) builder.build();
    if (jaxrsResponse.getGenericType() == null) {
      if (getMethod().getReturnType().equals(Response.class)) {
        jaxrsResponse.setGenericType(jaxrsResponse.getEntityClass());
      } else {
        jaxrsResponse.setGenericType(method.getGenericReturnType());
      }
    }
    jaxrsResponse.addMethodAnnotations(method.getAnnotatedMethod());
    return jaxrsResponse;
  }
Ejemplo n.º 17
0
 public static String getLocation(final Response response) {
   final URI uri = (URI) response.getMetadata().getFirst("Location");
   return uri.toString();
 }
Ejemplo n.º 18
0
    @Override
    public DataSource invoke(DataSource msg) {
      try {
        final URL url = new URL(this.endpoint);
        final String httpMethod =
            (String) this.requestContext.get(MessageContext.HTTP_REQUEST_METHOD);

        Map<String, List<String>> header =
            (Map<String, List<String>>)
                this.requestContext.get(MessageContext.HTTP_REQUEST_HEADERS);
        for (Map.Entry<String, List<String>> entry : header.entrySet()) {
          this.client.header(entry.getKey(), entry.getValue().toArray());
        }
        String username = (String) this.requestContext.get(Dispatch.USERNAME_PROPERTY);
        String password = (String) this.requestContext.get(Dispatch.PASSWORD_PROPERTY);

        if (username != null) {
          this.client.header(
              AUTHORIZATION,
              "Basic " + Base64.encodeBytes((username + ':' + password).getBytes())); // $NON-NLS-1$
        } else if (this.requestContext.get(GSSCredential.class.getName()) != null) {
          WebClient.getConfig(this.client)
              .getRequestContext()
              .put(
                  GSSCredential.class.getName(),
                  this.requestContext.get(GSSCredential.class.getName()));
          WebClient.getConfig(this.client)
              .getRequestContext()
              .put("auth.spnego.requireCredDelegation", true); // $NON-NLS-1$
        } else if (this.requestContext.get(OAuthCredential.class.getName()) != null) {
          OAuthCredential credential =
              (OAuthCredential) this.requestContext.get(OAuthCredential.class.getName());
          this.client.header(
              AUTHORIZATION, credential.getAuthorizationHeader(this.endpoint, httpMethod));
        }

        InputStream payload = null;
        if (msg != null) {
          payload = msg.getInputStream();
        }

        HTTPClientPolicy clientPolicy =
            WebClient.getConfig(this.client).getHttpConduit().getClient();
        Long timeout = (Long) this.requestContext.get(RECEIVE_TIMEOUT);
        if (timeout != null) {
          clientPolicy.setReceiveTimeout(timeout);
        }
        timeout = (Long) this.requestContext.get(CONNECTION_TIMEOUT);
        if (timeout != null) {
          clientPolicy.setConnectionTimeout(timeout);
        }

        javax.ws.rs.core.Response response = this.client.invoke(httpMethod, payload);
        this.responseContext.put(WSConnection.STATUS_CODE, response.getStatus());
        this.responseContext.putAll(response.getMetadata());

        ArrayList contentTypes =
            (ArrayList) this.responseContext.get("content-type"); // $NON-NLS-1$
        String contentType =
            contentTypes != null
                ? (String) contentTypes.get(0)
                : "application/octet-stream"; //$NON-NLS-1$
        return new HttpDataSource(url, (InputStream) response.getEntity(), contentType);
      } catch (IOException e) {
        throw new WebServiceException(e);
      }
    }
Ejemplo n.º 19
0
  private String verifyResponse(
      Response resp,
      String content,
      int status,
      List<String> encoding,
      List<String> language,
      List<String> type,
      List<String> var,
      List<String> ccl,
      List<String> cookies)
      throws Exception {
    boolean pass = true;
    StringBuffer sb = new StringBuffer();

    sb.append("========== Verifying a Response: " + newline);

    String tmp = verifyResponse(resp, content, status, null);
    sb.append(indent + tmp + newline);
    if (tmp.endsWith("false")) {
      pass = false;
    }

    MultivaluedMap<java.lang.String, java.lang.Object> mvp = resp.getMetadata();

    for (Map.Entry<String, List<Object>> entry : mvp.entrySet()) {
      String key = entry.getKey();
      sb.append(
          indent
              + "Processing Key found in response: "
              + key
              + ": "
              + entry.getValue()
              + "; "
              + newline);

      if (key.equalsIgnoreCase("Vary")) {
        for (String value : var) {
          String actual = entry.getValue().toString().toLowerCase();
          if (actual.indexOf(value) < 0) {
            pass = false;
            sb.append(indent + indent + "Expected header " + value + " not set in Vary." + newline);
          } else {
            sb.append(indent + indent + "Found expected header " + value + "." + newline);
          }
        }
      }

      if (encoding != null) {
        if (key.toString().equalsIgnoreCase("Content-encoding")) {
          for (Object enc : entry.getValue()) {
            if (!encoding.contains(enc.toString().toLowerCase())) {
              pass = false;
              sb.append(indent + indent + "Encoding test failed: " + newline);
            }
          }
        }
      }

      if (language != null) {
        if (key.toString().equalsIgnoreCase("Content-language")) {
          for (Object lang : entry.getValue()) {
            if (!language.contains(lang.toString())) {
              pass = false;
              sb.append(
                  indent
                      + indent
                      + "language test failed: "
                      + lang
                      + " is not expected in Response"
                      + newline);
              for (String tt : language) {
                sb.append(indent + indent + "Expecting Content-Language " + tt + newline);
              }
            }
          }
        }
      }

      if (type != null) {
        if (key.toString().equalsIgnoreCase("Content-Type")) {
          for (Object lang : entry.getValue()) {
            if (!type.contains(lang.toString().toLowerCase())) {
              pass = false;
              sb.append(
                  indent
                      + indent
                      + "Content-Type test failed: "
                      + lang
                      + " is not expected in Response"
                      + newline);
            }
          }
        }
      }

      if (ccl != null) {
        for (String tt : ccl) {
          sb.append("Expecting Cache-Control " + tt + newline);
        }
        if (key.toString().equalsIgnoreCase("Cache-Control")) {
          for (Object all_ccl : entry.getValue()) {
            for (String cc : ccl) {
              if (!(all_ccl.toString().toLowerCase().indexOf(cc.toLowerCase()) > -1)) {
                pass = false;
                sb.append(
                    indent
                        + indent
                        + "Cache-Control test failed: "
                        + cc
                        + " is not found in Response."
                        + newline);
              }
            }
          }
        }
      }

      if (cookies != null) {
        for (String tt : cookies) {
          sb.append(indent + indent + "EXpecting Set-Cookie" + tt + newline);
        }
        if (key.toString().equalsIgnoreCase("Set-Cookie")) {
          for (Object nck_actual : entry.getValue()) {
            sb.append(indent + indent + "Processing " + nck_actual.toString() + newline);
            String s = nck_actual.toString().toLowerCase().replace(" ", "");
            if (!cookies.contains(s)) {
              pass = false;
              sb.append(
                  indent
                      + indent
                      + "Set-Cookie test failed: "
                      + nck_actual
                      + " is not expected in Response."
                      + newline);
            } else {
              sb.append(
                  indent
                      + indent
                      + "Expected Set-Cookie: "
                      + nck_actual
                      + " is found in Response."
                      + newline);
            }
          }
        }
      }
    }
    sb.append(indent + pass);

    return sb.toString();
  }
Ejemplo n.º 20
0
  private String verifyResponse(
      Response resp, String content, int status, HashMap<String, String> expected_map)
      throws Exception {
    boolean pass = true;
    StringBuffer sb = new StringBuffer();

    sb.append("========== Verifying a Response with Map: " + newline);

    String entity = (String) resp.getEntity();

    if ((content == null) || (content == "")) {
      if (!(resp.getEntity() == null) || (resp.getEntity() == "")) {
        pass = false;
        sb.append(
            indent
                + "Entity verification failed: expecting no content, got "
                + (String) resp.getEntity()
                + newline);
      }
    } else if (!content.equals(((String) resp.getEntity()))) {
      pass = false;
      sb.append(
          indent
              + "Entity verification failed: expecting "
              + content
              + ", got "
              + (String) resp.getEntity()
              + newline);
    } else {
      sb.append(
          indent + "Correct content found in Response: " + (String) resp.getEntity() + newline);
    }

    if (resp.getStatus() != status) {
      pass = false;
      sb.append(
          indent
              + "Status code verification failed: expecting "
              + status
              + ", got "
              + resp.getStatus()
              + newline);
    } else {
      sb.append(indent + "Correct status found in Response: " + status + newline);
    }

    MultivaluedMap<java.lang.String, java.lang.Object> mvp = resp.getMetadata();
    if (expected_map == null) {
      sb.append(
          indent
              + "No keys to verify or expected, but found the following keys in Response:"
              + newline);
      for (String key : mvp.keySet()) {
        sb.append(indent + indent + "Key: " + key + "; " + mvp.getFirst(key) + ";" + newline);
      }
    } else {
      for (String key_actual : mvp.keySet()) {
        sb.append(indent + "Response contains key: " + key_actual + newline);
      }
      sb.append(indent + "Verifying the following keys in Response:" + newline);
      String actual, expected = null;
      for (Map.Entry<String, String> entry : expected_map.entrySet()) {
        String key = entry.getKey();
        if (!mvp.containsKey(key)) {
          pass = false;
          sb.append(indent + indent + "Key: " + key + " is not found in Response;" + newline);
        } else if (key.equalsIgnoreCase("last-modified")) {
          sb.append(indent + indent + "Key Last-Modified is found in response" + newline);
        } else {
          expected = entry.getValue().toLowerCase();
          actual = mvp.getFirst(key).toString().toLowerCase();

          if (actual.startsWith("\"") && actual.endsWith("\"")) {
            actual = actual.substring(1, actual.length() - 1);
          }

          if (!actual.equals(expected)) {
            pass = false;
            sb.append(
                indent
                    + indent
                    + "Key: "
                    + key
                    + " found in Response, but with different value;"
                    + newline);
            sb.append(
                indent
                    + indent
                    + "Expecting "
                    + entry.getValue()
                    + "; got "
                    + mvp.getFirst(key)
                    + newline);
          }
          sb.append(
              indent
                  + indent
                  + "Processed key "
                  + key
                  + " with expected value "
                  + entry.getValue()
                  + newline);
        }
      }
    }
    sb.append(indent + pass);
    return sb.toString();
  }
  private String parseTraverserIdFromLocationUri(Response response) {
    String locationUri = response.getMetadata().get("Location").get(0).toString();

    return locationUri.substring(locationUri.lastIndexOf("/") + 1);
  }
  @Test
  public void testMondrianImportExport() throws Exception {
    final String domainName = "SalesData";
    List<MimeType> mimeTypeList = new ArrayList<MimeType>();
    mimeTypeList.add(new MimeType("Mondrian", "mondrian.xml"));
    System.setProperty(
        "org.osjava.sj.root", "test-res/solution1/system/simple-jndi"); // $NON-NLS-1$ //$NON-NLS-2$

    File mondrian = new File("test-res/dsw/testData/SalesData.mondrian.xml");
    RepositoryFile repoMondrianFile =
        new RepositoryFile.Builder(mondrian.getName()).folder(false).hidden(false).build();
    RepositoryFileImportBundle bundle1 =
        new RepositoryFileImportBundle.Builder()
            .file(repoMondrianFile)
            .charSet("UTF-8")
            .input(new FileInputStream(mondrian))
            .mime("mondrian.xml")
            .withParam("parameters", "Datasource=Pentaho;overwrite=true")
            .withParam("domain-id", "SalesData")
            .build();
    MondrianImportHandler mondrianImportHandler =
        new MondrianImportHandler(mimeTypeList, PentahoSystem.get(IMondrianCatalogService.class));
    mondrianImportHandler.importFile(bundle1);

    try {
      KettleEnvironment.init();
      Props.init(Props.TYPE_PROPERTIES_EMPTY);
    } catch (Exception e) {
      // may already be initialized by another test
    }

    Domain domain = generateModel();

    ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
    model.setModelName("ORDERS");
    model.setDomain(domain);
    model.getWorkspaceHelper().populateDomain(model);

    new ModelerService().serializeModels(domain, domainName);

    final Response salesData =
        new DatasourceResource().doGetDSWFilesAsDownload(domainName + ".xmi");
    Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode());
    Assert.assertNotNull(salesData.getMetadata());
    Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition"));
    Assert.assertEquals(
        salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class);
    Assert.assertTrue(
        ((String) salesData.getMetadata().getFirst("Content-Disposition"))
            .endsWith(domainName + ".zip\""));

    File file = File.createTempFile(domainName, ".zip");
    final FileOutputStream fileOutputStream = new FileOutputStream(file);
    ((StreamingOutput) salesData.getEntity()).write(fileOutputStream);
    fileOutputStream.close();

    final ZipFile zipFile = new ZipFile(file);
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
      final ZipEntry zipEntry = entries.nextElement();
      Assert.assertTrue(
          zipEntry.getName().equals(domainName + ".xmi")
              || zipEntry.getName().equals(domainName + ".mondrian.xml"));
    }
    zipFile.close();
    file.delete();
  }