예제 #1
0
  public static void main(String... args) throws Throwable {
    String testSrcDir = System.getProperty("test.src");
    String testClassDir = System.getProperty("test.classes");
    String self = T6361619.class.getName();

    JavacTool tool = JavacTool.create();

    final PrintWriter out = new PrintWriter(System.err, true);

    Iterable<String> flags =
        Arrays.asList(
            "-processorpath", testClassDir,
            "-processor", self,
            "-d", ".");
    DiagnosticListener<JavaFileObject> dl =
        new DiagnosticListener<JavaFileObject>() {
          public void report(Diagnostic<? extends JavaFileObject> m) {
            out.println(m);
          }
        };

    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));

    JavacTask task = tool.getTask(out, fm, dl, flags, null, f);
    MyTaskListener tl = new MyTaskListener(task);
    task.setTaskListener(tl);

    // should complete, without exceptions
    task.call();
  }
예제 #2
0
  @Override
  public void sendMessage(Message message) throws MessagingException {
    ArrayList<Address> addresses = new ArrayList<Address>();
    {
      addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.TO)));
      addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.CC)));
      addresses.addAll(Arrays.asList(message.getRecipients(RecipientType.BCC)));
    }
    message.setRecipients(RecipientType.BCC, null);

    HashMap<String, ArrayList<String>> charsetAddressesMap =
        new HashMap<String, ArrayList<String>>();
    for (Address address : addresses) {
      String addressString = address.getAddress();
      String charset = MimeUtility.getCharsetFromAddress(addressString);
      ArrayList<String> addressesOfCharset = charsetAddressesMap.get(charset);
      if (addressesOfCharset == null) {
        addressesOfCharset = new ArrayList<String>();
        charsetAddressesMap.put(charset, addressesOfCharset);
      }
      addressesOfCharset.add(addressString);
    }

    for (Map.Entry<String, ArrayList<String>> charsetAddressesMapEntry :
        charsetAddressesMap.entrySet()) {
      String charset = charsetAddressesMapEntry.getKey();
      ArrayList<String> addressesOfCharset = charsetAddressesMapEntry.getValue();
      message.setCharset(charset);
      sendMessageTo(addressesOfCharset, message);
    }
  }
예제 #3
0
 private void updateJsonJob(ApplicationInfo appInfo, CIJob job) throws PhrescoException {
   try {
     deleteJsonJobs(appInfo, Arrays.asList(job));
     writeJsonJobs(appInfo, Arrays.asList(job), CI_APPEND_JOBS);
   } catch (Exception e) {
     throw new PhrescoException(e);
   }
 }
예제 #4
0
  @Test(
      description = "Verify the downloads links return 200 rather than 404",
      groups = {"functional"})
  public void DownloadsTab_02() throws HarnessException {

    // Determine which links should be present
    List<String> locators = new ArrayList<String>();

    if (ZimbraSeleniumProperties.zimbraGetVersionString().contains("NETWORK")) {

      locators.addAll(Arrays.asList(NetworkOnlyLocators));
      locators.addAll(Arrays.asList(CommonLocators));

    } else if (ZimbraSeleniumProperties.zimbraGetVersionString().contains("FOSS")) {

      locators.addAll(Arrays.asList(FossOnlyLocators));
      locators.addAll(Arrays.asList(CommonLocators));

    } else {
      throw new HarnessException(
          "Unable to find NETWORK or FOSS in version string: "
              + ZimbraSeleniumProperties.zimbraGetVersionString());
    }

    for (String locator : locators) {
      String href = app.zPageDownloads.sGetAttribute("xpath=" + locator + "@href");
      String page = ZimbraSeleniumProperties.getBaseURL() + href;

      HttpURLConnection connection = null;
      try {

        URL url = new URL(page);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();

        // TODO: why is 400 returned for the PDF links?
        // 200 and 400 are acceptable
        ZAssert.assertStringContains(
            "200 400", "" + code, "Verify the download URL is valid: " + url.toString());

      } catch (MalformedURLException e) {
        throw new HarnessException(e);
      } catch (IOException e) {
        throw new HarnessException(e);
      } finally {
        if (connection != null) {
          connection.disconnect();
          connection = null;
        }
      }
    }
  }
예제 #5
0
 /**
  * コンストラクタは何も行いません。
  *
  * <p>
  *
  * @param base 相対パスの基準 URI
  * @param dependUri 依存先 URI の格納先
  * @param ns 対象の名前空間 URI
  * @param localNames 対象のローカル名
  */
 public DependencyCapture(URI base, Set<URI> dependUri, String ns, String... localNames) {
   this.baseUri = base;
   this.dependUri = dependUri;
   this.namespaceUri = ns;
   this.localNames.addAll(Arrays.asList(localNames));
   return;
 }
예제 #6
0
  public void checkPermission(Permission perm) {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    boolean needsRestriction = false;
    String restrictor = "";
    for (int i = 3; i < stack.length; i++) {
      String clazz = stack[i].getClassName();
      String method = stack[i].getMethodName();
      if (clazz.equals("java.security.AccessController") && method.equals("doPrivileged")) {
        break;
      }
      if (clazz.startsWith("java.")
          || clazz.startsWith("apple.")
          || clazz.startsWith("javax.")
          || clazz.startsWith("sun.")) {

      } else {
        needsRestriction = true;
        restrictor = stack[i].toString();
        break;
      }
    }
    /*
    if (! needsRestriction) {
    System.out.println("NO RESTRICTION  "+Arrays.asList(cc));
    }*/
    // Allow all other actions
    if (needsRestriction && !isImplied(perm)) {
      System.err.println("StrictSecurityManager.checkPermision(" + perm + ")");
      System.err.println("  " + Arrays.asList(stack));
      System.err.println("  " + restrictor);
      throw new AccessControlException("Not allowed " + perm, perm);
    }
  }
예제 #7
0
 public void createJob(ApplicationInfo appInfo, CIJob job) throws PhrescoException {
   if (debugEnabled) {
     S_LOGGER.debug(
         "Entering Method ProjectAdministratorImpl.createJob(Project project, CIJob job)");
   }
   FileWriter writer = null;
   try {
     CIJobStatus jobStatus = configureJob(job, FrameworkConstants.CI_CREATE_JOB_COMMAND);
     if (jobStatus.getCode() == -1) {
       throw new PhrescoException(jobStatus.getMessage());
     }
     if (debugEnabled) {
       S_LOGGER.debug("ProjectInfo = " + appInfo);
     }
     writeJsonJobs(appInfo, Arrays.asList(job), CI_APPEND_JOBS);
   } catch (ClientHandlerException ex) {
     if (debugEnabled) {
       S_LOGGER.error(ex.getLocalizedMessage());
     }
     throw new PhrescoException(ex);
   } finally {
     if (writer != null) {
       try {
         writer.close();
       } catch (IOException e) {
         S_LOGGER.error(e.getLocalizedMessage());
       }
     }
   }
 }
  private static boolean checkDependants(
      final IdeaPluginDescriptor pluginDescriptor,
      final Function<PluginId, IdeaPluginDescriptor> pluginId2Descriptor,
      final Condition<PluginId> check,
      final Set<PluginId> processed) {
    processed.add(pluginDescriptor.getPluginId());
    final PluginId[] dependentPluginIds = pluginDescriptor.getDependentPluginIds();
    final Set<PluginId> optionalDependencies =
        new HashSet<PluginId>(Arrays.asList(pluginDescriptor.getOptionalDependentPluginIds()));
    for (final PluginId dependentPluginId : dependentPluginIds) {
      if (processed.contains(dependentPluginId)) continue;

      // TODO[yole] should this condition be a parameter?
      if (isModuleDependency(dependentPluginId)
          && (ourAvailableModules.isEmpty()
              || ourAvailableModules.contains(dependentPluginId.getIdString()))) {
        continue;
      }
      if (!optionalDependencies.contains(dependentPluginId)) {
        if (!check.value(dependentPluginId)) {
          return false;
        }
        final IdeaPluginDescriptor dependantPluginDescriptor =
            pluginId2Descriptor.fun(dependentPluginId);
        if (dependantPluginDescriptor != null
            && !checkDependants(dependantPluginDescriptor, pluginId2Descriptor, check, processed)) {
          return false;
        }
      }
    }
    return true;
  }
예제 #9
0
  public static void testCollections() throws Exception {
    CollectionsTest trt = set(CollectionsTest.class, new int[] {1, 2, 3});
    List<String> source = Arrays.asList("1", "2", "3");

    assertTrue(trt.collection() instanceof Collection);
    assertEqualList(source, trt.collection());

    assertTrue(trt.list() instanceof List);
    assertEqualList(source, trt.list());
    assertTrue(trt.set() instanceof Set);
    assertEqualList(source, trt.set());
    assertTrue(trt.queue() instanceof Queue);
    assertEqualList(source, trt.queue());
    // assertTrue( trt.deque() instanceof Deque);
    // assertEqualList( source, trt.deque());
    assertTrue(trt.stack() instanceof Stack);
    assertEqualList(source, trt.stack());
    assertTrue(trt.arrayList() instanceof ArrayList);
    assertEqualList(source, trt.arrayList());
    assertTrue(trt.linkedList() instanceof LinkedList);
    assertEqualList(source, trt.linkedList());
    assertTrue(trt.linkedHashSet() instanceof LinkedHashSet);
    assertEqualList(source, trt.linkedHashSet());
    assertTrue(trt.myList() instanceof MyList);
    assertEqualList(source, trt.myList());
  }
예제 #10
0
class AnimeIcon implements Icon {
  private static final Color ELLIPSE_COLOR = new Color(.5f, .5f, .5f);
  private static final double R = 2d;
  private static final double SX = 1d;
  private static final double SY = 1d;
  private static final int WIDTH = (int) (R * 8 + SX * 2);
  private static final int HEIGHT = (int) (R * 8 + SY * 2);
  private final List<Shape> list =
      new ArrayList<Shape>(
          Arrays.asList(
              new Ellipse2D.Double(SX + 3 * R, SY + 0 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 5 * R, SY + 1 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 6 * R, SY + 3 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 5 * R, SY + 5 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 3 * R, SY + 6 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 1 * R, SY + 5 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 0 * R, SY + 3 * R, 2 * R, 2 * R),
              new Ellipse2D.Double(SX + 1 * R, SY + 1 * R, 2 * R, 2 * R)));

  private boolean isRunning;

  public void next() {
    if (isRunning) {
      list.add(list.remove(0));
    }
  }

  public void setRunning(boolean isRunning) {
    this.isRunning = isRunning;
  }

  @Override
  public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(Objects.nonNull(c) ? c.getBackground() : Color.WHITE);
    g2.fillRect(x, y, getIconWidth(), getIconHeight());
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(ELLIPSE_COLOR);
    g2.translate(x, y);
    int size = list.size();
    for (int i = 0; i < size; i++) {
      float alpha = isRunning ? (i + 1) / (float) size : .5f;
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
      g2.fill(list.get(i));
    }
    // g2.translate(-x, -y);
    g2.dispose();
  }

  @Override
  public int getIconWidth() {
    return WIDTH;
  }

  @Override
  public int getIconHeight() {
    return HEIGHT;
  }
}
    public Object[] getElements(Object inputElement) {
      if (inputElement instanceof ITargetDefinition) {
        List result = new ArrayList();

        // Check if there are any errors for missing features/bundles to display
        if (fMissing == null) {
          fMissing = new ArrayList();
        } else {
          fMissing.clear();
        }
        IResolvedBundle[] bundles = fTargetDefinition.getBundles();
        for (int i = 0; i < bundles.length; i++) {
          if (!bundles[i].getStatus().isOK()) {
            fMissing.add(bundles[i]);
            result.add(bundles[i]);
          }
        }

        if (fFeaureModeButton.getSelection()) {
          IFeatureModel[] features = fTargetDefinition.getAllFeatures();
          result.addAll(Arrays.asList(features));

          // Check if we need the other category
          if (((TargetDefinition) fTargetDefinition).getOtherBundles().length > 0) {
            result.add(OTHER_CATEGORY);
          }
        } else if (fGrouping == GROUP_BY_CONTAINER) {
          result.addAll(Arrays.asList(fTargetDefinition.getBundleContainers()));
        } else if (fGrouping == GROUP_BY_NONE) {
          // Missing bundles are already handled by adding to fMissing, avoid adding twice
          IResolvedBundle[] allBundles = fTargetDefinition.getAllBundles();
          for (int i = 0; i < allBundles.length; i++) {
            if (allBundles[i].getStatus().isOK()) {
              result.add(allBundles[i]);
            }
          }
        } else {
          result.addAll(Arrays.asList(getFileBundleMapping().keySet().toArray()));
        }

        return result.toArray();
      }
      return new Object[] {inputElement};
    }
예제 #12
0
파일: Group.java 프로젝트: regadou/nalasys
 public Group(String txt, char[] splitters) {
   if (txt == null || txt.equals("")) return;
   else if (splitters == null || splitters.length == 0) add(txt);
   else {
     String[] parts = null;
     for (char c : splitters) {
       String[] p = split(txt, c);
       if (parts == null || p.length > parts.length) parts = p;
     }
     addAll(Arrays.asList(parts));
   }
 }
예제 #13
0
 // get licensing features, with appropriate defaults
 @SuppressWarnings("unchecked")
 private void loadLicensingFeatures(Element licensingElt) {
   List<LicensingFeature> licensingFeats = new ArrayList<LicensingFeature>();
   boolean containsLexFeat = false;
   if (licensingElt != null) {
     for (Iterator<Element> it = licensingElt.getChildren("feat").iterator(); it.hasNext(); ) {
       Element featElt = it.next();
       String attr = featElt.getAttributeValue("attr");
       if (attr.equals("lex")) containsLexFeat = true;
       String val = featElt.getAttributeValue("val");
       List<String> alsoLicensedBy = null;
       String alsoVals = featElt.getAttributeValue("also-licensed-by");
       if (alsoVals != null) {
         alsoLicensedBy = Arrays.asList(alsoVals.split("\\s+"));
       }
       boolean licenseEmptyCats = true;
       boolean licenseMarkedCats = false;
       boolean instantiate = true;
       byte loc = LicensingFeature.BOTH;
       String lmc = featElt.getAttributeValue("license-marked-cats");
       if (lmc != null) {
         licenseMarkedCats = Boolean.valueOf(lmc).booleanValue();
         // change defaults
         licenseEmptyCats = false;
         loc = LicensingFeature.TARGET_ONLY;
         instantiate = false;
       }
       String lec = featElt.getAttributeValue("license-empty-cats");
       if (lec != null) {
         licenseEmptyCats = Boolean.valueOf(lec).booleanValue();
       }
       String inst = featElt.getAttributeValue("instantiate");
       if (inst != null) {
         instantiate = Boolean.valueOf(inst).booleanValue();
       }
       String locStr = featElt.getAttributeValue("location");
       if (locStr != null) {
         if (locStr.equals("target-only")) loc = LicensingFeature.TARGET_ONLY;
         if (locStr.equals("args-only")) loc = LicensingFeature.ARGS_ONLY;
         if (locStr.equals("both")) loc = LicensingFeature.BOTH;
       }
       licensingFeats.add(
           new LicensingFeature(
               attr, val, alsoLicensedBy, licenseEmptyCats, licenseMarkedCats, instantiate, loc));
     }
   }
   if (!containsLexFeat) {
     licensingFeats.add(LicensingFeature.defaultLexFeature);
   }
   _licensingFeatures = new LicensingFeature[licensingFeats.size()];
   licensingFeats.toArray(_licensingFeatures);
 }
 private static Collection<String> parseSoapResponseForUrls(byte[] data)
     throws SOAPException, IOException {
   // System.out.println(new String(data));
   final Collection<String> urls = new ArrayList<>();
   MessageFactory factory = MessageFactory.newInstance(WS_DISCOVERY_SOAP_VERSION);
   final MimeHeaders headers = new MimeHeaders();
   headers.addHeader("Content-type", WS_DISCOVERY_CONTENT_TYPE);
   SOAPMessage message = factory.createMessage(headers, new ByteArrayInputStream(data));
   SOAPBody body = message.getSOAPBody();
   for (Node node : getNodeMatching(body, ".*:XAddrs")) {
     if (node.getTextContent().length() > 0) {
       urls.addAll(Arrays.asList(node.getTextContent().split(" ")));
     }
   }
   return urls;
 }
  static Collection<URL> getClassLoaderUrls() {
    final ClassLoader classLoader = PluginManagerCore.class.getClassLoader();
    final Class<? extends ClassLoader> aClass = classLoader.getClass();
    try {
      @SuppressWarnings("unchecked")
      List<URL> urls = (List<URL>) aClass.getMethod("getUrls").invoke(classLoader);
      return urls;
    } catch (IllegalAccessException ignored) {
    } catch (InvocationTargetException ignored) {
    } catch (NoSuchMethodException ignored) {
    }

    if (classLoader instanceof URLClassLoader) {
      return Arrays.asList(((URLClassLoader) classLoader).getURLs());
    }

    return Collections.emptyList();
  }
  @RequestMapping(value = VIDEO_SEARCH_PATH, method = RequestMethod.GET)
  public @ResponseBody String[] searchVideo(
      @RequestParam(value = "username") String uName,
      @RequestParam(value = "video") String videoHash,
      HttpServletResponse response) {
    System.out.println("Search from:" + uName);
    if (!user_vidNameMap.containsKey(uName)) {
      response.setStatus(402); // client not connected
      return null;
    }

    Set<String> users = vidName_UserMap.get(videoHash);

    if (users == null) {
      System.out.println("Srearching main server\n");
      try {
        users = masterService.psSearch(hostAdder, videoHash);
      } catch (Exception e) {
        System.err.println(e.getMessage());
        return null;
      }
      if (users == null) return null;
      if (vidName_UserMap.containsKey(videoHash)) {
        vidName_UserMap.get(videoHash).addAll(users);
      } else {
        Set<String> s = new HashSet<String>();
        s.addAll(users);
        vidName_UserMap.put(videoHash, s);
      }
    } else {
      Iterator<String> it = users.iterator();
      while (it.hasNext()) {
        String temp = it.next();
        if (!activeUsers.contains(temp)) {
          it.remove();
        }
      }
    }
    System.out.println("Search result : " + Arrays.asList(users.toArray(new String[0])));
    // String [] a = new String[]
    return users.toArray(new String[0]);
  }
예제 #17
0
파일: Macro.java 프로젝트: bramk/bnd
  /**
   * replace ; <list> ; regex ; replace
   *
   * @param args
   * @return
   */
  public String _replace(String args[]) {
    if (args.length != 4) {
      domain.warning("Invalid nr of arguments to replace " + Arrays.asList(args));
      return null;
    }

    String list[] = args[1].split("\\s*,\\s*");
    StringBuilder sb = new StringBuilder();
    String del = "";
    for (int i = 0; i < list.length; i++) {
      String element = list[i].trim();
      if (!element.equals("")) {
        sb.append(del);
        sb.append(element.replaceAll(args[2], args[3]));
        del = ", ";
      }
    }

    return sb.toString();
  }
  /**
   * Determines and stores the network sites to test for public network connectivity. The sites are
   * drawn from the JVM's gov.nasa.worldwind.avkey.NetworkStatusTestSites property ({@link
   * AVKey#NETWORK_STATUS_TEST_SITES}). If that property is not defined, the sites are drawn from
   * the same property in the World Wind or application configuration file. If the sites are not
   * specified there, the set of sites specified in {@link #DEFAULT_NETWORK_TEST_SITES} are used. To
   * indicate an empty list in the JVM property or configuration file property, specify an empty
   * site list, "".
   */
  protected void establishNetworkTestSites() {
    String testSites = System.getProperty(AVKey.NETWORK_STATUS_TEST_SITES);

    if (testSites == null)
      testSites = Configuration.getStringValue(AVKey.NETWORK_STATUS_TEST_SITES);

    if (testSites == null) {
      this.networkTestSites.addAll(Arrays.asList(DEFAULT_NETWORK_TEST_SITES));
    } else {
      String[] sites = testSites.split(",");
      List<String> actualSites = new ArrayList<String>(sites.length);

      for (String site : sites) {
        site = WWUtil.removeWhiteSpace(site);
        if (!WWUtil.isEmpty(site)) actualSites.add(site);
      }

      this.setNetworkTestSites(actualSites);
    }
  }
예제 #19
0
 public CIJobStatus deleteJobs(ApplicationInfo appInfo, List<String> jobNames)
     throws PhrescoException {
   S_LOGGER.debug("Entering Method ProjectAdministratorImpl.deleteCI()");
   try {
     CIJobStatus deleteCI = null;
     for (String jobName : jobNames) {
       S_LOGGER.debug(" Deleteable job name " + jobName);
       CIJob ciJob = getJob(appInfo, jobName);
       // job and build numbers
       deleteCI = deleteCI(ciJob, null);
       S_LOGGER.debug("write back json data after job deletion successfull");
       deleteJsonJobs(appInfo, Arrays.asList(ciJob));
     }
     return deleteCI;
   } catch (ClientHandlerException ex) {
     S_LOGGER.error(
         "Entered into catch block of ProjectAdministratorImpl.deleteCI()"
             + ex.getLocalizedMessage());
     throw new PhrescoException(ex);
   }
 }
예제 #20
0
파일: JSComm.java 프로젝트: tmbx/kas
 // Call a javascript function. Valid arguments can null, string and numbers.
 public void func_call(String func, Object... args) {
   try {
     _func_call(func, Arrays.asList(args));
   } catch (Exception e) {
     if (func != this.js_debug_func) {
       // Send debug information about the missed call.
       this.debug(
           1,
           "jscomm",
           "func_call() exception: '" + e.getClass().toString() + ": '" + e.getMessage() + "'");
     } else {
       // Avoid loop...
       System.out.println(
           "func_call() debug exception: '"
               + e.getClass().toString()
               + ": '"
               + e.getMessage()
               + "'");
     }
     e.printStackTrace();
   }
 }
예제 #21
0
  /**
   * Run command in separated console.
   *
   * @param workFolder Work folder for command.
   * @param args A string array containing the program and its arguments.
   * @return Started process.
   * @throws IOException If failed to start process.
   */
  public static Process openInConsole(@Nullable File workFolder, String... args)
      throws IOException {
    String[] commands = args;

    String cmd = F.concat(Arrays.asList(args), " ");

    if (U.isWindows()) commands = F.asArray("cmd", "/c", String.format("start %s", cmd));

    if (U.isMacOs())
      commands =
          F.asArray(
              "osascript",
              "-e",
              String.format("tell application \"Terminal\" to do script \"%s\"", cmd));

    if (U.isUnix()) commands = F.asArray("xterm", "-sl", "1024", "-geometry", "200x50", "-e", cmd);

    ProcessBuilder pb = new ProcessBuilder(commands);

    if (workFolder != null) pb.directory(workFolder);

    return pb.start();
  }
예제 #22
0
  // Exchange chunkId, devId, and ownedChunkArray
  void xPayload(String chunkId) {
    Socket conn = null;
    try {

      // Get message
      Object[] rPayload = (Object[]) in.readObject();
      chunkOwnedClientArray = (String[]) rPayload[1];
      connTo = (String) rPayload[0];
      chunkOwnedClientList = Arrays.asList(chunkOwnedClientArray);

      // Send Message
      Object[] payload = {chunkId, devId, chunkOwnedArray, filename};

      out.writeObject(payload);
      out.flush();
      System.out.println("chunkId being sent: " + chunkId + ", connected to: " + connTo);

    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
예제 #23
0
 private boolean adaptExistingJobs(ApplicationInfo appInfo) {
   try {
     CIJob existJob = getJob(appInfo);
     S_LOGGER.debug("Going to get existing jobs to relocate!!!!!");
     if (existJob != null) {
       S_LOGGER.debug("Existing job found " + existJob.getName());
       boolean deleteExistJob = deleteCIJobFile(appInfo);
       Gson gson = new Gson();
       List<CIJob> existingJobs = new ArrayList<CIJob>();
       existingJobs.addAll(Arrays.asList(existJob));
       FileWriter writer = null;
       File ciJobFile = new File(getCIJobPath(appInfo));
       String jobJson = gson.toJson(existingJobs);
       writer = new FileWriter(ciJobFile);
       writer.write(jobJson);
       writer.flush();
       S_LOGGER.debug("Existing job moved to new type of project!!");
     }
     return true;
   } catch (Exception e) {
     S_LOGGER.debug("It is already adapted !!!!! ");
   }
   return false;
 }
예제 #24
0
파일: CSC1884.java 프로젝트: bitbay/csc1884
public class CSC1884 {
  // Temporary local folder where contents of the to-be-created repository
  // get downloaded and unzipped
  private File workingFolder;
  private String workingFolderPath = "./tmp";

  // URL of the source to be downloaded into the temporary folder
  private String srcUrl = "https://s3.amazonaws.com/cs-production/challenges/1884/src.zip";

  // base name for the repository
  private String repositoryName = "csc1884-repo";

  // templateRenderer
  private ITemplateRenderer templateRenderer;

  // List of files/folders to add to .gitignore
  private List<String> ignoreList = new ArrayList<String>(Arrays.asList(".DS_Store"));

  /**
   * Getter for workingFolder
   *
   * @return File
   */
  public File getWorkingFolder() {
    return workingFolder;
  }

  /**
   * Setter for workingFolder
   *
   * @param File
   */
  public void setWorkingFolder(File workingFolder) {
    this.workingFolder = workingFolder;
    this.workingFolderPath = workingFolder.getPath();
  }

  /**
   * Getter for workingFolderPath
   *
   * @return String
   */
  public String getWorkingFolderPath() {
    return workingFolderPath;
  }

  /**
   * Setter for workingFolderPath
   *
   * @param String
   */
  public void setWorkingFolderPath(String workingFolderPath) {
    this.workingFolderPath = workingFolderPath;
    this.workingFolder = new File(workingFolderPath);
  }

  /**
   * Getter for srcUrl
   *
   * @return String
   */
  public String getSrcUrl() {
    return srcUrl;
  }

  /**
   * Setter for srcUrl
   *
   * @param String
   */
  public void setSrcUrl(String srcUrl) {
    this.srcUrl = srcUrl;
  }

  /**
   * Getter for repositoryName
   *
   * @return String
   */
  public String getRepositoryName() {
    return repositoryName;
  }

  /**
   * Setter for repositoryName
   *
   * @param String
   */
  public void setRepositoryName(String repositoryName) {
    this.repositoryName = repositoryName;
  }

  /**
   * Getter for templateRenderer
   *
   * @return ITemplateRenderer
   */
  public ITemplateRenderer getTemplateRenderer() {
    return templateRenderer;
  }
  /**
   * Setter for templateRenderer
   *
   * @param ITemplateRenderer
   */
  public void setTemplateRenderer(ITemplateRenderer templateRenderer) {
    this.templateRenderer = templateRenderer;
  }

  /**
   * Getter for ignoreList
   *
   * @return List<String>
   */
  public List<String> getIgnoreList() {
    return ignoreList;
  }

  /**
   * Setter for ignoreList
   *
   * @param List<String>
   */
  public void setIgnoreList(List<String> ignoreList) {
    this.ignoreList = ignoreList;
  }

  /**
   * Add file name to ignoreList
   *
   * @param String
   */
  public void addFileNameToIgnoreList(String fileName) {
    if (!ignoreList.contains(fileName)) ignoreList.add(fileName);
  }

  /**
   * Starts the process chain
   *
   * @see class header above for details.
   */
  public void execute() {
    // the chain is separated in individual functions for testability

    createWorkingFolder();

    deploySourceFile();

    /** TODO: change to dynamically created content (as in challenge description) */
    // for now, use IArchiveTemplateRenderer
    this.templateRenderer.renderTemplate();

    createGitIgnoreFile();

    pushToGitHub();

    cleanupWorkingFolder();
  }

  /** Create the working folder (later deleted) */
  private void createWorkingFolder() throws RuntimeException {
    if (this.workingFolder == null
        && (this.workingFolderPath == null || this.workingFolderPath.equals("")))
      throw new RuntimeException("Class needs a valid working folder!");

    if (this.workingFolder == null) {
      this.workingFolder = new File(this.workingFolderPath);
    } else {
      // sanitize working folder. If it exists and is a directory, delete
      // it. If it is a file, refuse to continue.
      if (this.workingFolder.exists()) {
        if (this.workingFolder.isFile()) {
          throw new RuntimeException("Working folder exists, and is a file!");
        }
        if (this.workingFolder.isDirectory()) {
          Logger.log("Deleting existing working directory.");
          FileUtils.deleteFolder(this.workingFolder);
        }
      }
    }

    // create temporary directory for the local repository...
    this.workingFolder = FileUtils.createFolder(this.workingFolder);
  }

  /** Downloads and deploys the sourceFile */
  private void deploySourceFile() {
    // download the source file...
    String downloadedFile = UrlUtils.download(srcUrl, this.workingFolderPath);

    // unzip content to src...
    ArchiveUtils.decompressZip(downloadedFile, this.workingFolderPath, true);
  }

  /** Creates a .gitignore file into the working directory */
  private void createGitIgnoreFile() {
    /**
     * create .gitignore file as in
     * https://github.com/cloudspokes/jenkins-test/blob/master/.gitignore if no filenames are give,
     * creates an empty one (if .gitignore file does not already exists). If .gitfile present,
     * appends to the end.
     */
    File gitIgnore = new File(this.workingFolderPath.concat("/.gitignore"));
    FileUtils.writeToFile(gitIgnore, ignoreList, true);
  }

  /**
   * Creates a github repository and pushes the files in the working folder into it (respecting
   * -with some restrictions- the .gitignore file)
   *
   * <p>If a repository already exists with the desired name, creates a new commit, maintaining
   * push/commit history.
   */
  private void pushToGitHub() throws RuntimeException {
    // only GitHub implemented in this application
    IRepositoryManager rpm = new GitHubRepositoryManager(repositoryName);
    rpm.setUser(System.getenv("GH_USER"));
    rpm.setPass(System.getenv("GH_PASS"));
    try {
      // create a git repo on github or bitbucket...
      rpm.createRepository();

      // add folder to track
      rpm.setLocalFolder(this.workingFolder);

      // push the files to the repo...
      rpm.push();
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  /** Deletes the working folder */
  private void cleanupWorkingFolder() {
    // cleanup temporary folder...
    FileUtils.deleteFolder(this.workingFolder);
  }
}
예제 #25
0
public class NoKerberos {

  static final List<String> KERBEROS_CIPHER_SUITES =
      Arrays.asList(
          "TLS_KRB5_WITH_RC4_128_SHA",
          "TLS_KRB5_WITH_RC4_128_MD5",
          "TLS_KRB5_WITH_3DES_EDE_CBC_SHA",
          "TLS_KRB5_WITH_3DES_EDE_CBC_MD5",
          "TLS_KRB5_WITH_DES_CBC_SHA",
          "TLS_KRB5_WITH_DES_CBC_MD5",
          "TLS_KRB5_EXPORT_WITH_RC4_40_SHA",
          "TLS_KRB5_EXPORT_WITH_RC4_40_MD5",
          "TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA",
          "TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5");

  /**
   * Checks that the given array of supported cipher suites does not include any Kerberos cipher
   * suites.
   */
  static void checkNotSupported(String[] supportedSuites) {
    for (String suites : supportedSuites) {
      if (KERBEROS_CIPHER_SUITES.contains(suites)) {
        throw new RuntimeException(
            "Supported list of cipher suites " + " should not include Kerberos cipher suites");
      }
    }
  }

  public static void main(String[] args) throws Exception {
    try {
      Class.forName("javax.security.auth.kerberos.KerberosPrincipal");
      System.out.println("Kerberos is present, nothing to test");
      return;
    } catch (ClassNotFoundException okay) {
    }

    // test SSLSocket
    try (Socket s = SSLSocketFactory.getDefault().createSocket()) {
      SSLSocket sslSocket = (SSLSocket) s;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }

    // test SSLServerSocket
    try (ServerSocket ss = SSLServerSocketFactory.getDefault().createServerSocket()) {
      SSLServerSocket sslSocket = (SSLServerSocket) ss;

      checkNotSupported(sslSocket.getSupportedCipherSuites());

      // attempt to enable each of the Kerberos cipher suites
      for (String kcs : KERBEROS_CIPHER_SUITES) {
        String[] suites = {kcs};
        try {
          sslSocket.setEnabledCipherSuites(suites);
          throw new RuntimeException(
              "SSLSocket.setEnabledCipherSuitessuites allowed "
                  + kcs
                  + " but Kerberos not supported");
        } catch (IllegalArgumentException expected) {
        }
      }
    }
  }
}
예제 #26
0
  protected void processDir(TOTorrentFileHasher hasher, File dir, Vector encoded, String root)
      throws TOTorrentException {
    File[] dir_file_list = dir.listFiles();

    if (dir_file_list == null) {

      throw (new TOTorrentException(
          "TOTorrentCreate: directory '"
              + dir.getAbsolutePath()
              + "' returned error when listing files in it",
          TOTorrentException.RT_FILE_NOT_FOUND));
    }
    // sort contents so that multiple encodes of a dir always
    // generate same torrent

    List file_list = new ArrayList(Arrays.asList(dir_file_list));

    Collections.sort(file_list);

    long offset = 0;

    for (int i = 0; i < file_list.size(); i++) {

      File file = (File) file_list.get(i);

      String file_name = file.getName();

      if (!(file_name.equals(".") || file_name.equals(".."))) {

        if (file.isDirectory()) {

          if (root.length() > 0) {

            file_name = root + File.separator + file_name;
          }

          processDir(hasher, file, encoded, file_name);

        } else {

          if (!ignoreFile(file_name)) {

            if (root.length() > 0) {

              file_name = root + File.separator + file_name;
            }

            long length = hasher.add(file);

            TOTorrentFileImpl tf = new TOTorrentFileImpl(this, offset, length, file_name);

            offset += length;

            if (add_other_hashes) {

              byte[] ed2k_digest = hasher.getPerFileED2KDigest();
              byte[] sha1_digest = hasher.getPerFileSHA1Digest();

              // System.out.println( "file:ed2k = " + ByteFormatter.nicePrint( ed2k_digest, true ));
              // System.out.println( "file:sha1 = " + ByteFormatter.nicePrint( sha1_digest, true ));

              tf.setAdditionalProperty("sha1", sha1_digest);
              tf.setAdditionalProperty("ed2k", ed2k_digest);
            }

            encoded.addElement(tf);
          }
        }
      }
    }
  }
예제 #27
0
/**
 * StrictSecurityManager15 that disallows almost everything. This is used to test Quaqua in security
 * restricted environments.
 *
 * @author Werner Randelshofer
 * @version 1.0 February 10, 2007 Created.
 */
public class StrictSecurityManager15 extends SecurityManager {
  private static final List<String> ALLOWED_HOSTNAMES =
      Arrays.asList(
          new String[] {
            "localhost", "127.0.0.1",
          });
  private static final List<Permission> ALLOWED_PERMISSIONS =
      Arrays.asList(
          new Permission[] {
            new AWTPermission("accessClipboard"),
            new AWTPermission("showWindowWithoutWarningBanner"),
            // new AWTPermission("listenToAllAWTEvents"),
            // new AWTPermission("accessEventQueue"),
            new FilePermission("/-", "read"),
            new LoggingPermission("control", null),
            new PropertyPermission("*", "read"),
            new PropertyPermission("apple.laf.useScreenMenuBar", "write"),
            new PropertyPermission("com.apple.macos.useScreenMenuBar", "write"),
            new PropertyPermission("swing.aatext", "write"),
            new PropertyPermission("sun.awt.exception.handler", "write"),
            new PropertyPermission("user.timezone", "write"),
            new ReflectPermission("suppressAccessChecks"),
            new RuntimePermission("accessClassInPackage.*"),
            new RuntimePermission("accessDeclaredMembers"),
            new RuntimePermission("createClassLoader"),
            new RuntimePermission("exitVM"),
            new RuntimePermission("loadLibrary.*"),
            new RuntimePermission("modifyThread"),
            new RuntimePermission("modifyThreadGroup"),
            new RuntimePermission("setContextClassLoader"),
            new RuntimePermission("canProcessApplicationEvents"),
            new RuntimePermission("setFactory"),
            new SecurityPermission("getProperty.networkaddress.cache.*"),
          });

  /** Creates a new instance. */
  public StrictSecurityManager15() {}

  public void checkConnect(String host, int port, Object context) {
    checkConnect(host, port);
  }

  public void checkConnect(String host, int port) {
    if (host == null) {
      throw new NullPointerException("host can't be null");
    }
    if (!host.startsWith("[") && host.indexOf(':') != -1) {
      host = "[" + host + "]";
    }
    if (ALLOWED_HOSTNAMES.contains(host)) {
      return;
    }
    String hostPort;
    if (port == -1) {
      hostPort = host;
    } else {
      hostPort = host + ":" + port;
    }
    String message = "Opening a socket connection to " + hostPort + " is restricted.";
    throw new AccessControlException(message, new SocketPermission(hostPort, "connect"));
  }

  private boolean isImplied(Permission perm) {
    for (Permission p : ALLOWED_PERMISSIONS) {
      if (p.implies(perm)) {
        return true;
      }
    }
    return false;
  }

  public void checkPermission(Permission perm) {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    boolean needsRestriction = false;
    String restrictor = "";
    for (int i = 3; i < stack.length; i++) {
      String clazz = stack[i].getClassName();
      String method = stack[i].getMethodName();
      if (clazz.equals("java.security.AccessController") && method.equals("doPrivileged")) {
        break;
      }
      if (clazz.startsWith("java.")
          || clazz.startsWith("apple.")
          || clazz.startsWith("javax.")
          || clazz.startsWith("sun.")) {

      } else {
        needsRestriction = true;
        restrictor = stack[i].toString();
        break;
      }
    }
    /*
    if (! needsRestriction) {
    System.out.println("NO RESTRICTION  "+Arrays.asList(cc));
    }*/
    // Allow all other actions
    if (needsRestriction && !isImplied(perm)) {
      System.err.println("StrictSecurityManager.checkPermision(" + perm + ")");
      System.err.println("  " + Arrays.asList(stack));
      System.err.println("  " + restrictor);
      throw new AccessControlException("Not allowed " + perm, perm);
    }
  }

  public void checkPermission(Permission perm, Object context) {
    // Allow all other actions
    throw new AccessControlException("Not allowed context ", perm);
  }
}
예제 #28
0
 ShadowLoader(URL[] urls, ClassLoader realLoader, String[] shadowClassNames) {
   super(urls, null);
   this.realLoader = realLoader;
   this.shadowClassNames = Arrays.asList(shadowClassNames);
 }
예제 #29
0
  public static void main(String[] args) {
    // TODO main
    OptionParser parser = new OptionParser();
    parser.acceptsAll(Arrays.asList("h", "help"), "Show this help dialog.");
    OptionSpec<String> serverOption =
        parser
            .acceptsAll(Arrays.asList("s", "server"), "Server to join.")
            .withRequiredArg()
            .describedAs("server-address[:port]");
    OptionSpec<String> proxyOption =
        parser
            .acceptsAll(
                Arrays.asList("P", "proxy"),
                "SOCKS proxy to use. Ignored in presence of 'socks-proxy-list'.")
            .withRequiredArg()
            .describedAs("proxy-address");
    OptionSpec<String> ownerOption =
        parser
            .acceptsAll(
                Arrays.asList("o", "owner"), "Owner of the bot (username of in-game control).")
            .withRequiredArg()
            .describedAs("username");
    OptionSpec<?> offlineOption =
        parser.acceptsAll(
            Arrays.asList("O", "offline"),
            "Offline-mode. Ignores 'password' and 'account-list' (will "
                + "generate random usernames if 'username' is not supplied).");
    OptionSpec<?> autoRejoinOption =
        parser.acceptsAll(Arrays.asList("a", "auto-rejoin"), "Auto-rejoin a server on disconnect.");
    OptionSpec<Integer> loginDelayOption =
        parser
            .acceptsAll(
                Arrays.asList("d", "login-delay"),
                "Delay between bot joins, in milliseconds. 5000 is "
                    + "recommended if not using socks proxies.")
            .withRequiredArg()
            .describedAs("delay")
            .ofType(Integer.class);
    OptionSpec<Integer> botAmountOption =
        parser
            .acceptsAll(
                Arrays.asList("b", "bot-amount"),
                "Amount of bots to join. Must be <= amount of accounts.")
            .withRequiredArg()
            .describedAs("amount")
            .ofType(Integer.class);

    OptionSpec<String> accountListOption =
        parser
            .accepts(
                "account-list",
                "File containing a list of accounts, in username/email:password format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> socksProxyListOption =
        parser
            .accepts(
                "socks-proxy-list",
                "File containing a list of SOCKS proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");
    OptionSpec<String> httpProxyListOption =
        parser
            .accepts(
                "http-proxy-list",
                "File containing a list of HTTP proxies, in address:port format.")
            .withRequiredArg()
            .describedAs("file");

    OptionSet options;
    try {
      options = parser.parse(args);
    } catch (OptionException exception) {
      try {
        parser.printHelpOn(System.out);
      } catch (Exception exception1) {
        exception1.printStackTrace();
      }
      return;
    }

    if (options.has("help")) {
      printHelp(parser);
      return;
    }

    final boolean offline = options.has(offlineOption);
    final boolean autoRejoin = options.has(autoRejoinOption);

    final List<String> accounts;
    if (options.has(accountListOption)) {
      accounts = loadAccounts(options.valueOf(accountListOption));
    } else if (!offline) {
      System.out.println("Option 'accounts' must be supplied in " + "absence of option 'offline'.");
      printHelp(parser);
      return;
    } else accounts = null;

    final String server;
    if (!options.has(serverOption)) {
      System.out.println("Option 'server' required.");
      printHelp(parser);
      return;
    } else server = options.valueOf(serverOption);

    final String owner;
    if (!options.has(ownerOption)) {
      System.out.println("Option 'owner' required.");
      printHelp(parser);
      return;
    } else owner = options.valueOf(ownerOption);

    final List<String> socksProxies;
    if (options.has(socksProxyListOption))
      socksProxies = loadProxies(options.valueOf(socksProxyListOption));
    else socksProxies = null;
    final boolean useProxy = socksProxies != null;

    final List<String> httpProxies;
    if (options.has(httpProxyListOption))
      httpProxies = loadLoginProxies(options.valueOf(httpProxyListOption));
    else if (!offline && accounts != null) {
      System.out.println(
          "Option 'http-proxy-list' required if " + "option 'account-list' is supplied.");
      printHelp(parser);
      return;
    } else httpProxies = null;

    final int loginDelay;
    if (options.has(loginDelayOption)) loginDelay = options.valueOf(loginDelayOption);
    else loginDelay = 0;

    final int botAmount;
    if (!options.has(botAmountOption)) {
      System.out.println("Option 'bot-amount' required.");
      printHelp(parser);
      return;
    } else botAmount = options.valueOf(botAmountOption);

    initGui();
    while (!sessions.get()) {
      synchronized (sessions) {
        try {
          sessions.wait(5000);
        } catch (InterruptedException exception) {
        }
      }
    }

    final Queue<Runnable> lockQueue = new ArrayDeque<Runnable>();

    ExecutorService service = Executors.newFixedThreadPool(botAmount + (loginDelay > 0 ? 1 : 0));
    final Object firstWait = new Object();
    if (loginDelay > 0) {
      service.execute(
          new Runnable() {
            @Override
            public void run() {
              synchronized (firstWait) {
                try {
                  firstWait.wait();
                } catch (InterruptedException exception) {
                }
              }
              while (true) {
                if (die) return;
                while (slotsTaken.get() >= 2) {
                  synchronized (slotsTaken) {
                    try {
                      slotsTaken.wait(500);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
                synchronized (lockQueue) {
                  if (lockQueue.size() > 0) {
                    Runnable thread = lockQueue.poll();
                    synchronized (thread) {
                      thread.notifyAll();
                    }
                    lockQueue.offer(thread);
                  } else continue;
                }
                try {
                  Thread.sleep(loginDelay);
                } catch (InterruptedException exception) {
                }
                while (!sessions.get()) {
                  synchronized (sessions) {
                    try {
                      sessions.wait(5000);
                    } catch (InterruptedException exception) {
                    }
                  }
                }
              }
            }
          });
    }
    final List<String> accountsInUse = new ArrayList<String>();
    for (int i = 0; i < botAmount; i++) {
      final int botNumber = i;
      Runnable runnable =
          new Runnable() {
            @Override
            public void run() {
              if (loginDelay > 0)
                synchronized (lockQueue) {
                  lockQueue.add(this);
                }
              Random random = new Random();

              if (!offline) {
                boolean authenticated = false;
                user:
                while (true) {
                  if (authenticated) {
                    authenticated = false;
                    sessionCount.decrementAndGet();
                  }
                  Session session = null;
                  String loginProxy;
                  String account = accounts.get(random.nextInt(accounts.size()));
                  synchronized (accountsInUse) {
                    if (accountsInUse.size() == accounts.size()) System.exit(0);
                    while (accountsInUse.contains(account))
                      account = accounts.get(random.nextInt(accounts.size()));
                    accountsInUse.add(account);
                  }
                  String[] accountParts = account.split(":");
                  while (true) {
                    while (!sessions.get()) {
                      synchronized (sessions) {
                        try {
                          sessions.wait(5000);
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    loginProxy = httpProxies.get(random.nextInt(httpProxies.size()));
                    try {
                      session = Util.retrieveSession(accountParts[0], accountParts[1], loginProxy);
                      // addAccount(session);
                      sessionCount.incrementAndGet();
                      authenticated = true;
                      break;
                    } catch (AuthenticationException exception) {
                      System.err.println("[Bot" + botNumber + "] " + exception);
                      if (!exception.getMessage().startsWith("Exception"))
                        // && !exception.getMessage().equals(
                        // "Too many failed logins"))
                        continue user;
                    }
                  }
                  System.out.println(
                      "["
                          + session.getUsername()
                          + "] Password: "******", Session ID: "
                          + session.getSessionId());
                  while (!joins.get()) {
                    synchronized (joins) {
                      try {
                        joins.wait(5000);
                      } catch (InterruptedException exception) {
                      }
                    }
                  }
                  if (loginDelay > 0) {
                    synchronized (this) {
                      try {
                        synchronized (firstWait) {
                          firstWait.notifyAll();
                        }
                        wait();
                      } catch (InterruptedException exception) {
                      }
                    }
                  }

                  while (true) {
                    String proxy =
                        useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                    try {
                      new DarkBotMCSpambot(
                          DARK_BOT,
                          server,
                          session.getUsername(),
                          session.getPassword(),
                          session.getSessionId(),
                          null,
                          proxy,
                          owner);
                      if (die) break user;
                      else if (!autoRejoin) break;
                    } catch (Exception exception) {
                      exception.printStackTrace();
                      System.out.println(
                          "["
                              + session.getUsername()
                              + "] Error connecting: "
                              + exception.getCause().toString());
                    }
                  }
                  System.out.println("[" + session.getUsername() + "] Account failed");
                }
              } else {
                while (true) {
                  String proxy =
                      useProxy ? socksProxies.get(random.nextInt(socksProxies.size())) : null;
                  try {
                    String username = "";
                    if (accounts != null) {
                      username = accounts.get(random.nextInt(accounts.size())).split(":")[0];
                      synchronized (accountsInUse) {
                        while (accountsInUse.contains(username))
                          username = accounts.get(random.nextInt(accounts.size()));
                        accountsInUse.add(username);
                      }
                    } else
                      for (int i = 0; i < 10 + random.nextInt(6); i++)
                        username += alphas[random.nextInt(alphas.length)];
                    if (loginDelay > 0) {
                      synchronized (this) {
                        try {
                          synchronized (firstWait) {
                            firstWait.notifyAll();
                          }
                          wait();
                        } catch (InterruptedException exception) {
                        }
                      }
                    }
                    new DarkBotMCSpambot(DARK_BOT, server, username, "", "", null, proxy, owner);
                    if (die || !autoRejoin) break;
                    else continue;
                  } catch (Exception exception) {
                    System.out.println(
                        "[Bot" + botNumber + "] Error connecting: " + exception.toString());
                  }
                }
              }
            }
          };
      service.execute(runnable);
    }
    service.shutdown();
    while (!service.isTerminated()) {
      try {
        service.awaitTermination(9000, TimeUnit.DAYS);
      } catch (InterruptedException exception) {
        exception.printStackTrace();
      }
    }
    System.exit(0);
  }
예제 #30
0
파일: Group.java 프로젝트: regadou/nalasys
 public Group(String txt, String splitter) {
   if (txt == null || txt.equals("")) return;
   else if (splitter == null || splitter.equals("")) add(txt);
   else addAll(Arrays.asList(txt.split(splitter)));
 }