/**
   * Constructor. Creates a datagram send socket and connects it to the Ganglia hypertable extension
   * listen port. Initializes mPrefix to "ht." + <code>component</code> + ".".
   *
   * @param component Hypertable component ("fsbroker", "hyperspace, "master", "rangeserver", or
   *     "thriftbroker")
   * @param props Configuration properties
   */
  public MetricsCollectorGanglia(String component, Properties props) {
    mPrefix = "ht." + component + ".";

    String str = props.getProperty("Hypertable.Metrics.Ganglia.Port", "15860");
    mPort = Integer.parseInt(str);

    str = props.getProperty("Hypertable.Metrics.Ganglia.Disabled");
    if (str != null && str.equalsIgnoreCase("true")) mDisabled = true;

    try {
      mAddr = InetAddress.getByName("localhost");
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException : 'localhost'");
      e.printStackTrace();
      System.exit(-1);
    }

    try {
      mSocket = new DatagramSocket();
    } catch (SocketException e) {
      e.printStackTrace();
      System.exit(-1);
    }

    mSocket.connect(mAddr, mPort);
    mConnected = true;
  }
예제 #2
1
 private static double executeWithDisruptorPipeline(int numConsumers) {
   CountDownLatch cdl = new CountDownLatch(numConsumers);
   List<Consumer> consumers = createConsumers(numConsumers, null, cdl, SIMULATE_PROCESSING);
   MessagePipeDisruptorImpl<Carbon> pipeline =
       new MessagePipeDisruptorImpl<Carbon>(
           QUEUE_SIZE, AtomEvent.EVENT_FACTORY, new YieldingWaitStrategy(), consumers);
   Producer producer = new Producer(pipeline, NUM_MANU_UNITS);
   Thread producerThread = new Thread(producer);
   producerThread.start();
   long startTime = System.currentTimeMillis();
   try {
     cdl.await();
     printStatistics(consumers);
     long endTime = System.currentTimeMillis();
     out.println("Took " + (endTime - startTime) + " ms");
     pipeline.halt();
     producerThread.interrupt();
     while (producerThread.isAlive()) {
       out.println("Interrupting producer");
       producerThread.interrupt();
       Thread.sleep(300);
     }
     ;
     return endTime - startTime;
   } catch (InterruptedException e) {
     e.printStackTrace();
     return Double.POSITIVE_INFINITY;
   }
 }
예제 #3
0
파일: PerfTest.java 프로젝트: ETK/javersion
  private static void runJaversionTree(Integer[] data) {
    out.println("Javersion PersistentTreeMap");
    @SuppressWarnings("unchecked")
    PersistentTreeMap<Integer, Integer> jmap = PersistentTreeMap.EMPTY;
    // warmup
    for (Integer v : data) {
      jmap = jmap.assoc(v, v);
    }
    jmap = null;
    //        System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      jmap = PersistentTreeMap.EMPTY;
      for (int j = 0; j < i; j++) {
        jmap = jmap.assoc(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        jmap = jmap.dissoc(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\nJaversion total time: %s", System.nanoTime() - begin));
  }
예제 #4
0
파일: PerfTest.java 프로젝트: ETK/javersion
  private static void runClojure(Integer[] data) {
    out.println("Clojure PersistentHashMap");
    clojure.lang.PersistentHashMap cmap = clojure.lang.PersistentHashMap.EMPTY;

    // warmup
    for (Integer v : data) {
      cmap = (clojure.lang.PersistentHashMap) cmap.assoc(v, v);
    }
    cmap = null;
    System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      cmap = clojure.lang.PersistentHashMap.EMPTY;
      for (int j = 0; j < i; j++) {
        cmap = (clojure.lang.PersistentHashMap) cmap.assoc(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        cmap = (clojure.lang.PersistentHashMap) cmap.without(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\n%s", System.nanoTime() - begin));
  }
예제 #5
0
 /**
  * create a new ACLMessage that is a reply to this message. In particular, it sets the following
  * parameters of the new message: receiver, language, ontology, protocol, conversation-id,
  * in-reply-to, reply-with. The programmer needs to set the communicative-act and the content. Of
  * course, if he wishes to do that, he can reset any of the fields.
  *
  * @return the ACLMessage to send as a reply
  */
 public ACLMessage createReply() {
   ACLMessage m = new ACLMessage(getPerformative());
   Iterator it = getAllReplyTo();
   while (it.hasNext()) m.addReceiver((AID) it.next());
   if ((reply_to == null) || reply_to.isEmpty()) m.addReceiver(getSender());
   m.setLanguage(getLanguage());
   m.setOntology(getOntology());
   m.setProtocol(getProtocol());
   m.setInReplyTo(getReplyWith());
   if (source != null) m.setReplyWith(source.getName() + java.lang.System.currentTimeMillis());
   else m.setReplyWith("X" + java.lang.System.currentTimeMillis());
   m.setConversationId(getConversationId());
   // Copy only well defined user-def-params
   String trace = getUserDefinedParameter(TRACE);
   if (trace != null) {
     m.addUserDefinedParameter(TRACE, trace);
   }
   // #CUSTOM_EXCLUDE_BEGIN
   // Set the Aclrepresentation of the reply message to the aclrepresentation of the sent message
   if (messageEnvelope != null) {
     m.setDefaultEnvelope();
     String aclCodec = messageEnvelope.getAclRepresentation();
     if (aclCodec != null) m.getEnvelope().setAclRepresentation(aclCodec);
   } else m.setEnvelope(null);
   // #CUSTOM_EXCLUDE_END
   return m;
 }
  /**
   * @param request
   * @param response @TODO refactor and optimize code for initializing handler
   */
  public void doService(HttpServletRequest request, HttpServletResponse response) {
    if (response.isCommitted()) {
      LOG.logWarning("The response object is already committed!");
    }

    long startTime = System.currentTimeMillis();
    address = request.getRequestURL().toString();

    String service = null;
    try {
      OGCWebServiceRequest ogcRequest = OGCRequestFactory.create(request);

      LOG.logInfo(
          StringTools.concat(
              500,
              "Handling request '",
              ogcRequest.getId(),
              "' from '",
              request.getRemoteAddr(),
              "' to service: '",
              ogcRequest.getServiceName(),
              "'"));

      // get service from request
      service = ogcRequest.getServiceName().toUpperCase();

      // get handler instance
      ServiceDispatcher handler =
          ServiceLookup.getInstance().getHandler(service, request.getRemoteAddr());
      // dispatch request to specific handler
      handler.perform(ogcRequest, response);
    } catch (OGCWebServiceException e) {
      LOG.logError(e.getMessage(), e);
      sendException(response, e, request, service);
    } catch (ServiceException e) {
      if (e.getNestedException() instanceof OGCWebServiceException) {
        sendException(response, (OGCWebServiceException) e.getNestedException(), request, service);
      } else {
        sendException(
            response,
            new OGCWebServiceException(this.getClass().getName(), e.getMessage()),
            request,
            service);
      }
      LOG.logError(e.getMessage(), e);
    } catch (Exception e) {
      sendException(
          response,
          new OGCWebServiceException(this.getClass().getName(), e.getMessage()),
          request,
          service);
      LOG.logError(e.getMessage(), e);
    }
    if (LOG.isDebug()) {
      LOG.logDebug(
          "OGCServletController: request performed in "
              + Long.toString(System.currentTimeMillis() - startTime)
              + " milliseconds.");
    }
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    Window win = getWindow();
    win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    win.setFlags(
        WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.main);

    // setup adView
    //        LinearLayout layout = (LinearLayout)findViewById(R.id.layout_setup);
    //        adView = new AdView(this, AdSize.BANNER, "a1507f940fc****");
    //        layout.addView(adView);
    //        adView.loadAd(new AdRequest());

    btnExit = (Button) findViewById(R.id.btn_exit);
    btnExit.setOnClickListener(exitAction);
    tvMessage1 = (TextView) findViewById(R.id.tv_message1);
    tvMessage2 = (TextView) findViewById(R.id.tv_message2);
    mBlackScreen = (ViewGroup) findViewById(R.id.black_screen);

    for (int i = 0; i < maxVideoNumber; i++) {
      videoFrames[i] = new VideoFrame(1024 * 1024 * 2);
    }

    System.loadLibrary("mp3encoder");
    System.loadLibrary("natpmp");

    initAudio();
    initCamera();
  }
예제 #8
0
 /* (non-Javadoc)
  * @see chu.engine.Game#loop()
  */
 @Override
 public void loop() {
   while (!Display.isCloseRequested()) {
     final long time = System.nanoTime();
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
     glClearDepth(1.0f);
     getInput();
     final ArrayList<Message> messages = new ArrayList<>();
     if (client != null) {
       synchronized (client.messagesLock) {
         messages.addAll(client.messages);
         for (Message m : messages) client.messages.remove(m);
       }
     }
     SoundStore.get().poll(0);
     glPushMatrix();
     // Global resolution scale
     //			Renderer.scale(scaleX, scaleY);
     currentStage.beginStep(messages);
     currentStage.onStep();
     currentStage.processAddStack();
     currentStage.processRemoveStack();
     currentStage.render();
     //				FEResources.getBitmapFont("stat_numbers").render(
     //						(int)(1.0f/getDeltaSeconds())+"", 440f, 0f, 0f);
     currentStage.endStep();
     glPopMatrix();
     Display.update();
     timeDelta = System.nanoTime() - time;
   }
   AL.destroy();
   Display.destroy();
   if (client != null && client.isOpen()) client.quit();
 }
예제 #9
0
 public long getTefTime() {
   synchronized (objectMutex) {
     return (((tefTime - System.currentTimeMillis()) > 0)
         ? (tefTime - System.currentTimeMillis())
         : 0);
   }
 }
예제 #10
0
 private static double executeWithNonDisruptorPipeline(
     int numConsumers, GenericPipe<Carbon> pipeline) {
   Producer producer = new Producer(pipeline, NUM_MANU_UNITS);
   CountDownLatch cdl = new CountDownLatch(numConsumers);
   List<Consumer> consumers = createConsumers(numConsumers, pipeline, cdl, SIMULATE_PROCESSING);
   ExecutorService pool = executeWithExecutor(consumers);
   Thread producerThread = new Thread(producer);
   producerThread.start();
   long startTime = System.currentTimeMillis();
   try {
     cdl.await();
     printStatistics(consumers);
     long endTime = System.currentTimeMillis();
     out.println("Took " + (endTime - startTime) + " ms");
     producerThread.interrupt();
     pool.shutdown();
     try {
       pool.awaitTermination(1000, TimeUnit.MILLISECONDS);
       out.println("Pool terminated");
     } catch (Exception e) {
       out.println("Awaiting termination failed, shutting down");
       pool.shutdownNow();
     }
     while (producerThread.isAlive()) {}
     ;
     return (endTime - startTime);
   } catch (InterruptedException e) {
     e.printStackTrace();
     return Double.POSITIVE_INFINITY;
   }
 }
    public long test(final Type type, final String fileName) {
      long start = System.currentTimeMillis();

      try {
        switch (type) {
          case WRITE:
            {
              checkSum = testWrite(fileName);
              break;
            }

          case READ:
            {
              final int checkSum = testRead(fileName);
              if (checkSum != this.checkSum) {
                final String msg = getName() + " expected=" + this.checkSum + " got=" + checkSum;
                throw new IllegalStateException(msg);
              }
              break;
            }
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      return System.currentTimeMillis() - start;
    }
예제 #12
0
  /**
   * This method is called upon plug-in activation
   *
   * @param context
   * @throws Exception
   */
  public void start(BundleContext context) throws Exception {
    super.start(context);
    iconsUrl = context.getBundle().getEntry(ICONS_PATH);
    Authenticator.setDefault(new UDIGAuthenticator());
    /*
     * TODO Further code can nuke the previously set authenticator. Proper security access
     * should be configured to prevent this.
     */
    disableCerts();
    try {
      loadVersion();

      java.lang.System.setProperty(
          "http.agent",
          "uDig "
              + getVersion()
              + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
      java.lang.System.setProperty(
          "https.agent",
          "uDig "
              + getVersion()
              + " (http://udig.refractions.net)"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    } catch (Throwable e) {
      log("error determining version", e); // $NON-NLS-1$
    }
  }
예제 #13
0
  /**
   * Adds post advices to the pointcut.
   *
   * @param advicesToAdd the advices to add
   */
  public void addPostAdvices(final String[] advicesToAdd) {
    for (int i = 0; i < advicesToAdd.length; i++) {
      if (advicesToAdd[i] == null || advicesToAdd[i].trim().length() == 0)
        throw new IllegalArgumentException(
            "name of advice to add can not be null or an empty string");
    }
    synchronized (m_postNames) {
      synchronized (m_postIndexes) {
        final String[] clone = new String[advicesToAdd.length];
        java.lang.System.arraycopy(advicesToAdd, 0, clone, 0, advicesToAdd.length);

        final String[] tmp = new String[m_postNames.length + advicesToAdd.length];
        java.lang.System.arraycopy(m_postNames, 0, tmp, 0, m_postNames.length);
        java.lang.System.arraycopy(clone, 0, tmp, m_postNames.length, tmp.length);

        m_postNames = new String[tmp.length];
        java.lang.System.arraycopy(tmp, 0, m_postNames, 0, tmp.length);

        m_postIndexes = new IndexTuple[m_postNames.length];
        for (int j = 0; j < m_postNames.length; j++) {
          m_postIndexes[j] = SystemLoader.getSystem(m_uuid).getAdviceIndexFor(m_postNames[j]);
        }
      }
    }
  }
예제 #14
0
  public static void main(String[] args) {
    if (args.length < 1) {
      System.out.println("Usage: evaluateCustomMath formula [model containing values]");
      System.exit(1);
    }

    String formula = args[0];
    String filename = args.length == 2 ? args[1] : null;

    ASTNode math = libsbml.parseFormula(formula);
    if (math == null) {
      System.out.println("Invalid formula, aborting.");
      System.exit(1);
    }

    SBMLDocument doc = null;
    if (filename != null) {
      doc = libsbml.readSBML(filename);
      if (doc.getNumErrors(libsbml.LIBSBML_SEV_ERROR) > 0) {
        System.out.println("The models contains errors, please correct them before continuing.");
        doc.printErrors();
        System.exit(1);
      }
      // the following maps a list of ids to their corresponding model values
      // this makes it possible to evaluate expressions involving SIds.
      SBMLTransforms.mapComponentValues(doc.getModel());
    } else {
      // create dummy document
      doc = new SBMLDocument(3, 1);
    }

    double result = SBMLTransforms.evaluateASTNode(math, doc.getModel());
    System.out.println(String.format("%s = %s", formula, result));
  }
예제 #15
0
 // Load the .so
 static {
   System.loadLibrary("SDL");
   // System.loadLibrary("SDL_image");
   // System.loadLibrary("SDL_mixer");
   // System.loadLibrary("SDL_ttf");
   System.loadLibrary("main");
 }
 private int enumerate(ThreadGroup list[], int n, boolean recurse) {
   int ngroupsSnapshot = 0;
   ThreadGroup[] groupsSnapshot = null;
   synchronized (this) {
     if (destroyed) {
       return 0;
     }
     int ng = ngroups;
     if (ng > list.length - n) {
       ng = list.length - n;
     }
     if (ng > 0) {
       System.arraycopy(groups, 0, list, n, ng);
       n += ng;
     }
     if (recurse) {
       ngroupsSnapshot = ngroups;
       if (groups != null) {
         groupsSnapshot = new ThreadGroup[ngroupsSnapshot];
         System.arraycopy(groups, 0, groupsSnapshot, 0, ngroupsSnapshot);
       } else {
         groupsSnapshot = null;
       }
     }
   }
   if (recurse) {
     for (int i = 0; i < ngroupsSnapshot; i++) {
       n = groupsSnapshot[i].enumerate(list, n, true);
     }
   }
   return n;
 }
예제 #17
0
 /**
  * Removes a StmtLine (0..*).
  *
  * @param index The index of the StmtLine to get.
  */
 public void removeStmtLine(int index) {
   if (this.stmtLine == null) throw new java.lang.ArrayIndexOutOfBoundsException();
   biz.c24.io.training.statements.StatementLine[] temp = this.stmtLine;
   this.stmtLine = new biz.c24.io.training.statements.StatementLine[temp.length - 1];
   java.lang.System.arraycopy(temp, 0, this.stmtLine, 0, index);
   java.lang.System.arraycopy(temp, index + 1, this.stmtLine, index, temp.length - index - 1);
   if (this.stmtLine.length == 0) this.stmtLine = null;
 }
예제 #18
0
파일: search.java 프로젝트: martron/libRETS
 static {
   try {
     System.loadLibrary("librets");
   } catch (UnsatisfiedLinkError e) {
     System.err.println("Unable to load the librets native library.\n" + e);
     System.exit(1);
   }
 }
 public static void basic_putenv(Object name, Object value) {
   String name_string = SmartEiffelRuntime.NullTerminatedBytesToString(name);
   String value_string = SmartEiffelRuntime.NullTerminatedBytesToString(value);
   Properties props = System.getProperties();
   props.put(name_string, value_string);
   System.setProperties(props);
   return;
 }
예제 #20
0
  /**
   * Entry point.
   *
   * @param args[0] Domain controller name.
   * @param args[1] Domain user name.
   * @param args[2] Domain password.
   * @param args[3] Optional file name. Default is mp3Spider.out
   */
  public static void main(String args[]) throws IOException, InterruptedException {

    String domCtrl = null;
    String domName = null;
    String domUser = null;
    String domPass = null;
    // File to write to
    FileWriter fwrite = null;

    try {
      domCtrl = args[0];
      domName = args[1];
      domUser = args[2];
      domPass = args[3];
    } catch (ArrayIndexOutOfBoundsException e) {
      System.err.println("Usage:");
      System.err.println(
          "java mp3Spider <Domain controller> "
              + "<Domain Name> <Username> <Password> [<Out file>]");
      System.exit(1);
    }

    if (args.length == 5) fwrite = new FileWriter(args[5]);
    else fwrite = new FileWriter("mp3Spider.out");

    // Get list of machines on the domain
    CifsLogin login = new CifsLogin(domUser, domPass);
    CifsRemoteAdmin admin = null;
    CifsServerInfo mach[] = null;
    try {
      admin = CifsSessionManager.connectRemoteAdmin("Mach_list_all", domCtrl, login);

      mach = admin.listServersInfo(domName, CifsServerInfo.SV_TYPE_ALL);
      admin.disconnect();
    } catch (CifsIOException e) {
      System.err.println("Session failed: " + e);
      e.printStackTrace();
      System.exit(1);
    }

    // Create a thread and start shareVu() for every machine
    ShareVu t[] = new ShareVu[mach.length];
    for (int i = 0; i < mach.length; i++) {
      System.out.println("Mach: " + mach[i].getComputerName());
      // Create the thread
      t[i] = new ShareVu(mach[i].getComputerName(), login, fwrite);
    }

    // Wait for all threads to finito

    for (int i = 0; i < mach.length; i++) {
      try {
        t[i].t.join();
      } catch (InterruptedException e) {
        System.out.println("Join error " + e);
      }
    }
  }
예제 #21
0
 public void write(byte[] buffer, int offset, int length) {
   if (count + length >= bytes.length) {
     byte[] newBytes = new byte[(count + length) * 2];
     System.arraycopy(bytes, 0, newBytes, 0, count);
     bytes = newBytes;
   }
   System.arraycopy(buffer, offset, bytes, count, length);
   count += length;
 }
예제 #22
0
 /**
  * Insert a subarray of the <code>char[]</code> argument into this <code>StringBuffer</code>.
  *
  * @param offset the place to insert in this buffer
  * @param str the <code>char[]</code> to insert
  * @param str_offset the index in <code>str</code> to start inserting from
  * @param len the number of characters to insert
  * @return this <code>StringBuffer</code>
  * @throws NullPointerException if <code>str</code> is <code>null</code>
  * @throws StringIndexOutOfBoundsException if any index is out of bounds
  * @since 1.2
  */
 public synchronized StringBuffer insert(int offset, char[] str, int str_offset, int len) {
   if (offset < 0 || offset > count || len < 0 || str_offset < 0 || str_offset > str.length - len)
     throw new StringIndexOutOfBoundsException();
   ensureCapacity_unsynchronized(count + len);
   System.arraycopy(value, offset, value, offset + len, count - offset);
   System.arraycopy(str, str_offset, value, offset, len);
   count += len;
   return this;
 }
예제 #23
0
  public long getRemainingCooldown(String cooldownGroup) {
    if (cooldowns.containsKey(cooldownGroup)) {
      if (System.currentTimeMillis() < cooldowns.get(cooldownGroup)) {
        return (long) (cooldowns.get(cooldownGroup) - System.currentTimeMillis());
      } else {
        cooldowns.remove(cooldownGroup);
      }
    }

    return 0L;
  }
예제 #24
0
    @Override
    public SolutionObject solve(
        int[][] travelTime,
        int[] releaseDates,
        int[] dueDates,
        int[][] servicePairs,
        int[] serviceTimes,
        @Nullable SolutionObject currentSolution) {

      inputMemory.add(
          new ArraysObject(
              travelTime,
              releaseDates,
              dueDates,
              servicePairs,
              serviceTimes,
              currentSolution == null ? null : new SolutionObject[] {currentSolution}));
      if (print) {
        out.println("int[][] travelTime = " + fix(deepToString(travelTime)));
        out.println("int[] releaseDates = " + fix(Arrays.toString(releaseDates)));
        out.println("int[] dueDates = " + fix(Arrays.toString(dueDates)));
        out.println("int[][] servicePairs = " + fix(deepToString(servicePairs)));
        out.println("int[] serviceTime = " + fix(Arrays.toString(serviceTimes)));
      }

      final long start = System.currentTimeMillis();
      final SolutionObject sol =
          solver.solve(
              travelTime, releaseDates, dueDates, servicePairs, serviceTimes, currentSolution);
      if (print) {
        out.println(System.currentTimeMillis() - start + "ms");
        out.println("route: " + Arrays.toString(sol.route));
        out.println("arrivalTimes: " + Arrays.toString(sol.arrivalTimes));
        out.println("objectiveValue: " + sol.objectiveValue);
      }

      outputMemory.add(
          new SolutionObject(
              copyOf(sol.route, sol.route.length),
              copyOf(sol.arrivalTimes, sol.arrivalTimes.length),
              sol.objectiveValue));

      int totalTravelTime = 0;
      for (int i = 1; i < travelTime.length; i++) {
        totalTravelTime += travelTime[sol.route[i - 1]][sol.route[i]];
      }
      if (print) {
        out.println("travel time :  " + totalTravelTime);
      }
      return sol;
    }
예제 #25
0
 protected static final void initializeNative() {
   try {
     System.loadLibrary("bioerafft");
   } catch (Throwable e) {
     // e.printStackTrace();
     if (debug) {
       System.out.println("" + e.getMessage());
       System.out.println(
           "Native implementation (bioerafft) of FFT not found in "
               + System.getProperty("java.library.path")
               + ", using pure version");
     }
   }
 }
예제 #26
0
  public static void main(String[] args) throws IOException {

    boolean helyes = false;
    int i = 0;
    String aa = "al";
    do {
      System.out.println("-----Weclome!-----");
      System.out.println("a. - Soronkent szeretne keresni!");
      System.out.println("b. - Szavankent szeretne keresni!");
      System.out.println("c. - Ne legyen kis/nagy betuerzekeny!");
      System.out.println("x. - Kilep");
      System.out.println("------------------");
      String s = System.console().readLine();
      if (s.equals("x")) {
        helyes = true;
      } else {
        if (s.equals("a")) {
          System.out.println("irja':");
          String line = System.console().readLine();
          try {
            findTextLine(line, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
        if (s.equals("b")) {
          System.out.println("irja':");
          String word = System.console().readLine();
          try {
            findTextWord(word, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
        if (s.equals("c")) {
          System.out.println("irja':");
          String line = System.console().readLine();
          try {
            findTextWordNoCaps(line, args[0]);
          } catch (FileNotFoundException e) {
            System.out.println("A kov fajl nem talalhato: " + args[0]);
          }
          helyes = true;
        }
      }
    } while (helyes == false);
  }
예제 #27
0
  public static void main(String[] args) throws LBMException {
    LBMContext ctx = null; /* Context object: container for UM "instance". */
    LBMSource src = null; /* Source object: for sending messages. */

    SrcCB srccb = new SrcCB();

    /** * Initialization: create necessary UM objects. ** */
    try {
      LBMTopic topic = null;
      LBMSourceAttributes srcAttr = null;

      ctx = new LBMContext();
      srcAttr = new LBMSourceAttributes();
      srcAttr.setValue("ume_store", "127.0.0.1:29999");
      srcAttr.setValue("ume_store_behavior", "qc");
      topic = ctx.allocTopic("test.topic", srcAttr);
      src = ctx.createSource(topic, srccb, null, null);
    } catch (LBMException ex) {
      System.err.println("Error initializing LBM objects: " + ex.toString());
      System.exit(1);
    }

    while (true) {
      if (srcReady == 1) {
        /** * Send a message. ** */
        try {
          src.send("test".getBytes(), "test".getBytes().length, LBM.MSG_FLUSH | LBM.SRC_NONBLOCK);
        } catch (LBMException ex) {
          /* Error trying to send, wait 1 second and try again */
          try {
            Thread.sleep(1000);
          } catch (InterruptedException tex) {
            System.err.println("Error Thread.sleep interrupted: " + tex.toString());
            System.exit(1);
          }
        }
      } else {
        /* No quorum, wait 1 second and check again */
        System.out.println("Source is not ready to send (no quorum)");
        try {
          Thread.sleep(1000);
        } catch (InterruptedException tex) {
          System.err.println("Error Thread.sleep interrupted: " + tex.toString());
          System.exit(1);
        }
      }
    }
  } /* main */
예제 #28
0
  int getValues(Map<String, Object> values, String ip, String timeout) {
    try {
      Class.forName("edu.bucknell.net.JDHCP.DHCPSocket");
    } catch (ClassNotFoundException cnfe) {
      lastError = "JDHCP libraries unavailable (see Help document for DHCP Monitor)";
      return 1;
    }

    IP = ip;
    Timeout = Integer.parseInt(timeout);

    int sleepTime = 1000;
    Random r = new Random();
    int xid = r.nextInt();
    byte hwaddr[] = new byte[16];

    startTime = System.currentTimeMillis();
    Object results[] = acquireAddress(xid, hwaddr, sleepTime);
    if (results[0].equals("n/a")) {
      lastError = (String) results[4];
      return 1;
    } else {
      values.put("Roundtime", results[1]);
      values.put("Address", results[4]);
    }

    return 0;
  }
  public void run() {
    try {
      JobTemplate jt;

      do {
        jt = this.createJobTemplateException();
      } while (this.jobTemplateException);

      String cwd;
      jt.setWorkingDirectory(java.lang.System.getProperty("user.dir"));
      cwd = jt.getWorkingDirectory();
      System.out.println("The working directory is: " + cwd);

      String name;
      jt.setJobName(this.name);
      name = jt.getJobName();
      System.out.println("The jobTemplate name is: " + name);

      jt.setRemoteCommand(this.executable);
      jt.setArgs(this.args);

      jt.setOutputPath("stdout." + GridWaySession.GW_JOB_ID);
      jt.setErrorPath("stderr." + GridWaySession.GW_JOB_ID);

      for (int i = 0; i < this.nJobs; i++) {
        if (jt != null) {
          String id = this.session.runJob(jt);
          System.out.println("Job successfully submitted ID: " + id);
        }
      }
    } catch (Exception e) {
      this.setException(e);
    }
  }
예제 #30
-1
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // finding id on element
    btnSend = (Button) findViewById(R.id.btnSend);
    inputLogin = (EditText) findViewById(R.id.txtChatBox);
    lblWelcome = (TextView) findViewById(R.id.lblWelcome);
    linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
    // create new element
    layoutParams =
        new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    currentContext = this;

    // to fix bug when request socket to server and don't forget add android
    // perminssion internet and android permisiion to network
    java.lang.System.setProperty("java.net.preferIPv4Stack", "true");
    java.lang.System.setProperty("java.net.preferIPv6Addresses", "false");

    btnSend.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            if (btnSend.getText().toString().equals("login")) {
              ProcessAllSocket processTest =
                  new ProcessAllSocket(currentContext, inputLogin.getText().toString());
              processTest.ConnectToSocket(socket, "testActivity");
            } else {
              // showing histori chat from client
              sendChat(
                  linearLayout,
                  layoutParams,
                  inputLogin.getText().toString(),
                  "Me",
                  TestActivity.this);

              // send chat to server
              try {
                processTest.getSocketIo.emit(
                    "chat", new JSONObject().put("msg", inputLogin.getText().toString()));
              } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
            }
          }
        });
  }