public static IdeaPluginDescriptorImpl[] loadDescriptors(@Nullable StartupProgress progress) {
    if (ClassUtilCore.isLoadingOfExternalPluginsDisabled()) {
      return IdeaPluginDescriptorImpl.EMPTY_ARRAY;
    }

    final List<IdeaPluginDescriptorImpl> result = new ArrayList<IdeaPluginDescriptorImpl>();

    int pluginsCount =
        countPlugins(PathManager.getPluginsPath())
            + countPlugins(PathManager.getPreinstalledPluginsPath());
    loadDescriptors(PathManager.getPluginsPath(), result, progress, pluginsCount);
    Application application = ApplicationManager.getApplication();
    boolean fromSources = false;
    if (application == null || !application.isUnitTestMode()) {
      int size = result.size();
      loadDescriptors(PathManager.getPreinstalledPluginsPath(), result, progress, pluginsCount);
      fromSources = size == result.size();
    }

    loadDescriptorsFromProperty(result);

    loadDescriptorsFromClassPath(result, fromSources ? progress : null);

    IdeaPluginDescriptorImpl[] pluginDescriptors =
        result.toArray(new IdeaPluginDescriptorImpl[result.size()]);
    try {
      Arrays.sort(pluginDescriptors, new PluginDescriptorComparator(pluginDescriptors));
    } catch (Exception e) {
      prepareLoadingPluginsErrorMessage(
          IdeBundle.message("error.plugins.were.not.loaded", e.getMessage()));
      getLogger().info(e);
      return findCorePlugin(pluginDescriptors);
    }
    return pluginDescriptors;
  }
Exemplo n.º 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);
    }
  }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
  /**
   * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually
   * should go to struct.
   *
   * @param from
   * @param to
   * @param excludes
   * @return
   * @throws Exception
   */
  public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception {
    Arrays.sort(excludes);
    for (Field f : from.fields()) {
      if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue;

      Object o = f.get(from);
      if (o == null) continue;

      Field tof = to.getField(f.getName());
      if (tof != null)
        try {
          tof.set(to, Converter.cnv(tof.getGenericType(), o));
        } catch (Exception e) {
          System.out.println(
              "Failed to convert "
                  + f.getName()
                  + " from "
                  + from.getClass()
                  + " to "
                  + to.getClass()
                  + " value "
                  + o
                  + " exception "
                  + e);
        }
    }

    return to;
  }
Exemplo n.º 5
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);
   }
 }
Exemplo n.º 6
0
  public Cedars(String args[]) throws ArchiveException, IOException, HoneycombTestException {

    verbose = false;

    parseArgs(args);
    initHCClient(host);

    // generate lists of random sizes around 30M and 3M
    // sort ascending to allow continuous expansion
    try {
      initRandom();
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
    }
    sizes = new long[n_files];
    for (int i = 0; i < sizes.length; i++) {
      sizes[i] = MIN_SIZE + (long) (rand.nextDouble() * (double) RANGE);
    }
    Arrays.sort(sizes);

    sizes2 = new long[n_files];
    for (int i = 0; i < sizes2.length; i++) {
      sizes2[i] = MIN_SIZE2 + (long) (rand.nextDouble() * (double) RANGE2);
    }
    Arrays.sort(sizes2);

    sizes3 = new long[n_files];
    for (int i = 0; i < sizes3.length; i++) {
      sizes3[i] = MIN_SIZE3 + (long) (rand.nextDouble() * (double) RANGE3);
    }
    Arrays.sort(sizes3);

    oids = new String[n_files];
    Arrays.fill(oids, null);
    shas = new String[n_files];
    Arrays.fill(shas, null);

    if (out_file != null) {
      try {
        String host = clnthost;
        fo = new FileWriter(out_file, true); // append=true
        flog("#S Cedars [" + host + "] " + new Date() + "\n");
      } catch (Exception e) {
        System.err.println("Opening " + out_file);
        e.printStackTrace();
        System.exit(1);
      }
    }
    Runtime.getRuntime().addShutdownHook(new Thread(new Shutdown(), "Shutdown"));
    doIt();

    done = true;
  }
Exemplo n.º 7
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;
        }
      }
    }
  }
Exemplo n.º 8
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);
    }
  }
Exemplo n.º 9
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;
 }
Exemplo n.º 10
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());
       }
     }
   }
 }
Exemplo n.º 11
0
Arquivo: Macro.java Projeto: bramk/bnd
 private String doCommand(Object target, String method, String[] args) {
   if (target == null) ; // System.err.println("Huh? Target should never be null " +
   // domain);
   else {
     String cname = "_" + method.replaceAll("-", "_");
     try {
       Method m = target.getClass().getMethod(cname, new Class[] {String[].class});
       return (String) m.invoke(target, new Object[] {args});
     } catch (NoSuchMethodException e) {
       // Ignore
     } catch (InvocationTargetException e) {
       if (e.getCause() instanceof IllegalArgumentException) {
         domain.error(
             "%s, for cmd: %s, arguments; %s",
             e.getCause().getMessage(), method, Arrays.toString(args));
       } else {
         domain.warning("Exception in replace: %s", e.getCause());
         e.getCause().printStackTrace();
       }
     } catch (Exception e) {
       domain.warning("Exception in replace: " + e + " method=" + method);
       e.printStackTrace();
     }
   }
   return null;
 }
  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;
  }
Exemplo n.º 13
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());
  }
Exemplo n.º 14
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};
    }
Exemplo n.º 16
0
 public void run() {
   try {
     InputStream in;
     OutputStream out;
     try {
       in = sk.getInputStream();
       out = sk.getOutputStream();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
     while (true) {
       try {
         int len = Utils.int32d(read(in, 4), 0);
         if (!auth && (len > 256)) return;
         Message msg = new MessageBuf(read(in, len));
         String cmd = msg.string();
         Object[] args = msg.list();
         Object[] reply;
         if (auth) {
           Command cc = commands.get(cmd);
           if (cc != null) reply = cc.run(this, args);
           else reply = new Object[] {"nocmd"};
         } else {
           if (cmd.equals("nonce")) {
             reply = new Object[] {nonce};
           } else if (cmd.equals("auth")) {
             if (Arrays.equals((byte[]) args[0], ckey)) {
               reply = new Object[] {"ok"};
               auth = true;
             } else {
               reply = new Object[] {"no"};
             }
           } else {
             return;
           }
         }
         MessageBuf rb = new MessageBuf();
         rb.addlist(reply);
         byte[] rbuf = new byte[4 + rb.size()];
         Utils.uint32e(rb.size(), rbuf, 0);
         rb.fin(rbuf, 4);
         out.write(rbuf);
       } catch (IOException e) {
         return;
       }
     }
   } catch (InterruptedException e) {
   } finally {
     try {
       sk.close();
     } catch (IOException e) {
       throw (new RuntimeException(e));
     }
   }
 }
Exemplo n.º 17
0
Arquivo: Macro.java Projeto: bramk/bnd
 public static Properties getParent(Properties p) {
   try {
     Field f = Properties.class.getDeclaredField("defaults");
     f.setAccessible(true);
     return (Properties) f.get(p);
   } catch (Exception e) {
     Field[] fields = Properties.class.getFields();
     System.err.println(Arrays.toString(fields));
     return null;
   }
 }
Exemplo n.º 18
0
 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));
   }
 }
Exemplo n.º 19
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);
 }
Exemplo n.º 20
0
  /**
   * Returns compact class host.
   *
   * @param obj Object to compact.
   * @return String.
   */
  @Nullable
  public static Object compactObject(Object obj) {
    if (obj == null) return null;

    if (obj instanceof Enum) return obj.toString();

    if (obj instanceof String || obj instanceof Boolean || obj instanceof Number) return obj;

    if (obj instanceof Collection) {
      Collection col = (Collection) obj;

      Object[] res = new Object[col.size()];

      int i = 0;

      for (Object elm : col) res[i++] = compactObject(elm);

      return res;
    }

    if (obj.getClass().isArray()) {
      Class<?> arrType = obj.getClass().getComponentType();

      if (arrType.isPrimitive()) {
        if (obj instanceof boolean[]) return Arrays.toString((boolean[]) obj);
        if (obj instanceof byte[]) return Arrays.toString((byte[]) obj);
        if (obj instanceof short[]) return Arrays.toString((short[]) obj);
        if (obj instanceof int[]) return Arrays.toString((int[]) obj);
        if (obj instanceof long[]) return Arrays.toString((long[]) obj);
        if (obj instanceof float[]) return Arrays.toString((float[]) obj);
        if (obj instanceof double[]) return Arrays.toString((double[]) obj);
      }

      Object[] arr = (Object[]) obj;

      int iMax = arr.length - 1;

      StringBuilder sb = new StringBuilder("[");

      for (int i = 0; i <= iMax; i++) {
        sb.append(compactObject(arr[i]));

        if (i != iMax) sb.append(", ");
      }

      sb.append("]");

      return sb.toString();
    }

    return U.compact(obj.getClass().getName());
  }
Exemplo n.º 21
0
  private int compare(Revision a, Revision b) {
    if (Arrays.equals(a._id, b._id)) return 0;

    Version va = getVersion(a);
    Version vb = getVersion(b);
    int n = va.compareTo(vb);
    if (n != 0) return n;

    if (a.created != b.created) return a.created > b.created ? 1 : -1;

    for (int i = 0; i < a._id.length; i++)
      if (a._id[i] != b._id[i]) return a._id[i] > b._id[i] ? 1 : -1;

    return 0;
  }
Exemplo n.º 22
0
 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;
 }
Exemplo n.º 23
0
  /**
   * Concat arrays in one.
   *
   * @param arrays Arrays.
   * @return Summary array.
   */
  public static int[] concat(int[]... arrays) {
    assert arrays != null;
    assert arrays.length > 1;

    int len = 0;

    for (int[] a : arrays) len += a.length;

    int[] r = Arrays.copyOf(arrays[0], len);

    for (int i = 1, shift = 0; i < arrays.length; i++) {
      shift += arrays[i - 1].length;
      System.arraycopy(arrays[i], 0, r, shift, arrays[i].length);
    }

    return r;
  }
Exemplo n.º 24
0
Arquivo: Macro.java Projeto: bramk/bnd
 /**
  * Get the contents of a file.
  *
  * @param in
  * @return
  * @throws IOException
  */
 public String _cat(String args[]) throws IOException {
   verifyCommand(args, "${cat;<in>}, get the content of a file", null, 2, 2);
   File f = domain.getFile(args[1]);
   if (f.isFile()) {
     return IO.collect(f);
   } else if (f.isDirectory()) {
     return Arrays.toString(f.list());
   } else {
     try {
       URL url = new URL(args[1]);
       return IO.collect(url, "UTF-8");
     } catch (MalformedURLException mfue) {
       // Ignore here
     }
     return null;
   }
 }
  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();
  }
Exemplo n.º 26
0
    @Override
    public void run() {

      try {
        // Create a server socket
        // DatagramSocket socket = new DatagramSocket(8000);
        textArea.append("UDP connnection listener started at " + new Date() + '\n');

        // while (true) {

        // The byte array for sending and receiving datagram packets
        byte[] buffer = new byte[BUFFER_SIZE];

        // Initialize buffer for each iteration
        Arrays.fill(buffer, (byte) 0);

        // Create a packet for receiving data
        // DatagramPacket receivePacket = new DatagramPacket(buffer.clone(), buffer.length);

        // Receive radius from the client in a packet
        // socket.receive(receivePacket);

        // Create a new thread for the UDP connection
        HandleUDPClient task =
            new HandleUDPClient(
                new DatagramSocket(8000), new DatagramPacket(buffer.clone(), buffer.length));

        // Start the new thread
        // new Thread(task).start();
        task.run();

        // Increment clientNo
        clientNo++;

        //					break;
        //	        	}
      } catch (BindException ex) {
        // Not supporting multiple UDP clients for now
        textArea.append("Multiple UDP client connections are currently not supported.\n");
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
Exemplo n.º 27
0
  @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]);
  }
  /** Creates an Message through the advance createMessage() method and inspects its parameters. */
  public void testCreateMessage2() {
    String body =
        "This is an IM coming from the tested implementation" + " on " + new Date().toString();
    String contentType = "text/html";
    String encoding = "UTF-16";
    String subject = "test message";
    net.java.sip.communicator.service.protocol.Message msg =
        opSetBasicIM.createMessage(body.getBytes(), contentType, encoding, subject);

    assertEquals("message body", body, msg.getContent());
    assertTrue("message body bytes", Arrays.equals(body.getBytes(), msg.getRawData()));
    assertEquals("message length", body.length(), msg.getSize());
    assertEquals("message content type", contentType, msg.getContentType());
    assertEquals("message encoding", encoding, msg.getEncoding());
    assertNotNull("message uid", msg.getMessageUID());

    // a further test on message uid.
    net.java.sip.communicator.service.protocol.Message msg2 = opSetBasicIM.createMessage(body);
    assertFalse("message uid", msg.getMessageUID().equals(msg2.getMessageUID()));
  }
Exemplo n.º 29
0
Arquivo: Macro.java Projeto: 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();
  }
Exemplo n.º 30
0
 static void displayInfo(NetworkInterface netint) throws IOException {
   inetAddresses = netint.getInterfaceAddresses();
   System.out.println("some information about my link:");
   System.out.printf("Display name: %s\n", netint.getDisplayName());
   System.out.printf("Name: %s\n", netint.getName());
   System.out.printf("Up? %s\n", netint.isUp());
   System.out.printf("Loopback? %s\n", netint.isLoopback());
   System.out.printf("PointToPoint? %s\n", netint.isPointToPoint());
   System.out.printf("Supports multicast? %s\n", netint.supportsMulticast());
   System.out.printf("Virtual? %s\n", netint.isVirtual());
   System.out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress()));
   System.out.printf("MTU: %s\n", netint.getMTU());
   System.out.printf("\n");
   System.out.println(
       "my ip address is: " + ((InterfaceAddress) inetAddresses.get(0)).getAddress());
   System.out.println(
       "the sunnetmask address is: "
           + ((InterfaceAddress) inetAddresses.get(0)).getNetworkPrefixLength());
   System.out.println("the broadcast address of this subnet is:" + bcid);
 }