Search in sources :

Example 1 with KettleAuthenticationException

use of org.pentaho.di.repository.KettleAuthenticationException in project pentaho-kettle by pentaho.

the class ExecuteJobServletTest method testExecuteJobServletTestWithUnauthorizedUser.

@Test
public void testExecuteJobServletTestWithUnauthorizedUser() throws KettleException, IOException, ServletException {
    doReturn(ExecuteJobServlet.CONTEXT_PATH).when(mockHttpServletRequest).getContextPath();
    doReturn(REPOSITORY_NAME).when(mockHttpServletRequest).getParameter("rep");
    doReturn(UNAUTHORIZED_USER).when(mockHttpServletRequest).getParameter("user");
    doReturn(PASSWORD).when(mockHttpServletRequest).getParameter("pass");
    doReturn(JOB_NAME).when(mockHttpServletRequest).getParameter("job");
    doReturn(LEVEL).when(mockHttpServletRequest).getParameter("level");
    PowerMockito.mockStatic(Encr.class);
    when(Encr.decryptPasswordOptionallyEncrypted(PASSWORD)).thenReturn(PASSWORD);
    KettleAuthenticationException kae = new KettleAuthenticationException();
    ExecutionException ee = new ExecutionException(kae);
    KettleException ke = new KettleException(ee);
    doThrow(ke).when(spyExecuteJobServlet).openRepository(REPOSITORY_NAME, UNAUTHORIZED_USER, PASSWORD);
    StringWriter out = mockWriter();
    spyExecuteJobServlet.doGet(mockHttpServletRequest, spyHttpServletResponse);
    String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.Authentication", ExecuteJobServlet.CONTEXT_PATH);
    assertTrue(out.toString().contains(message));
}
Also used : KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) KettleException(org.pentaho.di.core.exception.KettleException) StringWriter(java.io.StringWriter) Matchers.anyString(org.mockito.Matchers.anyString) ExecutionException(java.util.concurrent.ExecutionException) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with KettleAuthenticationException

use of org.pentaho.di.repository.KettleAuthenticationException in project pentaho-kettle by pentaho.

the class ExecuteJobServlet method doGet.

/**
 * <div id="mindtouch">
 *    <h1>/kettle/executeJob</h1>
 *    <a name="GET"></a>
 *    <h2>GET</h2>
 *    <p>Executes job from the specified repository.
 *  Connects to the repository provided as a parameter, loads the job from it and executes it.
 *  Empty response is returned or response contains output of an error happened during the job execution.
 *  Response contains <code>ERROR</code> result if error happened during job execution.</p>
 *
 *    <p><b>Example Request:</b><br />
 *    <pre function="syntax.xml">
 *    GET /kettle/executeJob/?rep=my_repository&user=my_user&pass=my_password&job=my_job&level=INFO
 *    </pre>
 *
 *    </p>
 *    <h3>Parameters</h3>
 *    <table class="pentaho-table">
 *    <tbody>
 *    <tr>
 *      <th>name</th>
 *      <th>description</th>
 *      <th>type</th>
 *    </tr>
 *    <tr>
 *    <td>rep</td>
 *    <td>Repository id to connect to.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>user</td>
 *    <td>User name to be used to connect to repository.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>pass</td>
 *    <td>User password to be used to connect to repository.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>job</td>
 *    <td>Job name to be loaded and executed.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>level</td>
 *    <td>Logging level to be used for job execution (i.e. Debug).</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>*any name*</td>
 *    <td>All the other parameters will be sent to the job for using as variables.
 *  When necessary you can add custom parameters to the request.
 *  They will be used to set the job variables values.</td>
 *    <td>query</td>
 *    </tr>
 *    </tbody>
 *    </table>
 *
 *  <h3>Response Body</h3>
 *
 *  <table class="pentaho-table">
 *    <tbody>
 *      <tr>
 *        <td align="right">element:</td>
 *        <td>(custom)</td>
 *      </tr>
 *      <tr>
 *        <td align="right">media types:</td>
 *        <td>application/xml</td>
 *      </tr>
 *    </tbody>
 *  </table>
 *    <p>Response contains error output of the job executed or Carte object Id
 *  if the execution was successful.</p>
 *
 *    <p><b>Example Error Response:</b></p>
 *    <pre function="syntax.xml">
 *  <webresult>
 *    <result>OK</result>
 *    <message>Job started</message>
 *    <id>74d96aa6-f29a-4bac-a26a-06a8c8f107e5</id>
 *  </webresult>
 *    </pre>
 *
 *    <h3>Status Codes</h3>
 *    <table class="pentaho-table">
 *  <tbody>
 *    <tr>
 *      <th>code</th>
 *      <th>description</th>
 *    </tr>
 *    <tr>
 *      <td>200</td>
 *      <td>Request was processed.</td>
 *    </tr>
 *    <tr>
 *      <td>500</td>
 *      <td>Internal server error occurs during request processing.</td>
 *    </tr>
 *  </tbody>
 *</table>
 *</div>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) {
        return;
    }
    if (log.isDebug()) {
        logDebug(BaseMessages.getString(PKG, "ExecuteJobServlet.Log.ExecuteJobRequested"));
    }
    // Options taken from PAN
    // 
    String[] knownOptions = new String[] { "rep", "user", "pass", "job", "level" };
    String repOption = request.getParameter("rep");
    String userOption = request.getParameter("user");
    String passOption = Encr.decryptPasswordOptionallyEncrypted(request.getParameter("pass"));
    String jobOption = request.getParameter("job");
    String levelOption = request.getParameter("level");
    PrintWriter out = response.getWriter();
    Repository repository;
    try {
        repository = openRepository(repOption, userOption, passOption);
    } catch (KettleRepositoryNotFoundException krnfe) {
        // Repository not found.
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.UnableToFindRepository", repOption);
        out.println(new WebResult(WebResult.STRING_ERROR, message));
        return;
    } catch (KettleException ke) {
        // Authentication Error.
        if (ke.getCause() instanceof ExecutionException) {
            ExecutionException ee = (ExecutionException) ke.getCause();
            if (ee.getCause() instanceof KettleAuthenticationException) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.Authentication", getContextPath());
                out.println(new WebResult(WebResult.STRING_ERROR, message));
                return;
            }
        }
        // Something unexpected occurred.
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.UnexpectedError", Const.CR + Const.getStackTracker(ke));
        out.println(new WebResult(WebResult.STRING_ERROR, message));
        return;
    }
    String encoding = System.getProperty("KETTLE_DEFAULT_SERVLET_ENCODING", null);
    if (encoding != null && !Utils.isEmpty(encoding.trim())) {
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html; charset=" + encoding);
    }
    JobMeta jobMeta;
    try {
        jobMeta = loadJob(repository, jobOption);
    } catch (KettleException ke) {
        // Job not found in repository.
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        out.println(new WebResult(WebResult.STRING_ERROR, ke.getMessage()));
        return;
    }
    // Set the servlet parameters as variables in the job
    // 
    String[] parameters = jobMeta.listParameters();
    Enumeration<?> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String parameter = (String) parameterNames.nextElement();
        String[] values = request.getParameterValues(parameter);
        // 
        if (Const.indexOfString(parameter, knownOptions) < 0) {
            // 
            if (Const.indexOfString(parameter, parameters) < 0) {
                jobMeta.setVariable(parameter, values[0]);
            } else {
                try {
                    jobMeta.setParameterValue(parameter, values[0]);
                } catch (UnknownParamException upe) {
                    // Unknown parameter is unexpected.
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.UnexpectedError", Const.CR + Const.getStackTracker(upe));
                    out.println(new WebResult(WebResult.STRING_ERROR, message));
                }
            }
        }
    }
    JobExecutionConfiguration jobExecutionConfiguration = new JobExecutionConfiguration();
    LogLevel logLevel = LogLevel.getLogLevelForCode(levelOption);
    jobExecutionConfiguration.setLogLevel(logLevel);
    JobConfiguration jobConfiguration = new JobConfiguration(jobMeta, jobExecutionConfiguration);
    String carteObjectId = UUID.randomUUID().toString();
    SimpleLoggingObject servletLoggingObject = new SimpleLoggingObject(CONTEXT_PATH, LoggingObjectType.CARTE, null);
    servletLoggingObject.setContainerObjectId(carteObjectId);
    servletLoggingObject.setLogLevel(logLevel);
    // Create the job and store in the list...
    // 
    final Job job = new Job(repository, jobMeta, servletLoggingObject);
    job.setRepository(repository);
    job.setSocketRepository(getSocketRepository());
    getJobMap().addJob(jobMeta.getName(), carteObjectId, job, jobConfiguration);
    job.setContainerObjectId(carteObjectId);
    if (repository != null) {
        // The repository connection is open: make sure we disconnect from the repository once we
        // are done with this job.
        // 
        Repository finalRepository = repository;
        job.addJobListener(new JobAdapter() {

            @Override
            public void jobFinished(Job job) {
                finalRepository.disconnect();
            }
        });
    }
    try {
        runJob(job);
        WebResult webResult = new WebResult(WebResult.STRING_OK, "Job started", carteObjectId);
        out.println(webResult.getXML());
        out.flush();
    } catch (Exception executionException) {
        // Something went wrong while running the job.
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        String logging = KettleLogStore.getAppender().getBuffer(job.getLogChannelId(), false).toString();
        String message = BaseMessages.getString(PKG, "ExecuteJobServlet.Error.WhileExecutingJob", jobOption, logging);
        out.println(new WebResult(WebResult.STRING_ERROR, message));
        return;
    }
    // Everything went well till the end.
    response.setStatus(HttpServletResponse.SC_OK);
}
Also used : KettleException(org.pentaho.di.core.exception.KettleException) KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) JobMeta(org.pentaho.di.job.JobMeta) SimpleLoggingObject(org.pentaho.di.core.logging.SimpleLoggingObject) JobExecutionConfiguration(org.pentaho.di.job.JobExecutionConfiguration) JobAdapter(org.pentaho.di.job.JobAdapter) LogLevel(org.pentaho.di.core.logging.LogLevel) ServletException(javax.servlet.ServletException) KettleException(org.pentaho.di.core.exception.KettleException) KettleRepositoryNotFoundException(org.pentaho.di.repository.KettleRepositoryNotFoundException) UnknownParamException(org.pentaho.di.core.parameters.UnknownParamException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) Repository(org.pentaho.di.repository.Repository) UnknownParamException(org.pentaho.di.core.parameters.UnknownParamException) KettleRepositoryNotFoundException(org.pentaho.di.repository.KettleRepositoryNotFoundException) ExecutionException(java.util.concurrent.ExecutionException) Job(org.pentaho.di.job.Job) JobConfiguration(org.pentaho.di.job.JobConfiguration) PrintWriter(java.io.PrintWriter)

Example 3 with KettleAuthenticationException

use of org.pentaho.di.repository.KettleAuthenticationException in project pentaho-kettle by pentaho.

the class ExecuteTransServletTest method doGetRepositoryAuthenticationFailTest.

@Test
public void doGetRepositoryAuthenticationFailTest() throws Exception {
    HttpServletRequest mockHttpServletRequest = mock(HttpServletRequest.class);
    HttpServletResponse mockHttpServletResponse = mock(HttpServletResponse.class);
    RepositoriesMeta repositoriesMeta = mock(RepositoriesMeta.class);
    RepositoryMeta repositoryMeta = mock(RepositoryMeta.class);
    Repository repository = mock(Repository.class);
    PluginRegistry pluginRegistry = mock(PluginRegistry.class);
    KettleException kettleException = mock(KettleException.class);
    ExecutionException executionException = mock(ExecutionException.class);
    KettleLogStore.init();
    StringWriter out = new StringWriter();
    PrintWriter printWriter = new PrintWriter(out);
    when(mockHttpServletRequest.getParameter("rep")).thenReturn("Repo");
    when(mockHttpServletRequest.getParameter("trans")).thenReturn("Trans");
    when(mockHttpServletRequest.getParameter("user")).thenReturn("wrongUser");
    when(mockHttpServletRequest.getParameter("pass")).thenReturn("wrongPass");
    when(mockHttpServletResponse.getWriter()).thenReturn(printWriter);
    whenNew(RepositoriesMeta.class).withNoArguments().thenReturn(repositoriesMeta);
    when(repositoriesMeta.findRepository("Repo")).thenReturn(repositoryMeta);
    mockStatic(PluginRegistry.class);
    when(PluginRegistry.getInstance()).thenReturn(pluginRegistry);
    when(pluginRegistry.loadClass(RepositoryPluginType.class, repositoryMeta, Repository.class)).thenReturn(repository);
    doThrow(kettleException).when(repository).connect("wrongUser", "wrongPass");
    when(kettleException.getCause()).thenReturn(executionException);
    when(executionException.getCause()).thenReturn(new KettleAuthenticationException());
    when(repository.isConnected()).thenReturn(false);
    executeTransServlet.doGet(mockHttpServletRequest, mockHttpServletResponse);
    verify(mockHttpServletResponse).setStatus(HttpServletResponse.SC_OK);
    verify(mockHttpServletResponse).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) RepositoryMeta(org.pentaho.di.repository.RepositoryMeta) KettleException(org.pentaho.di.core.exception.KettleException) KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) Repository(org.pentaho.di.repository.Repository) StringWriter(java.io.StringWriter) PluginRegistry(org.pentaho.di.core.plugins.PluginRegistry) HttpServletResponse(javax.servlet.http.HttpServletResponse) RepositoriesMeta(org.pentaho.di.repository.RepositoriesMeta) ExecutionException(java.util.concurrent.ExecutionException) PrintWriter(java.io.PrintWriter) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 4 with KettleAuthenticationException

use of org.pentaho.di.repository.KettleAuthenticationException in project pentaho-kettle by pentaho.

the class ExecuteTransServlet method doGet.

/**
 * <div id="mindtouch">
 *    <h1>/kettle/executeTrans</h1>
 *    <a name="GET"></a>
 *    <h2>GET</h2>
 *    <p>Executes transformation from the specified repository.
 *  Connects to the repository provided as a parameter, loads the transformation from it and executes it.
 *  Empty response is returned or response contains output of an error happened during the transformation execution.
 *  Response contains <code>ERROR</code> result if error happened during transformation execution.</p>
 *
 *    <p><b>Example Request:</b><br />
 *    <pre function="syntax.xml">
 *    GET /kettle/executeTrans/?rep=my_repository&user=my_user&pass=my_password&trans=my_trans&level=INFO
 *    </pre>
 *
 *    </p>
 *    <h3>Parameters</h3>
 *    <table class="pentaho-table">
 *    <tbody>
 *    <tr>
 *      <th>name</th>
 *      <th>description</th>
 *      <th>type</th>
 *    </tr>
 *    <tr>
 *    <td>rep</td>
 *    <td>Repository id to connect to.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>user</td>
 *    <td>User name to be used to connect to repository.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>pass</td>
 *    <td>User password to be used to connect to repository.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>trans</td>
 *    <td>Transfromation name to be loaded and executed.</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>level</td>
 *    <td>Logging level to be used for transformation execution (i.e. Debug).</td>
 *    <td>query</td>
 *    </tr>
 *    <tr>
 *    <td>*any name*</td>
 *    <td>All the other parameters will be sent to the transformation for using as variables.
 *  When necessary you can add custom parameters to the request.
 *  They will be used to set the transformation variables values..</td>
 *    <td>query</td>
 *    </tr>
 *    </tbody>
 *    </table>
 *
 *  <h3>Response Body</h3>
 *
 *  <table class="pentaho-table">
 *    <tbody>
 *      <tr>
 *        <td align="right">element:</td>
 *        <td>(custom)</td>
 *      </tr>
 *      <tr>
 *        <td align="right">media types:</td>
 *        <td>application/xml</td>
 *      </tr>
 *    </tbody>
 *  </table>
 *    <p>Response contains error output of the transformation executed or nothing
 *  if the execution was successful.</p>
 *
 *    <p><b>Example Error Response:</b></p>
 *    <pre function="syntax.xml">
 *  <webresult>
 *    <result>ERROR</result>
 *    <message>Unexpected error executing the transformation&#x3a;
 *    &#xd;&#xa;org.pentaho.di.core.exception.KettleException&#x3a;
 *    &#xd;&#xa;Unable to find transformation &#x27;dummy-trans.ktr&#x27; in directory
 *    &#x3a;&#x2f;home&#x2f;admin&#xd;&#xa;&#xd;&#xa; at
 *    org.pentaho.di.www.ExecuteTransServlet.loadTransformation&#x28;ExecuteTransServlet.java&#x3a;214&#x29;&#xd;&#xa;
 *    at org.pentaho.di.www.ExecuteTransServlet.doGet&#x28;ExecuteTransServlet.java&#x3a;104&#x29;&#xd;&#xa;
 *    at javax.servlet.http.HttpServlet.service&#x28;HttpServlet.java&#x3a;707&#x29;&#xd;&#xa;
 *    at javax.servlet.http.HttpServlet.service&#x28;HttpServlet.java&#x3a;820&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.servlet.ServletHolder.handle&#x28;ServletHolder.java&#x3a;511&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.servlet.ServletHandler.handle&#x28;ServletHandler.java&#x3a;390&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.servlet.SessionHandler.handle&#x28;SessionHandler.java&#x3a;182&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.handler.ContextHandler.handle&#x28;ContextHandler.java&#x3a;765&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.handler.ContextHandlerCollection.handle&#x28;ContextHandlerCollection.java&#x3a;230&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.handler.HandlerCollection.handle&#x28;HandlerCollection.java&#x3a;114&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.handler.HandlerWrapper.handle&#x28;HandlerWrapper.java&#x3a;152&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.Server.handle&#x28;Server.java&#x3a;326&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.HttpConnection.handleRequest&#x28;HttpConnection.java&#x3a;536&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.HttpConnection&#x24;RequestHandler.headerComplete&#x28;HttpConnection.java&#x3a;915&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.HttpParser.parseNext&#x28;HttpParser.java&#x3a;539&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.HttpParser.parseAvailable&#x28;HttpParser.java&#x3a;212&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.HttpConnection.handle&#x28;HttpConnection.java&#x3a;405&#x29;&#xd;&#xa;
 *    at org.mortbay.jetty.bio.SocketConnector&#x24;Connection.run&#x28;SocketConnector.java&#x3a;228&#x29;&#xd;&#xa;
 *    at org.mortbay.thread.QueuedThreadPool&#x24;PoolThread.run&#x28;QueuedThreadPool.java&#x3a;582&#x29;&#xd;&#xa;
 *    </message>
 *    <id/>
 *  </webresult>
 *    </pre>
 *
 *    <h3>Status Codes</h3>
 *    <table class="pentaho-table">
 *  <tbody>
 *    <tr>
 *      <th>code</th>
 *      <th>description</th>
 *    </tr>
 *    <tr>
 *      <td>200</td>
 *      <td>Request was processed.</td>
 *    </tr>
 *    <tr>
 *      <td>400</td>
 *      <td>When missing mandatory params repo and trans</td>
 *    </tr>
 *    <tr>
 *      <td>401</td>
 *      <td>When authentication to repository fails</td>
 *    </tr>
 *    <tr>
 *      <td>404</td>
 *      <td>When transformation is not found</td>
 *    </tr>
 *    <tr>
 *      <td>500</td>
 *      <td>Internal server error occurs during request processing.</td>
 *    </tr>
 *  </tbody>
 *</table>
 *</div>
 */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) {
        return;
    }
    if (log.isDebug()) {
        logDebug(BaseMessages.getString(PKG, "ExecuteTransServlet.Log.ExecuteTransRequested"));
    }
    // Options taken from PAN
    // 
    String[] knownOptions = new String[] { REP, USER, PASS, TRANS, LEVEL };
    String repOption = request.getParameter(REP);
    String userOption = request.getParameter(USER);
    String passOption = Encr.decryptPasswordOptionallyEncrypted(request.getParameter(PASS));
    String transOption = request.getParameter(TRANS);
    String levelOption = request.getParameter(LEVEL);
    response.setStatus(HttpServletResponse.SC_OK);
    String encoding = System.getProperty("KETTLE_DEFAULT_SERVLET_ENCODING", null);
    if (encoding != null && !Utils.isEmpty(encoding.trim())) {
        response.setCharacterEncoding(encoding);
        response.setContentType("text/html; charset=" + encoding);
    }
    PrintWriter out = response.getWriter();
    if (repOption == null || transOption == null) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.println(new WebResult(WebResult.STRING_ERROR, BaseMessages.getString(PKG, "ExecuteTransServlet.Error.MissingMandatoryParameter", repOption == null ? REP : TRANS)));
        return;
    }
    try {
        final Repository repository = openRepository(repOption, userOption, passOption);
        final TransMeta transMeta = loadTransformation(repository, transOption);
        // Set the servlet parameters as variables in the transformation
        // 
        String[] parameters = transMeta.listParameters();
        Enumeration<?> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = (String) parameterNames.nextElement();
            String[] values = request.getParameterValues(parameter);
            // 
            if (Const.indexOfString(parameter, knownOptions) < 0) {
                // 
                if (Const.indexOfString(parameter, parameters) < 0) {
                    transMeta.setVariable(parameter, values[0]);
                } else {
                    transMeta.setParameterValue(parameter, values[0]);
                }
            }
        }
        TransExecutionConfiguration transExecutionConfiguration = new TransExecutionConfiguration();
        LogLevel logLevel = LogLevel.getLogLevelForCode(levelOption);
        transExecutionConfiguration.setLogLevel(logLevel);
        TransConfiguration transConfiguration = new TransConfiguration(transMeta, transExecutionConfiguration);
        String carteObjectId = UUID.randomUUID().toString();
        SimpleLoggingObject servletLoggingObject = new SimpleLoggingObject(CONTEXT_PATH, LoggingObjectType.CARTE, null);
        servletLoggingObject.setContainerObjectId(carteObjectId);
        servletLoggingObject.setLogLevel(logLevel);
        // Create the transformation and store in the list...
        // 
        final Trans trans = new Trans(transMeta, servletLoggingObject);
        trans.setRepository(repository);
        trans.setSocketRepository(getSocketRepository());
        getTransformationMap().addTransformation(transMeta.getName(), carteObjectId, trans, transConfiguration);
        trans.setContainerObjectId(carteObjectId);
        if (repository != null) {
            // The repository connection is open: make sure we disconnect from the repository once we
            // are done with this transformation.
            // 
            trans.addTransListener(new TransAdapter() {

                @Override
                public void transFinished(Trans trans) {
                    repository.disconnect();
                }
            });
        }
        // Pass the servlet print writer to the transformation...
        // 
        trans.setServletPrintWriter(out);
        trans.setServletReponse(response);
        trans.setServletRequest(request);
        try {
            // Execute the transformation...
            // 
            executeTrans(trans);
            String logging = KettleLogStore.getAppender().getBuffer(trans.getLogChannelId(), false).toString();
            if (trans.isFinishedOrStopped() && trans.getErrors() > 0) {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                out.println(new WebResult(WebResult.STRING_ERROR, BaseMessages.getString(PKG, "ExecuteTransServlet.Error.ErrorExecutingTrans", logging)));
            }
            out.flush();
        } catch (Exception executionException) {
            String logging = KettleLogStore.getAppender().getBuffer(trans.getLogChannelId(), false).toString();
            throw new KettleException(BaseMessages.getString(PKG, "ExecuteTransServlet.Error.ErrorExecutingTrans", logging), executionException);
        }
    } catch (Exception ex) {
        // When we get to this point KettleAuthenticationException has already been wrapped in an Execution Exception
        // and that in a KettleException
        Throwable kettleExceptionCause = ex.getCause();
        if (kettleExceptionCause != null && kettleExceptionCause instanceof ExecutionException) {
            Throwable executionExceptionCause = kettleExceptionCause.getCause();
            if (executionExceptionCause != null && executionExceptionCause instanceof KettleAuthenticationException) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                out.println(new WebResult(WebResult.STRING_ERROR, BaseMessages.getString(PKG, "ExecuteTransServlet.Error.Authentication", getContextPath())));
            }
        } else if (ex.getMessage().contains(UNABLE_TO_FIND_TRANS)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            out.println(new WebResult(WebResult.STRING_ERROR, BaseMessages.getString(PKG, "ExecuteTransServlet.Error.UnableToFindTransformation", transOption)));
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.println(new WebResult(WebResult.STRING_ERROR, BaseMessages.getString(PKG, "ExecuteTransServlet.Error.UnexpectedError", Const.CR + Const.getStackTracker(ex))));
        }
    }
}
Also used : KettleException(org.pentaho.di.core.exception.KettleException) KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) TransMeta(org.pentaho.di.trans.TransMeta) SimpleLoggingObject(org.pentaho.di.core.logging.SimpleLoggingObject) TransConfiguration(org.pentaho.di.trans.TransConfiguration) LogLevel(org.pentaho.di.core.logging.LogLevel) TransAdapter(org.pentaho.di.trans.TransAdapter) ServletException(javax.servlet.ServletException) KettleException(org.pentaho.di.core.exception.KettleException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) KettleAuthenticationException(org.pentaho.di.repository.KettleAuthenticationException) TransExecutionConfiguration(org.pentaho.di.trans.TransExecutionConfiguration) Repository(org.pentaho.di.repository.Repository) ExecutionException(java.util.concurrent.ExecutionException) Trans(org.pentaho.di.trans.Trans) PrintWriter(java.io.PrintWriter)

Aggregations

ExecutionException (java.util.concurrent.ExecutionException)4 KettleException (org.pentaho.di.core.exception.KettleException)4 KettleAuthenticationException (org.pentaho.di.repository.KettleAuthenticationException)4 PrintWriter (java.io.PrintWriter)3 Repository (org.pentaho.di.repository.Repository)3 IOException (java.io.IOException)2 StringWriter (java.io.StringWriter)2 ServletException (javax.servlet.ServletException)2 Test (org.junit.Test)2 LogLevel (org.pentaho.di.core.logging.LogLevel)2 SimpleLoggingObject (org.pentaho.di.core.logging.SimpleLoggingObject)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 Matchers.anyString (org.mockito.Matchers.anyString)1 UnknownParamException (org.pentaho.di.core.parameters.UnknownParamException)1 PluginRegistry (org.pentaho.di.core.plugins.PluginRegistry)1 Job (org.pentaho.di.job.Job)1 JobAdapter (org.pentaho.di.job.JobAdapter)1 JobConfiguration (org.pentaho.di.job.JobConfiguration)1