Exemplo n.º 1
0
  public String addUser(String login, String password) {
    try {
      File file = new File(ServerSettings.STATISTICS_ROOT + File.separator + type + ".xml");
      if (!file.exists()) {
        return "File doesn't exists: " + file.getAbsolutePath();
      }

      Map<String, String> map = readUsersFromFile();
      if (map == null) {
        return "Impossible to read xml file: " + file.getAbsolutePath();
      }
      if (map.containsKey(login)) {
        return "User already exists";
      }

      Document document = ResponseUtils.getXmlDocument(file);
      if (document == null) {
        return "Impossible to read xml file: " + file.getAbsolutePath();
      }
      NodeList nodeList = document.getElementsByTagName("users");
      Node newNode = document.createElement("user");
      newNode.appendChild(document.createElement("login"));
      newNode.appendChild(document.createTextNode(login));
      newNode.appendChild(document.createElement("password"));
      try {
        password = generateMD5(password);
      } catch (NoSuchAlgorithmException e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
            e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login);
        return "Impossible to generate MD5";
      } catch (UnsupportedEncodingException e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
            e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + login);
        return "Impossible to read password in UTF-8";
      }
      newNode.appendChild(document.createTextNode(password));
      nodeList.item(0).appendChild(newNode);

      NodeList list = document.getElementsByTagName("users");
      Node node = list.item(0);

      DOMSource source = new DOMSource(node);

      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();

      FileWriter writer = new FileWriter(file);
      StreamResult result = new StreamResult(writer);
      transformer.transform(source, result);

      writer.close();
      return "User was added";
    } catch (Throwable e) {
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), "");
      return "Unknown error: User wasn't added";
    }
  }
Exemplo n.º 2
0
  @Nullable
  private Map<String, String> readUsersFromFile() {
    try {
      // TODO add exceptions
      Map<String, String> users = new HashMap<String, String>();

      File file = new File(ServerSettings.STATISTICS_ROOT + File.separator + type + ".xml");
      if (!file.exists()) {
        return null;
      }

      Document document = ResponseUtils.getXmlDocument(file);
      if (document == null) {
        return null;
      }
      NodeList nodeList = document.getElementsByTagName("user");
      if (nodeList == null) {
        return null;
      }
      for (int i = 0; i < nodeList.getLength(); i++) {
        NodeList children = nodeList.item(i).getChildNodes();
        users.put(children.item(1).getTextContent(), children.item(3).getTextContent());
      }
      return users;
    } catch (Throwable e) {
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), "");
    }
    return null;
  }
Exemplo n.º 3
0
  private String getPostDataFromRequest(HttpExchange exchange) {
    StringBuilder reqResponse = new StringBuilder();
    try {
      reqResponse.append(ResponseUtils.readData(exchange.getRequestBody()));
    } catch (IOException e) {
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap: " + exchange.getRequestURI());
      throw new IllegalArgumentException("Cannot read data from file");
    }

    String finalResponse = null;
    try {
      finalResponse = URLDecoder.decode(reqResponse.toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.AUTHORIZATION.name(), "ldap");
      throw new IllegalArgumentException("Cannot read data from file");
    }
    return finalResponse;
  }
Exemplo n.º 4
0
  private boolean loginWithLDAP(String login, String password) {
    try {

      LdapContext context = null;
      try {
        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.SECURITY_AUTHENTICATION, "Simple");
        env.put(Context.SECURITY_PRINCIPAL, login);
        //                env.put(Context.SECURITY_PRINCIPAL, "labs\\natalia.ukhorskaya");
        //                env.put(Context.SECURITY_CREDENTIALS, "DeeJou5d");
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.PROVIDER_URL, "ldap://msdc.labs.intellij.net:389");
        context = new InitialLdapContext(env, null);

      } catch (NamingException nex) {
        // nex.printStackTrace();
        return false;
      }

      String cn;
      if (login.contains("\\")) {
        cn = login.substring(login.indexOf("\\"));
      } else {
        cn = login;
      }

      String query = "(&(objectclass=person)(samaccountname=" + cn + "))";
      String attribute = "cn";

      SearchControls ctrl = new SearchControls();
      ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
      NamingEnumeration enumeration = context.search("dc=labs,dc=intellij,dc=net", query, ctrl);
      SearchResult result = (SearchResult) enumeration.next();
      if (result != null) {
        Attributes attribs = result.getAttributes();
        NamingEnumeration values = attribs.get(attribute).getAll();
        if (values.hasMore()) {
          userName = values.next().toString();
        }
        return true;
      }

    } catch (Throwable e) {
      // incorrect login or password
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, SessionInfo.TypeOfRequest.ANALYZE_LOG.name(), login + " " + password);
    }
    return false;
  }
Exemplo n.º 5
0
 @Override
 public Result authenticate(HttpExchange exchange) {
   String data;
   try {
     data = getPostDataFromRequest(exchange);
   } catch (IllegalArgumentException e) {
     ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
         e,
         SessionInfo.TypeOfRequest.AUTHORIZATION.name(),
         "ldap: " + exchange.getRequestURI().toString());
     return super.authenticate(exchange);
   }
   Pair<String, String> pair = parseData(data);
   if (checkCredentials(pair.first, pair.second)) {
     return new Success(new HttpPrincipal(pair.first, this.getRealm()));
   } else {
     return new Failure(401);
   }
   // To change body of overridden methods use File | Settings | File Templates.
 }
  public String getResult() {
    ErrorAnalyzer analyzer = new ErrorAnalyzer(currentPsiFile, sessionInfo);
    List<ErrorDescriptor> errors;
    try {
      errors = analyzer.getAllErrors();
    } catch (KotlinCoreException e) {
      ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
          e, sessionInfo.getType(), currentPsiFile.getText());
      return ResponseUtils.getErrorWithStackTraceInJson(
          ServerSettings.KOTLIN_ERROR_MESSAGE, e.getStackTraceString());
    }

    if (errors.isEmpty() || isOnlyWarnings(errors)) {
      Project currentProject = currentPsiFile.getProject();
      //            BindingContext bindingContext =
      // AnalyzerFacade.analyzeOneFileWithJavaIntegration(
      //                                (JetFile) currentPsiFile,
      // JetControlFlowDataTraceFactory.EMPTY);

      sessionInfo.getTimeManager().saveCurrentTime();
      GenerationState generationState;
      try {
        generationState = new GenerationState(currentProject, ClassBuilderFactory.BINARIES);
        generationState.compile((JetFile) currentPsiFile);
        //                generationState.compileCorrectFiles(bindingContext,
        // Collections.singletonList((JetFile) currentPsiFile));
      } catch (Throwable e) {
        ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
            e, sessionInfo.getType(), currentPsiFile.getText());
        //
        // ErrorWriterOnServer.LOG_FOR_EXCEPTIONS.error(ErrorWriter.getExceptionForLog(sessionInfo.getType(), e, currentPsiFile.getText()));
        return ResponseUtils.getErrorWithStackTraceInJson(
            ServerSettings.KOTLIN_ERROR_MESSAGE, new KotlinCoreException(e).getStackTraceString());
      }
      ErrorWriterOnServer.LOG_FOR_INFO.info(
          ErrorWriter.getInfoForLogWoIp(
              sessionInfo.getType(),
              sessionInfo.getId(),
              "COMPILE correctNamespaces "
                  + sessionInfo.getTimeManager().getMillisecondsFromSavedTime()));

      StringBuilder stringBuilder = new StringBuilder("Generated classfiles: ");
      stringBuilder.append(ResponseUtils.addNewLine());
      final ClassFileFactory factory = generationState.getFactory();

      sessionInfo.getTimeManager().saveCurrentTime();
      List<String> files = factory.files();
      File outputDir =
          new File(
              ServerSettings.OUTPUT_DIRECTORY + File.separator + "tmp" + RandomUtils.nextInt());
      boolean isOutputExists = true;
      if (!outputDir.exists()) {
        isOutputExists = outputDir.mkdirs();
      }
      for (String file : files) {
        //                File outputDir = new File(ServerSettings.OUTPUT_DIRECTORY);
        //                ServerSettings.OUTPUT_DIRECTORY = outputDir.getAbsolutePath();
        if (isOutputExists) {
          File target = new File(outputDir, file);
          try {
            FileUtil.writeToFile(target, factory.asBytes(file));
            stringBuilder.append(file).append(ResponseUtils.addNewLine());
          } catch (IOException e) {
            ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
                e, sessionInfo.getType(), currentPsiFile.getText());
            return ResponseUtils.getErrorInJson("Cannot get a completion.");
          }
        } else {
          ErrorWriter.ERROR_WRITER.writeExceptionToExceptionAnalyzer(
              new UnsupportedOperationException("Cannot create output directory for files"),
              SessionInfo.TypeOfRequest.DOWNLOAD_LOG.name(),
              currentPsiFile.getText());
          return ResponseUtils.getErrorInJson("Error on server: cannot run your program.");
        }
      }
      ErrorWriterOnServer.LOG_FOR_INFO.info(
          ErrorWriter.getInfoForLogWoIp(
              sessionInfo.getType(),
              sessionInfo.getId(),
              "Write files on disk "
                  + sessionInfo.getTimeManager().getMillisecondsFromSavedTime()));

      JSONArray jsonArray = new JSONArray();
      Map<String, String> map = new HashMap<String, String>();
      map.put("type", "info");
      map.put("text", stringBuilder.toString());
      jsonArray.put(map);

      JavaRunner runner =
          new JavaRunner(files, arguments, jsonArray, currentPsiFile.getText(), sessionInfo);

      return runner.getResult(outputDir.getAbsolutePath());

    } else {
      return generateResponseWithErrors(errors);
    }
  }