Package org.nasutekds.server.tools

Examples of org.nasutekds.server.tools.LDAPConnection


   */
  public LDAPConnection connect(LDAPConnectionConsoleInteraction ui,
                                PrintStream out, PrintStream err)
          throws LDAPConnectionException
  {
    LDAPConnection connection = null;
    try {
      ui.run();
      LDAPConnectionOptions options = new LDAPConnectionOptions();
      options.setVersionNumber(3);
      connection = connect(
View Full Code Here


  throws LDAPConnectionException
  {
    // Attempt to connect and authenticate to the Directory Server.
    AtomicInteger nextMessageID = new AtomicInteger(1);

    LDAPConnection connection = new LDAPConnection(
            host, port, options, out, err);

    connection.connectToHost(bindDN, bindPw, nextMessageID, timeout);

    return connection;
  }
View Full Code Here

               new LDAPConnectionOptions();
          PrintStream nullPrintStream =
               new PrintStream(new OutputStream() {
                 public void write ( int b ) { }
               });
          LDAPConnection connection =
               new LDAPConnection(hostname, ldapPort,
                                  connectionOptions,
                                  nullPrintStream,
                                  nullPrintStream);

          connection.connectToHost(null, null, nextMessageID);

          try
          {
            LDAPReader reader = connection.getLDAPReader();
            LDAPWriter writer = connection.getLDAPWriter();

            // Send the Get Symmetric Key extended request.

            ByteString requestValue =
                 GetSymmetricKeyExtendedOperation.encodeRequestValue(
                      symmetricKey, getInstanceKeyID());

            ExtendedRequestProtocolOp extendedRequest =
                 new ExtendedRequestProtocolOp(
                      ServerConstants.
                           OID_GET_SYMMETRIC_KEY_EXTENDED_OP,
                      requestValue);

            ArrayList<Control> controls =
                 new ArrayList<Control>();
            LDAPMessage requestMessage =
                 new LDAPMessage(nextMessageID.getAndIncrement(),
                                 extendedRequest, controls);
            writer.writeMessage(requestMessage);
            LDAPMessage responseMessage = reader.readMessage();

            ExtendedResponseProtocolOp extendedResponse =
                 responseMessage.getExtendedResponseProtocolOp();
            if (extendedResponse.getResultCode() ==
                 LDAPResultCode.SUCCESS)
            {
              // Got our symmetric key value.
              return extendedResponse.getValue().toString();
            }
          }
          finally
          {
            connection.close(nextMessageID);
          }
        }
      }
      catch (Exception e)
      {
View Full Code Here

   * @throws IOException   If an error occurs while interacting with the client.
   */
  public void doPost(HttpServletRequest req, HttpServletResponse res)
  throws ServletException, IOException {
    LDAPConnectionOptions connOptions = new LDAPConnectionOptions();
    LDAPConnection connection = null;
    BatchRequest batchRequest = null;

    // Keep the Servlet input stream buffered in case the SOAP unmarshalling
    // fails, the SAX parsing will be able to retrieve the requestID even if
    // the XML is malmformed by resetting the input stream.
    BufferedInputStream is = new BufferedInputStream(req.getInputStream(),
                                                     65536);
    if ( is.markSupported() ) {
      is.mark(65536);
    }

    // Create response in the beginning as it might be used if the parsing
    // failes.
    BatchResponse batchResponse = objFactory.createBatchResponse();
    List<JAXBElement<?>> batchResponses = batchResponse.getBatchResponses();
    Document doc = db.newDocument();

    SOAPBody soapBody = null;

    MimeHeaders mimeHeaders = new MimeHeaders();
    Enumeration en = req.getHeaderNames();
    String bindDN = null;
    String bindPassword = null;
    boolean authorizationInHeader = false;
    while (en.hasMoreElements()) {
      String headerName = (String) en.nextElement();
      String headerVal = req.getHeader(headerName);
      if (headerName.equalsIgnoreCase("authorization")) {
        if (headerVal.startsWith("Basic ")) {
          authorizationInHeader = true;
          String authorization = headerVal.substring(6).trim();
          try {
            String unencoded = new String(Base64.decode(authorization));
            int colon = unencoded.indexOf(':');
            if (colon > 0) {
              bindDN = unencoded.substring(0, colon).trim();
              bindPassword = unencoded.substring(colon + 1);
            }
          } catch (ParseException ex) {
            // DN:password parsing error
            batchResponses.add(
              createErrorResponse(
                    new LDAPException(LDAPResultCode.INVALID_CREDENTIALS,
                    Message.raw(ex.getMessage()))));
            break;
          }
        }
      }
      StringTokenizer tk = new StringTokenizer(headerVal, ",");
      while (tk.hasMoreTokens()) {
        mimeHeaders.addHeader(headerName, tk.nextToken().trim());
      }
    }

    if ( ! authorizationInHeader ) {
      // if no authorization, set default user
      bindDN = "";
      bindPassword = "";
    } else {
      // otherwise if DN or password is null, send back an error
      if ( (bindDN == null || bindPassword == null)
         && batchResponses.size()==0) {
        batchResponses.add(
              createErrorResponse(
                    new LDAPException(LDAPResultCode.INVALID_CREDENTIALS,
                    Message.raw("Unable to retrieve credentials."))));
      }
    }

    // if an error already occured, the list is not empty
    if ( batchResponses.size() == 0 ) {
      try {
        SOAPMessage message = messageFactory.createMessage(mimeHeaders, is);
        soapBody = message.getSOAPBody();
      } catch (SOAPException ex) {
        // SOAP was unable to parse XML successfully
        batchResponses.add(
          createXMLParsingErrorResponse(is,
                                        batchResponse,
                                        String.valueOf(ex.getCause())));
      }
    }

    if ( soapBody != null ) {
      Iterator it = soapBody.getChildElements();
      while (it.hasNext()) {
        Object obj = it.next();
        if (!(obj instanceof SOAPElement)) {
          continue;
        }
        SOAPElement se = (SOAPElement) obj;
        JAXBElement<BatchRequest> batchRequestElement = null;
        try {
          Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
          unmarshaller.setSchema(schema);
          batchRequestElement = unmarshaller.unmarshal(se, BatchRequest.class);
        } catch (JAXBException e) {
          // schema validation failed
          batchResponses.add(createXMLParsingErrorResponse(is,
                                                       batchResponse,
                                                       String.valueOf(e)));
        }
        if ( batchRequestElement != null ) {
          batchRequest = batchRequestElement.getValue();

          // set requestID in response
          batchResponse.setRequestID(batchRequest.getRequestID());

          boolean connected = false;
          if ( connection == null ) {
            connection = new LDAPConnection(hostName, port, connOptions);
            try {
              connection.connectToHost(bindDN, bindPassword);
              connected = true;
            } catch (LDAPConnectionException e) {
              // if connection failed, return appropriate error response
              batchResponses.add(createErrorResponse(e));
            }
          }
          if ( connected ) {
            List<DsmlMessage> list = batchRequest.getBatchRequests();

            for (DsmlMessage request : list) {
              JAXBElement<?> result = performLDAPRequest(connection, request);
              if ( result != null ) {
                batchResponses.add(result);
              }
              // evaluate response to check if an error occured
              Object o = result.getValue();
              if ( o instanceof ErrorResponse ) {
                if ( ON_ERROR_EXIT.equals(batchRequest.getOnError()) ) {
                  break;
                }
              } else if ( o instanceof LDAPResult ) {
                int code = ((LDAPResult)o).getResultCode().getCode();
                if ( code != LDAPResultCode.SUCCESS
                  && code != LDAPResultCode.REFERRAL
                  && code != LDAPResultCode.COMPARE_TRUE
                  && code != LDAPResultCode.COMPARE_FALSE ) {
                  if ( ON_ERROR_EXIT.equals(batchRequest.getOnError()) ) {
                    break;
                  }
                }
              }
            }
          }
          // close connection to LDAP server
          if ( connection != null ) {
            connection.close(nextMessageID);
          }
        }
      }
    }
    try {
View Full Code Here

          err.println(wrapText(message, MAX_LINE_WIDTH));
          return 1;
        }
      }

      LDAPConnection conn = null;
      try {
        conn = argParser.connect(out, err);
        TaskClient tc = new TaskClient(conn);
        TaskEntry taskEntry = tc.schedule(this);
        Message startTime = taskEntry.getScheduledStartTime();
        if (taskEntry.getTaskState() == TaskState.RECURRING) {
          out.println(
                  wrapText(INFO_TASK_TOOL_RECURRING_TASK_SCHEDULED.get(
                          taskEntry.getType(),
                          taskEntry.getId()),
                  MAX_LINE_WIDTH));
        } else if (startTime == null || startTime.length() == 0) {
          out.println(
                  wrapText(INFO_TASK_TOOL_TASK_SCHEDULED_NOW.get(
                          taskEntry.getType(),
                          taskEntry.getId()),
                  MAX_LINE_WIDTH));
        } else {
          out.println(
                  wrapText(INFO_TASK_TOOL_TASK_SCHEDULED_FUTURE.get(
                          taskEntry.getType(),
                          taskEntry.getId(),
                          taskEntry.getScheduledStartTime()),
                  MAX_LINE_WIDTH));
        }
        if (!taskScheduleArgs.startArg.isPresent()) {

          // Poll the task printing log messages until finished
          String taskId = taskEntry.getId();
          Set<Message> printedLogMessages = new HashSet<Message>();
          do {
            taskEntry = tc.getTaskEntry(taskId);
            List<Message> logs = taskEntry.getLogMessages();
            for (Message log : logs) {
              if (!printedLogMessages.contains(log)) {
                printedLogMessages.add(log);
                out.println(log);
              }
            }

            try {
              Thread.sleep(SYNCHRONOUS_TASK_POLL_INTERVAL);
            } catch (InterruptedException e) {
              // ignore
            }

          } while (!taskEntry.isDone());
          if (TaskState.isSuccessful(taskEntry.getTaskState())) {
            if (taskEntry.getTaskState() != TaskState.RECURRING) {
              out.println(
                  wrapText(INFO_TASK_TOOL_TASK_SUCESSFULL.get(
                          taskEntry.getType(),
                          taskEntry.getId()),
                  MAX_LINE_WIDTH));
            }
            return 0;
          } else {
            out.println(
                wrapText(INFO_TASK_TOOL_TASK_NOT_SUCESSFULL.get(
                        taskEntry.getType(),
                        taskEntry.getId()),
                MAX_LINE_WIDTH));
            return 1;
          }
        }
        ret = 0;
      } catch (LDAPConnectionException e) {
        Message message = null;
        if (isWrongPortException(e,
            new Integer(argParser.getArguments().getPort())))
        {
          message = ERR_TASK_LDAP_FAILED_TO_CONNECT_WRONG_PORT.get(
            argParser.getArguments().getHostName(),
            argParser.getArguments().getPort());
        } else {
          message = ERR_TASK_TOOL_START_TIME_NO_LDAP.get(e.getMessage());
        }
        if (err != null) err.println(wrapText(message, MAX_LINE_WIDTH));
        ret = 1;
      } catch (IOException ioe) {
        Message message = ERR_TASK_TOOL_IO_ERROR.get(String.valueOf(ioe));
        if (err != null) err.println(wrapText(message, MAX_LINE_WIDTH));
        ret = 1;
      } catch (ASN1Exception ae) {
        Message message = ERR_TASK_TOOL_DECODE_ERROR.get(ae.getMessage());
        if (err != null) err.println(wrapText(message, MAX_LINE_WIDTH));
        ret = 1;
      } catch (LDAPException le) {
        Message message = ERR_TASK_TOOL_DECODE_ERROR.get(le.getMessage());
        if (err != null) err.println(wrapText(message, MAX_LINE_WIDTH));
        ret = 1;
      } catch (OpenDsException e) {
        Message message = e.getMessageObject();
        if (err != null) err.println(wrapText(message, MAX_LINE_WIDTH));
        ret = 1;
      } finally
      {
        if (conn != null)
        {
          try
          {
            conn.close(null);
          }
          catch (Throwable t)
          {
            // Ignore.
          }
View Full Code Here

TOP

Related Classes of org.nasutekds.server.tools.LDAPConnection

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.