private int send(FileDescriptor fd, ByteBuffer src, SocketAddress target) throws IOException {
    if (src instanceof DirectBuffer) return sendFromNativeBuffer(fd, src, target);

    // Substitute a native buffer
    int pos = src.position();
    int lim = src.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
    try {
      bb.put(src);
      bb.flip();
      // Do not update src until we see how many bytes were written
      src.position(pos);

      int n = sendFromNativeBuffer(fd, bb, target);
      if (n > 0) {
        // now update src
        src.position(pos + n);
      }
      return n;
    } finally {
      Util.releaseTemporaryDirectBuffer(bb);
    }
  }
示例#2
0
  public void init() {
    String host = util.getHost();
    String bindAddr = util.getBindAddress();
    int port = util.getPort(ListeningContextFace.DEFAULT_TRAP_PORT);
    String socketType = util.getSocketType();
    // String oid = util.getOid();
    String community = util.getCommunity();

    try {
      context = new SnmpContextv2c(host, port, bindAddr, socketType);
      context.setCommunity(community);

      pdu = new TrapPduv2(context);
      pdu.addOid(sysUpTime, new AsnUnsInteger(5));
      pdu.addOid(snmpTrapOID, new AsnObjectId(warmStart));

      System.out.println(pdu.toString());
      pdu.send();

      // when calling destroy, the pdu might not be sent
      // context.destroy();
    } catch (java.io.IOException exc) {
      System.out.println("IOException " + exc.getMessage());
    } catch (uk.co.westhawk.snmp.stack.PduException exc) {
      System.out.println("PduException " + exc.getMessage());
    }
    // System.exit(0);
  }
示例#3
0
 /**
  * Gets the imageicon. If the user has a predefined icon, get that, otherwise get the varian icon.
  *
  * @return the imageicon
  */
 protected ImageIcon getImageIcon() {
   ImageIcon icon = null;
   String strPath = WOperators.getDefIcon();
   if (strPath != null) {
     icon = Util.getImageIcon(strPath);
   }
   if (icon == null) icon = Util.getImageIcon(WOperators.ICON);
   return icon;
 }
示例#4
0
文件: Util.java 项目: gubo/slipwire
 public static void main(final String[] args) {
   try {
     final String encrypted = Util.encrypt("fred flintstone");
     final String decrypted = Util.decrypt(encrypted);
     DBG.m(encrypted + " / " + decrypted);
   } catch (Exception x) {
     DBG.m(x);
   }
 }
示例#5
0
  public static String resolveArtifactParam(Map<String, Object> parameters) throws CoreException {
    String artifactLocation = (String) parameters.get(EclipseTouchpoint.PARM_ARTIFACT_LOCATION);
    if (artifactLocation != null) return artifactLocation;

    IArtifactKey artifactKey = (IArtifactKey) parameters.get(EclipseTouchpoint.PARM_ARTIFACT);
    if (artifactKey == null) {
      IInstallableUnit iu = (IInstallableUnit) parameters.get(EclipseTouchpoint.PARM_IU);
      throw new CoreException(Util.createError(NLS.bind(Messages.iu_contains_no_arifacts, iu)));
    }

    throw new CoreException(
        Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey)));
  }
 public SocketAddress receive(ByteBuffer dst) throws IOException {
   if (dst.isReadOnly()) throw new IllegalArgumentException("Read-only buffer");
   if (dst == null) throw new NullPointerException();
   synchronized (readLock) {
     ensureOpen();
     // Socket was not bound before attempting receive
     if (localAddress() == null) bind(null);
     int n = 0;
     ByteBuffer bb = null;
     try {
       begin();
       if (!isOpen()) return null;
       SecurityManager security = System.getSecurityManager();
       readerThread = NativeThread.current();
       if (isConnected() || (security == null)) {
         do {
           n = receive(fd, dst);
         } while ((n == IOStatus.INTERRUPTED) && isOpen());
         if (n == IOStatus.UNAVAILABLE) return null;
       } else {
         bb = Util.getTemporaryDirectBuffer(dst.remaining());
         for (; ; ) {
           do {
             n = receive(fd, bb);
           } while ((n == IOStatus.INTERRUPTED) && isOpen());
           if (n == IOStatus.UNAVAILABLE) return null;
           InetSocketAddress isa = (InetSocketAddress) sender;
           try {
             security.checkAccept(isa.getAddress().getHostAddress(), isa.getPort());
           } catch (SecurityException se) {
             // Ignore packet
             bb.clear();
             n = 0;
             continue;
           }
           bb.flip();
           dst.put(bb);
           break;
         }
       }
       return sender;
     } finally {
       if (bb != null) Util.releaseTemporaryDirectBuffer(bb);
       readerThread = 0;
       end((n > 0) || (n == IOStatus.UNAVAILABLE));
       assert IOStatus.check(n);
     }
   }
 }
示例#7
0
 /**
  * Returns the specified image.
  *
  * @param url image url
  * @return image
  */
 public static Image get(final URL url) {
   try {
     return ImageIO.read(url);
   } catch (final IOException ex) {
     throw Util.notExpected(ex);
   }
 }
 void releaseBuffers() {
   for (int i = 0; i < numBufs; i++) {
     if (!(bufs[i] instanceof DirectBuffer)) {
       Util.releaseTemporaryDirectBuffer(shadow[i]);
     }
   }
 }
 /**
  * Invoked prior to write to prepare the WSABUF array. Where necessary, it substitutes
  * non-direct buffers with direct buffers.
  */
 void prepareBuffers() {
   shadow = new ByteBuffer[numBufs];
   long address = writeBufferArray;
   for (int i = 0; i < numBufs; i++) {
     ByteBuffer src = bufs[i];
     int pos = src.position();
     int lim = src.limit();
     assert (pos <= lim);
     int rem = (pos <= lim ? lim - pos : 0);
     long a;
     if (!(src instanceof DirectBuffer)) {
       // substitute with direct buffer
       ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
       bb.put(src);
       bb.flip();
       src.position(pos); // leave heap buffer untouched for now
       shadow[i] = bb;
       a = ((DirectBuffer) bb).address();
     } else {
       shadow[i] = src;
       a = ((DirectBuffer) src).address() + pos;
     }
     unsafe.putAddress(address + OFFSETOF_BUF, a);
     unsafe.putInt(address + OFFSETOF_LEN, rem);
     address += SIZEOF_WSABUF;
   }
 }
示例#10
0
 static {
   Attributes m = null;
   final URL loc = Prop.LOCATION;
   if (loc != null) {
     final String jar = loc.getFile();
     try {
       final ClassLoader cl = JarManifest.class.getClassLoader();
       final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF");
       while (list.hasMoreElements()) {
         final URL url = list.nextElement();
         if (!url.getFile().contains(jar)) continue;
         final InputStream in = url.openStream();
         try {
           m = new Manifest(in).getMainAttributes();
           break;
         } finally {
           in.close();
         }
       }
     } catch (final IOException ex) {
       Util.errln(ex);
     }
   }
   MAP = m;
 }
示例#11
0
  public void openLink(String link) {
    if (WWUtil.isEmpty(link)) return;

    try {
      try {
        // See if the link is a URL, and invoke the browser if it is
        URL url = new URL(link.replace(" ", "%20"));
        Desktop.getDesktop().browse(url.toURI());
        return;
      } catch (MalformedURLException ignored) { // just means that the link is not a URL
      }

      // It's not a URL, so see if it's a file and invoke the desktop to open it if it is.
      File file = new File(link);
      if (file.exists()) {
        Desktop.getDesktop().open(new File(link));
        return;
      }

      String message = "Cannot open resource. It's not a valid file or URL.";
      Util.getLogger().log(Level.SEVERE, message);
      this.showErrorDialog(null, "No Reconocido V\u00ednculo", message);
    } catch (UnsupportedOperationException e) {
      String message =
          "Unable to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "Error Opening Resource", message);
    } catch (IOException e) {
      String message =
          "I/O error while opening resource.\n"
              + link
              + (e.getMessage() != null ? ".\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message, e);
      this.showErrorDialog(e, "I/O Error", message);
    } catch (Exception e) {
      String message =
          "Error attempting to open resource.\n"
              + link
              + (e.getMessage() != null ? "\n" + e.getMessage() : "");
      Util.getLogger().log(Level.SEVERE, message);
      this.showMessageDialog(message, "Error Opening Resource", JOptionPane.ERROR_MESSAGE);
    }
  }
示例#12
0
 /**
  * Returns the image url.
  *
  * @param name name of image
  * @return url
  */
 private static URL url(final String name) {
   final String path = "/img/" + name + ".png";
   URL url = BaseXImages.class.getResource(path);
   if (url == null) {
     Util.stack("Image not found: " + path);
     url = BaseXImages.class.getResource("/img/warn.png");
   }
   return url;
 }
示例#13
0
 /**
  * Returns a string representation of all found arguments.
  *
  * @param args array with arguments
  * @return string representation
  */
 static String foundArgs(final Value[] args) {
   // compose found arguments
   final StringBuilder sb = new StringBuilder();
   for (final Value v : args) {
     if (sb.length() != 0) sb.append(", ");
     sb.append(v instanceof Jav ? Util.className(((Jav) v).toJava()) : v.seqType());
   }
   return sb.toString();
 }
示例#14
0
 public void setVisible(boolean bShow, String title) {
   if (bShow) {
     String strDir = "";
     String strFreq = "";
     String strTraynum = "";
     m_strHelpFile = getHelpFile(title);
     String strSampleName = getSampleName(title);
     String frameBounds = getFrameBounds(title);
     StringTokenizer tok = new QuotedStringTokenizer(title);
     if (tok.hasMoreTokens()) strDir = tok.nextToken();
     if (tok.hasMoreTokens()) strFreq = tok.nextToken();
     if (tok.hasMoreTokens()) strTraynum = tok.nextToken();
     else {
       try {
         Integer.parseInt(strDir);
         // if strdir is number, then strdir is empty, and the
         // strfreq is the number
         strTraynum = strFreq;
         strFreq = strDir;
         strDir = "";
       } catch (Exception e) {
       }
     }
     try {
       setTitle(gettitle(strFreq));
       m_lblSampleName.setText("3");
       boolean bVast = isVast(strTraynum);
       CardLayout layout = (CardLayout) m_pnlSampleName.getLayout();
       if (!bVast) {
         if (strSampleName == null) {
           strSampleName = getSampleName(strDir, strTraynum);
         }
         m_lblSampleName.setText(strSampleName);
         layout.show(m_pnlSampleName, OTHER);
       } else {
         m_strDir = strDir;
         setTrays();
         layout.show(m_pnlSampleName, VAST);
         m_trayTimer.start();
       }
       boolean bSample = bVast || !strSampleName.trim().equals("");
       m_pnlSampleName.setVisible(bSample);
       m_lblLogin.setForeground(getBackground());
       m_lblLogin.setVisible(false);
       m_passwordField.setText("");
       m_passwordField.setCaretPosition(0);
     } catch (Exception e) {
       Messages.writeStackTrace(e);
     }
     setBounds(frameBounds);
     ExpPanel exp = Util.getActiveView();
     if (exp != null) exp.waitLogin(true);
   }
   writePersistence();
   setVisible(bShow);
 }
示例#15
0
 @Override
 @EventHandler
 public void onChatReceived(ChatReceivedEvent event) {
   super.onChatReceived(event);
   String message = Util.stripColors(event.getMessage());
   if (message.startsWith("Please register with \"/register")) {
     String password = Util.generateRandomString(10 + random.nextInt(6));
     bot.say("/register " + password + " " + password);
   } else if (message.contains("You are not member of any faction.")
       && spamMessage != null
       && createFaction) {
     String msg = "/f create " + Util.generateRandomString(7 + random.nextInt(4));
     bot.say(msg);
   }
   for (String s : captchaList) {
     Matcher captchaMatcher = Pattern.compile(s).matcher(message);
     if (captchaMatcher.matches()) bot.say(captchaMatcher.group(1));
   }
 }
示例#16
0
  public LoginBox() {
    super("VnmrJ Login");

    dolayout("", "", "");
    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    // setVast();
    DisplayOptions.addChangeListener(this);

    try {
      InetAddress inetAddress = InetAddress.getLocalHost();
      m_strHostname = inetAddress.getHostName();
    } catch (Exception e) {
      m_strHostname = "localhost";
    }

    VNMRFrame vnmrFrame = VNMRFrame.getVNMRFrame();
    Dimension size = vnmrFrame.getSize();
    position = vnmrFrame.getLocationOnScreen();
    AppIF appIF = Util.getAppIF();
    int h = appIF.statusBar.getSize().height;
    width = size.width;
    height = size.height - h;

    // Allow resizing and use the previous size and position
    // To stop resizing, use setResizable(false);
    readPersistence();

    //        setSize(width, height);
    //        setLocation(position);
    //        setResizable(false);

    setBackgroundColor(Util.getBgColor());

    m_trayTimer =
        new javax.swing.Timer(
            6000,
            new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                setTrays();
              }
            });
  }
示例#17
0
 /**
  * Adds parameters from the passed on request body.
  *
  * @param body request body
  * @param params map parameters
  */
 private static void addParams(final String body, final Map<String, String[]> params) {
   for (final String nv : body.split("&")) {
     final String[] parts = nv.split("=", 2);
     if (parts.length < 2) continue;
     try {
       params.put(parts[0], new String[] {URLDecoder.decode(parts[1], Token.UTF8)});
     } catch (final Exception ex) {
       Util.notexpected(ex);
     }
   }
 }
示例#18
0
  public static IFileArtifactRepository getAggregatedBundleRepository(
      IProvisioningAgent agent, IProfile profile, int repoFilter) {
    List<IFileArtifactRepository> bundleRepositories = new ArrayList<IFileArtifactRepository>();

    // we check for a shared bundle pool first as it should be preferred over the user bundle pool
    // in a shared install
    IArtifactRepositoryManager manager = getArtifactRepositoryManager(agent);
    if ((repoFilter & AGGREGATE_SHARED_CACHE) != 0) {
      String sharedCache = profile.getProperty(IProfile.PROP_SHARED_CACHE);
      if (sharedCache != null) {
        try {
          URI repoLocation = new File(sharedCache).toURI();
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repository if it could not be read
        }
      }
    }

    if ((repoFilter & AGGREGATE_CACHE) != 0) {
      IFileArtifactRepository bundlePool = Util.getBundlePoolRepository(agent, profile);
      if (bundlePool != null) bundleRepositories.add(bundlePool);
    }

    if ((repoFilter & AGGREGATE_CACHE_EXTENSIONS) != 0) {
      List<String> repos = getListProfileProperty(profile, CACHE_EXTENSIONS);
      for (String repo : repos) {
        try {
          URI repoLocation;
          try {
            repoLocation = new URI(repo);
          } catch (URISyntaxException e) {
            // in 1.0 we wrote unencoded URL strings, so try as an unencoded string
            repoLocation = URIUtil.fromString(repo);
          }
          IArtifactRepository repository = manager.loadRepository(repoLocation, null);
          if (repository != null
              && repository instanceof IFileArtifactRepository
              && !bundleRepositories.contains(repository))
            bundleRepositories.add((IFileArtifactRepository) repository);
        } catch (ProvisionException e) {
          // skip repositories that could not be read
        } catch (URISyntaxException e) {
          // unexpected, URLs should be pre-checked
          LogHelper.log(new Status(IStatus.ERROR, Activator.ID, e.getMessage(), e));
        }
      }
    }
    return new AggregatedBundleRepository(agent, bundleRepositories);
  }
  private int receive(FileDescriptor fd, ByteBuffer dst) throws IOException {
    int pos = dst.position();
    int lim = dst.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);
    if (dst instanceof DirectBuffer && rem > 0) return receiveIntoNativeBuffer(fd, dst, rem, pos);

    // Substitute a native buffer. If the supplied buffer is empty
    // we must instead use a nonempty buffer, otherwise the call
    // will not block waiting for a datagram on some platforms.
    int newSize = Math.max(rem, 1);
    ByteBuffer bb = Util.getTemporaryDirectBuffer(newSize);
    try {
      int n = receiveIntoNativeBuffer(fd, bb, newSize, 0);
      bb.flip();
      if (n > 0 && rem > 0) dst.put(bb);
      return n;
    } finally {
      Util.releaseTemporaryDirectBuffer(bb);
    }
  }
示例#20
0
  public void init() {
    String host = util.getHost();

    h = new JLabel(host + " up since: ");
    v = new JLabel(" unknown ");
    setLayout(new GridLayout(2, 1));
    add(h);
    add(v);
    try {
      context = new SnmpContext(host, port);
    } catch (java.io.IOException exc) {
      System.out.println("IOException " + exc.getMessage());
      System.exit(0);
    }
  }
示例#21
0
  /**
   * Sets a status and sends an info message.
   *
   * @param code status code
   * @param message info message
   * @param error treat as error (use web server standard output)
   * @throws IOException I/O exception
   */
  public void status(final int code, final String message, final boolean error) throws IOException {
    try {
      log(message, code);
      res.resetBuffer();
      if (code == SC_UNAUTHORIZED) res.setHeader(WWW_AUTHENTICATE, BASIC);

      if (error && code >= SC_BAD_REQUEST) {
        res.sendError(code, message);
      } else {
        res.setStatus(code);
        if (message != null) res.getOutputStream().write(token(message));
      }
    } catch (final IllegalStateException ex) {
      log(Util.message(ex), SC_INTERNAL_SERVER_ERROR);
    }
  }
示例#22
0
  /**
   * 超时测试
   *
   * @param req
   * @param res
   */
  public static void asyncSubscribe(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    iAsyncMgntInt.setAsyncCall(true); // 标志异步调用
    HttpSession session = req.getSession(false);
    Util.set(session.getId(), session);

    TopicCmd mc = new TopicCmd(); // 自动处理命令
    mc.setSessionKey("SYS_OPER_LIST");
    mc.setSessionId(session.getId());

    iAsyncMgntInt.setResponseCommand(mc);
    iAsyncMgntInt.setMessageType("test_subscribe");

    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    try {

      int result = iAsyncMgntInt.select_sysOperators_subscribe(holder, errMsg); // 获取响应结果

      res.getWriter().println("<html>");
      res.getWriter().println("<head>");
      res.getWriter().println("<title>");
      res.getWriter().println("异步架构系统测试");
      res.getWriter().println("</title>");
      res.getWriter().println("</head>");
      res.getWriter().println("<body>");
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("消息订阅已发起<br>");
      res.getWriter().println("<form name=\"testform\" action=\"./test\" method=\"get\">");
      res.getWriter()
          .println("<input type=\"hidden\" name=\"method\" value=\"asyncSubscribeResult\">");
      res.getWriter()
          .println("<input type=\"hidden\" name=\"mseq\" value=\"" + mc.getSessionKey() + "\">");
      res.getWriter().println("<input type=\"submit\" name=\"test\" value=\"查看订阅情况\">");
      res.getWriter().println("</form>");
      res.getWriter().println("</body>");
      res.getWriter().println("</html>");

    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        res.getWriter().println(e.getMessage());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
示例#23
0
  // Get the size of the full vnmrj frame and set the Login Panel
  // to that size and position.
  public void setDefaultSizePosition() {
    VNMRFrame vnmrFrame = VNMRFrame.getVNMRFrame();
    Dimension size = vnmrFrame.getSize();

    // Save point for later use also
    position = vnmrFrame.getLocationOnScreen();
    AppIF appIF = Util.getAppIF();
    int h = appIF.statusBar.getSize().height;

    // Save width and height for later use also
    width = size.width;
    height = size.height - h;

    // Go ahead and set the size and position
    setSize(width, height);
    setLocation(position);
  }
示例#24
0
  protected void setTrayPresent(String strPath) {
    String strzone = "zones";
    BufferedReader reader = WFileUtil.openReadFile(strPath);
    if (reader == null) return;

    String strLine;
    try {
      // if the zones are set to 0, then there is no tray present
      // set rackInfo(1,zones) 3 => tray 1 present
      // set rackInfo(2,zones) 0 => tray 2 not present
      while ((strLine = reader.readLine()) != null) {
        int index = strLine.indexOf(strzone);
        if (index < 0) continue;

        String strTray = strLine.substring(index - 2, index - 1);
        int nTray = 0;
        try {
          nTray = Integer.parseInt(strTray);
        } catch (Exception e) {
        }

        if (nTray <= 0) continue;

        int nZone = 0;
        try {
          strTray = strLine.substring(index + strzone.length() + 2, strLine.length());
          nZone = Integer.parseInt(strTray);
        } catch (Exception e) {
        }

        Color colorbg = Color.white;
        String strTooltip = TRAY;
        if (nZone <= 0) {
          colorbg = Color.black;
          strTooltip = NOTRAY;
        }
        VBox pnlVast = m_pnlVast[nTray - 1];
        pnlVast.setbackground(colorbg);
        pnlVast.setToolTipText(Util.getTooltipString(strTooltip));
      }
      reader.close();
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
    }
  }
示例#25
0
  public void init() {
    // get the host name
    String host = util.getHost();

    h = new JLabel("Host " + host + ", Interface " + intfIndex + " speed");
    try {
      context = new SnmpContext(host, port);
      context.setCommunity(community);

      setLayout(new GridLayout(2, 1));
      add(h);
      v = new JLabel(" unknown ");
      add(v);
    } catch (java.io.IOException exc) {
      System.out.println("IOException " + exc.getMessage());
      System.exit(0);
    }
  }
示例#26
0
  protected static char[] getPassword(char[] password) {
    int size = password.length;
    int data = 0;
    boolean bwindows = Util.iswindows();
    for (int i = 0; i < size; i++) {
      if (!bwindows) {
        if (password[i] == '`' || password[i] == '"' || password[i] == '\\') data = data + 1;
      } else {
        if (password[i] == '"') data = data + 1;
        else if (password[i] == ' ') data = data + 2;
      }
    }
    char[] password2 = new char[size + data];
    int size2 = password2.length;
    int j = 0;
    for (int i = 0; i < size2; i++) {
      if (j >= size) break;
      boolean bSpace = false;

      if (!bwindows) {
        if (password[j] == '`' || password[j] == '"' || password[j] == '\\') {
          password2[i] = '\\';
          i = i + 1;
        }
      } else {
        if (password[j] == '"') {
          password2[i] = '\\';
          i = i + 1;
        } else if (password[j] == ' ') {
          password2[i] = '"';
          i = i + 1;
          password2[i] = password[j];
          i = i + 1;
          password2[i] = '"';
          // i=i+1;
          bSpace = true;
        }
      }
      if (!bSpace) password2[i] = password[j];
      j = j + 1;
    }

    return password2;
  }
示例#27
0
  /**
   * Tests writing of request content when @src is set.
   *
   * @throws IOException I/O Exception
   */
  @Test
  public void writeFromResource() throws IOException {
    // Create a file form which will be read
    final IOFile file = new IOFile(Prop.TMP, Util.className(FnHttpTest.class));
    file.write(token("test"));

    // Request
    final HttpRequest req = new HttpRequest();
    req.payloadAttrs.put("src", file.url());
    req.payloadAttrs.put("method", "binary");
    // HTTP connection
    final FakeHttpConnection fakeConn = new FakeHttpConnection(new URL("http://www.test.com"));
    HttpClient.setRequestContent(fakeConn.getOutputStream(), req);

    // Delete file
    file.delete();

    assertEquals(fakeConn.out.toString(Strings.UTF8), "test");
  }
示例#28
0
文件: UDP.java 项目: NZDIS/jgroups
 void closeMulticastSocket() {
   if (mcast_sock != null) {
     try {
       if (mcast_addr != null) {
         // by sending a dummy packet the thread will be awakened
         sendDummyPacket(mcast_addr.getIpAddress(), mcast_addr.getPort());
         Util.sleep(300);
         mcast_sock.leaveGroup(mcast_addr.getIpAddress());
       }
       mcast_sock.close(); // this will cause the mcast receiver thread to break out of its loop
       mcast_sock = null;
       if (Trace.trace) {
         Trace.info("UDP.closeMulticastSocket()", "multicast socket closed");
       }
     } catch (IOException ex) {
     }
     mcast_addr = null;
   }
 }
示例#29
0
  protected void setTrayActive(String strDir) {
    String strTray;
    String strStudy;
    String strActive = "Active";
    String cmd =
        "SELECT vrack_,studystatus from study WHERE (autodir=\'"
            + strDir
            + "\') AND (hostname=\'"
            + getHost()
            + "\')";
    m_dbResult = null;

    try {
      m_dbResult = getdbmanager().executeQuery(cmd);
    } catch (Exception e) {
      return;
    }
    if (m_dbResult == null) return;

    int nTray = 0;
    try {
      while (m_dbResult.next()) {
        strTray = m_dbResult.getString(1);
        strStudy = m_dbResult.getString(2);
        if (strStudy != null && strStudy.equalsIgnoreCase(strActive)) {
          try {
            nTray = Integer.parseInt(strTray);
          } catch (Exception e) {
          }

          if (nTray > 0) {
            m_pnlVast[nTray - 1].setbackground(Color.blue);
            m_pnlVast[nTray - 1].setToolTipText(Util.getTooltipString(TRAYACTIVE));
            break;
          }
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
    }
  }
示例#30
0
文件: UDP.java 项目: NZDIS/jgroups
    public void run() {
      Message msg;

      while (outgoing_queue != null && outgoing_packet_handler != null) {
        try {
          msg = (Message) outgoing_queue.remove();
          handleMessage(msg);
        } catch (QueueClosedException closed_ex) {
          if (Trace.trace) {
            Trace.info("UDP.OutgoingPacketHandler.run()", "packet_handler thread terminating");
          }
          break;
        } catch (Throwable t) {
          Trace.error(
              "UDP.OutgoingPacketHandler.run()",
              "exception sending packet: " + Util.printStackTrace(t));
        }
        msg = null; // let's give the poor garbage collector a hand...
      }
    }