Exemple #1
0
  /**
   * 从REGISTER信息中解析出设备信息
   *
   * @return Device
   */
  public Device extractDevice() {
    if (type == FeMessage.TYPE_REGISTER) {
      byte id[] = new byte[8];
      int model = 0;
      int streamLen = 0;
      int sps = 0;
      byte key[] = new byte[16];

      System.arraycopy(body, 0, id, 0, 8);
      model = MessageUtils.bytesToShort(body, 8);
      L.i(
          "<TEST> device model = "
              + Integer.toString((int) (body[8] & 0x00ff))
              + " "
              + Integer.toString((int) (body[9] & 0x00ff)));
      streamLen = body[10] & 0x00ff;

      sps = MessageUtils.bytesToShort(body, 11);
      L.i("<TEST> device sps = " + Integer.toString(sps));

      System.arraycopy(body, 16, key, 0, 16);

      L.i("<TEST> device key = " + new String(body));

      Device dev = new Device(id, model);

      dev.setSps(sps);
      dev.setStreamLen(streamLen);
      dev.setKey(key);
      return dev;
    } else {
      return null;
    }
  }
 public void updateModel(FacesContext context, UIComponent comp) {
   // System.out.println(getDesc(comp, "UPDATE"));
   // System.out.println("  valid: " + isComponentValid(comp));
   // System.out.println("  setLocalValueInValueBinding: " + setLocalValueInValueBinding);
   if (!isComponentValid(comp) || !setLocalValueInValueBinding) {
     return;
   }
   // System.out.println("  value: " + value);
   ValueBinding vb = comp.getValueBinding(name);
   // System.out.println("  vb: " + vb);
   if (vb == null) return;
   try {
     vb.setValue(context, value);
     // System.out.println("  vb.setValue worked");
     clearValue();
   } catch (PropertyNotFoundException e) {
     // System.out.println("PropertyNotFoundException: " + e);
     // It's ok for the application to not use a settable ValueBinding,
     //  since the UIComponent can keep the value. But they probably
     //  don't mean to, so we should log something
     log.info(e);
     // Don't keep trying to set it
     discontinueSettingLocalValueInValueBinding();
   } catch (Exception e) {
     // System.out.println("Exception: " + e);
     String msgId = comp.getClass().getName() + '.' + name;
     Object label = MessageUtils.getComponentLabel(context, comp);
     FacesMessage msg = MessageUtils.getMessage(context, msgId, new Object[] {label, value});
     if (msg != null) context.addMessage(comp.getClientId(context), msg);
     setInvalid(comp);
   }
 }
 // Show error message
 public static void displayExceptionMessage(Context pContext, Exception pE) {
   try {
     LogUtils.LOGD("TAG", "MSG", pE);
     MessageUtils.toast(pContext, pE.toString(), true);
   } catch (Exception e) {
     LogUtils.LOGD("TAG", "MSG", pE);
     MessageUtils.toast(pContext, e.toString(), true);
   }
 }
Exemple #4
0
 /*
  * Ecg
  */
 public static FeMessage createEcg(Ecg ecg, int idx) {
   byte body[] = new byte[2 + 50];
   System.arraycopy(MessageUtils.shortToBytes(idx), 0, body, 0, 2);
   int data[] = ecg.getData();
   for (int m = 0; m < data.length; m++) {
     System.arraycopy(MessageUtils.shortToBytes(data[m]), 0, body, 2 + 2 * m, 2);
   }
   return new FeMessage(TYPE_STREAM_ECG_1, body);
 }
Exemple #5
0
  public static byte[] toBytes(FeMessage msg) {
    byte packet[] = new byte[8 + msg.getBody().length];
    byte msgBody[] = msg.getBody();

    System.arraycopy(FeMessage.HEADER, 0, packet, 0, 4);
    System.arraycopy(MessageUtils.shortToBytes(msg.getType()), 0, packet, 4, 2);
    System.arraycopy(MessageUtils.shortToBytes(msgBody.length), 0, packet, 6, 2);

    System.arraycopy(msgBody, 0, packet, 8, msgBody.length);

    return packet;
  }
Exemple #6
0
 @Override
 protected Index doInBackground() throws Exception {
   int binSize = IgvTools.LINEAR_BIN_SIZE;
   FeatureCodec codec =
       CodecFactory.getCodec(
           file.getAbsolutePath(), GenomeManager.getInstance().getCurrentGenome());
   if (codec != null) {
     try {
       Index index = IndexFactory.createLinearIndex(file, codec, binSize);
       if (index != null) {
         IgvTools.writeTribbleIndex(index, idxFile.getAbsolutePath());
       }
       return index;
     } catch (TribbleException.MalformedFeatureFile e) {
       StringBuffer buf = new StringBuffer();
       buf.append("<html>Files must be sorted by start position prior to indexing.<br>");
       buf.append(e.getMessage());
       buf.append(
           "<br><br>Note: igvtools can be used to sort the file, select \"File > Run igvtools...\".");
       MessageUtils.showMessage(buf.toString());
     }
   } else {
     throw new DataLoadException("Unknown File Type", file.getAbsolutePath());
   }
   return null;
 }
Exemple #7
0
 // Sends the help page for /citizens help
 public static void sendHelpPage(CommandSender sender, int page) {
   switch (page) {
     case 1:
       header(sender, "General", 1, 2);
       sender.sendMessage(
           ChatColor.GREEN
               + "  []"
               + StringUtils.wrap(" - required")
               + "  ()"
               + StringUtils.wrap(" - optional"));
       format(sender, "citizens", "", "display Citizens information");
       format(sender, "citizens", "reload", "reload Citizens files");
       format(sender, "citizens", "save", "force a save of Citizens files");
       format(sender, "citizens", "debug", "toggle Citizens debug mode");
       format(sender, "citizens", "clean", "remove ghost NPCs");
       format(sender, "toggle", "help (page)", "view available toggleable types");
       format(sender, "toggle", "[type]", "toggle an NPC type");
       format(sender, "toggle", "all [on/off]", "toggle all types for an NPC");
       break;
     case 2:
       header(sender, "General", 2, 2);
       format(sender, "npc", "help [page]", "basic NPC help pages");
       format(sender, "[type]", "help", "view the help page for an NPC type");
       footer(sender);
       break;
     default:
       sender.sendMessage(MessageUtils.getMaxPagesMessage(page, 2));
       break;
   }
 }
Exemple #8
0
 public static void requestDial(Activity activity, String tele) {
   if (!TextUtils.isEmpty(tele)) {
     try {
       activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("tel:" + tele)));
     } catch (Exception e) {
       try {
         AlertDialog.Builder builder = MessageUtils.createHoloBuilder(activity);
         builder.setMessage(activity.getText(R.string.ct_call_phone_fail) + tele).create().show();
       } catch (Exception e1) {
         e1.printStackTrace();
       }
     }
   } else {
     MessageUtils.showToast(activity.getString(R.string.ct_null_phone_num));
   }
 }
  public byte[] convert() {
    int offset = 0;
    int TotalLen = pieceLength + 9;
    byte[] result = new byte[TotalLen];
    byte[] blen = intToByte(pieceLength + 5);
    byte[] bindex = intToByte(index);

    for (int i = 0; i != bindex.length; ++i) {
      System.out.println(bindex[i]);
    }

    byte[] btype = new byte[1];
    btype[0] = MessageUtils.convertIntToByte(type);
    System.arraycopy(blen, 0, result, offset, 4);
    offset += 4;

    System.arraycopy(btype, 0, result, offset, 1);
    offset += 1;

    System.arraycopy(bindex, 0, result, offset, 4);
    offset += 4;

    System.arraycopy(piece, 0, result, offset, pieceLength);

    return result;
  }
  @Override
  public int onStartCommand(final Intent intent, final int flags, final int startId) {
    super.onStartCommand(intent, flags, startId);

    if (intent == null) {
      return START_STICKY;
    }

    String action = intent.getAction();
    mLogger.fine("request action: " + action);
    if (action == null) {
      return START_STICKY;
    }

    Bundle resExtra = new Bundle();

    resExtra.putInt(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_ERROR);
    resExtra.putInt(
        DConnectMessage.EXTRA_REQUEST_CODE,
        intent.getIntExtra(DConnectMessage.EXTRA_REQUEST_CODE, -1));
    Intent response = MessageUtils.createResponseIntent(intent.getExtras(), resExtra);
    if (BuildConfig.DEBUG) {
      response.putExtra("debug", "DevicePlugin");
    }

    if (IntentDConnectMessage.ACTION_GET.equals(action)
        || IntentDConnectMessage.ACTION_POST.equals(action)
        || IntentDConnectMessage.ACTION_PUT.equals(action)
        || IntentDConnectMessage.ACTION_DELETE.equals(action)) {
      onRequest(intent, response);
    }

    return START_STICKY;
  }
Exemple #11
0
  /** 解析来自FE的mark数据 (从外部获取时间) */
  public EcgMark extractMark(long startTime) {
    if (type == FeMessage.TYPE_STATUS) {

      int markType = MessageUtils.bytesToShort(body, 0);
      int value = MessageUtils.bytesToInt(body, 2);

      //            L.i("<SIGNAL> mark type = " + Integer.toString(markType) + "  value =" +
      // Integer.toHexString(value));
      return new EcgMark(startTime, startTime, EcgMark.TYPE_GROUP_STATUS, markType, value);
    } else if (type == FeMessage.TYPE_USERINPUT) {
      return new EcgMark(
          startTime, startTime, EcgMark.TYPE_GROUP_PHYSIO, EcgMark.PHYSIO_USERINPUT, 0);
    } else {
      return null;
    }
  }
  /**
   * 受信したリクエストをプロファイルに振り分ける.
   *
   * @param request リクエストパラメータ
   * @param response レスポンスパラメータ
   */
  protected void onRequest(final Intent request, final Intent response) {

    mLogger.fine("request: " + request);
    mLogger.fine("request extras: " + request.getExtras());

    // プロファイル名の取得
    String profileName = request.getStringExtra(DConnectMessage.EXTRA_PROFILE);
    if (profileName == null) {
      MessageUtils.setNotSupportProfileError(response);
      sendResponse(response);
      return;
    }

    // プロファイルを取得する
    DConnectProfile profile = getProfile(profileName);
    if (profile == null) {
      MessageUtils.setNotSupportProfileError(response);
      sendResponse(response);
      return;
    }

    // 各プロファイルでリクエストを処理する
    boolean send = true;
    if (isUseLocalOAuth()) {
      // アクセストークン
      String accessToken = request.getStringExtra(AuthorizationProfile.PARAM_ACCESS_TOKEN);
      // LocalOAuth処理
      CheckAccessTokenResult result =
          LocalOAuth2Main.checkAccessToken(accessToken, profileName, IGNORE_PROFILES);
      if (result.checkResult()) {
        send = profile.onRequest(request, response);
      } else {
        if (accessToken == null) {
          MessageUtils.setEmptyAccessTokenError(response);
        } else if (!result.isExistAccessToken()) {
          MessageUtils.setNotFoundClientId(response);
        } else if (!result.isExistClientId()) {
          MessageUtils.setNotFoundClientId(response);
        } else if (!result.isExistScope()) {
          MessageUtils.setScopeError(response);
        } else if (!result.isNotExpired()) {
          MessageUtils.setExpiredAccessTokenError(response);
        } else {
          MessageUtils.setAuthorizationError(response);
        }
      }
    } else {
      send = profile.onRequest(request, response);
    }

    if (send) {
      // send broad cast
      mLogger.fine("send broadcast: " + response);
      mLogger.fine("send broadcast extra: " + response.getExtras());
      sendResponse(response);
    }
  }
	private static net.jxta.endpoint.Message buildJxtaMessage(Message message, boolean isBroadcast) throws IOException {
		net.jxta.endpoint.Message msg = new net.jxta.endpoint.Message();
		if (isBroadcast) {
			MessageUtils.addStringToMessage(msg, MSG_NAMESPACE_SENDING, MSG_ELEM_COMM_TYPE, COMM_TYPE_BROADCAST);
		}
		else {
			if (message.getReceiver() == null) {
				MessageUtils.addStringToMessage(msg, MSG_NAMESPACE_SENDING, MSG_ELEM_COMM_TYPE, COMM_TYPE_DIRECT_RANDOM);
			}
			else {
				MessageUtils.addStringToMessage(msg, MSG_NAMESPACE_SENDING, MSG_ELEM_COMM_TYPE, COMM_TYPE_DIRECT_SPECIFIED);
			}
		}

		MessageUtils.addObjectToMessage(msg, MSG_NAMESPACE_SENDING, MSG_ELEM_OBJ, message);
		return msg;
	}
Exemple #14
0
  public static void notNull(String varname, Object var) {

    if (var == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, varname));
    }
  }
Exemple #15
0
  public static boolean checkMessage(String s1, String s2, SocketChannel sc) {
    if (s1 == null || s1 == null) {
      sendMessage(sc, MessageUtils.message("<server>", "bad message"));
      System.out.println("Bad message from " + getNickFromSocket(sc));
      return false;
    }

    return true;
  }
Exemple #16
0
  /**
   * 创建认证反馈消息
   *
   * @return
   */
  public static FeMessage createRegAckMsg(Device dev) {
    byte body[] = new byte[FeMessage.getBodyLength(FeMessage.TYPE_REGISTER_ACK, 0, 0)];
    System.arraycopy(dev.getId(), 0, body, 0, 8);
    /*test code */
    body[0] = (byte) 0x00ff;
    body[1] = (byte) 0x00ff;
    System.arraycopy(MessageUtils.shortToBytes(dev.getModel()), 0, body, 8, 2);
    body[10] = (byte) (dev.getStreamLen() & 0x00ff);
    System.arraycopy(MessageUtils.shortToBytes(dev.getSps()), 0, body, 11, 2);

    /*
     *send back the key pair
     */
    /*
     * test code
     */
    dev.setKeyPair("0000000000000000".getBytes());

    System.arraycopy(dev.getKeyPair(), 0, body, 16, 16);
    return new FeMessage(FeMessage.TYPE_REGISTER_ACK, body);
  }
Exemple #17
0
 public Object getIndex() {
   if (worker == null || !worker.isDone()) {
     return null;
   } else {
     try {
       return worker.get();
     } catch (Exception ex) {
       MessageUtils.showMessage(ex.getMessage());
     }
     return null;
   }
 }
Exemple #18
0
  /**
   * 创建标记信息
   *
   * @return
   */
  public static FeMessage createMarkMsg(EcgMark mark) {
    if (mark.getTypeGroup() == EcgMark.TYPE_GROUP_STATUS) {
      byte body[] = new byte[FeMessage.getBodyLength(FeMessage.TYPE_STATUS, 0, 0)];
      body[0] = 0;
      body[1] = 0;

      System.arraycopy(MessageUtils.shortToBytes(mark.getType()), 0, body, 2, 2);
      System.arraycopy(MessageUtils.shortToBytes(mark.getValue()), 0, body, 4, 2);

      return new FeMessage(FeMessage.TYPE_STATUS, body);
    } else if (mark.getTypeGroup() == EcgMark.TYPE_GROUP_PHYSIO) {
      byte body[] = new byte[FeMessage.getBodyLength(FeMessage.TYPE_ANALYSIS_PHSIO, 0, 0)];

      if (mark.getType() == EcgMark.PHYSIO_HR) {
        System.arraycopy(MessageUtils.shortToBytes(1), 0, body, 0, 2);
      } else if (mark.getType() == EcgMark.PHYSIO_BR) {
        System.arraycopy(MessageUtils.shortToBytes(2), 0, body, 0, 2);
      } else {
        System.arraycopy(MessageUtils.shortToBytes(mark.getType()), 0, body, 0, 2);
      }

      System.arraycopy(MessageUtils.shortToBytes(mark.getValue()), 0, body, 2, 2);

      return new FeMessage(FeMessage.TYPE_ANALYSIS_PHSIO, body);
    } else {
      return null;
    }
  }
Exemple #19
0
  public static void disconnectClient(SocketChannel sc) {
    String clientName = getNickFromSocket(sc);
    if (clientName == null) {
      Utils.printErrorAndExit("Error: it could not happen");
    }

    sendMessage(sc, MessageUtils.bye());
    clients.remove(clientName);
    Utils.tryClose(sc);

    notifyAllClients(clientName + " leave this chatroom");
    System.out.println(clientName + " leave this chatroom");
  }
Exemple #20
0
  /**
   * Returns the URL pattern of the {@link javax.faces.webapp.FacesServlet} that is executing the
   * current request. If there are multiple URL patterns, the value returned by <code>
   * HttpServletRequest.getServletPath()</code> and <code>HttpServletRequest.getPathInfo()</code> is
   * used to determine which mapping to return. If no mapping can be determined, it most likely
   * means that this particular request wasn't dispatched through the {@link
   * javax.faces.webapp.FacesServlet}.
   *
   * @param context the {@link FacesContext} of the current request
   * @return the URL pattern of the {@link javax.faces.webapp.FacesServlet} or <code>null</code> if
   *     no mapping can be determined
   * @throws NullPointerException if <code>context</code> is null
   */
  public static String getFacesMapping(FacesContext context) {

    if (context == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }

    // Check for a previously stored mapping
    ExternalContext extContext = context.getExternalContext();
    String mapping = (String) RequestStateManager.get(context, RequestStateManager.INVOCATION_PATH);

    if (mapping == null) {

      // first check for javax.servlet.forward.servlet_path
      // and javax.servlet.forward.path_info for non-null
      // values.  if either is non-null, use this
      // information to generate determine the mapping.

      String servletPath = extContext.getRequestServletPath();
      String pathInfo = extContext.getRequestPathInfo();

      mapping = getMappingForRequest(servletPath, pathInfo);
      if (mapping == null) {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.log(
              Level.FINE,
              "jsf.faces_servlet_mapping_cannot_be_determined_error",
              new Object[] {servletPath});
        }
      }
    }

    // if the FacesServlet is mapped to /* throw an
    // Exception in order to prevent an endless
    // RequestDispatcher loop
    // if ("/*".equals(mapping)) {
    //    throw new FacesException(MessageUtils.getExceptionMessageString(
    //          MessageUtils.FACES_SERVLET_MAPPING_INCORRECT_ID));
    // }

    if (mapping != null) {
      RequestStateManager.set(context, RequestStateManager.INVOCATION_PATH, mapping);
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(
          Level.FINE, "URL pattern of the FacesServlet executing the current request " + mapping);
    }
    return mapping;
  }
		/** {@inheritDoc}
		 */
		@Override
		public void pipeMsgEvent(PipeMsgEvent event) {
			net.jxta.endpoint.Message message = event.getMessage();
			if (message == null || this.pipe==null) {
				return;
			}
			try {
				Message janusMessage = (Message) MessageUtils.getObjectFromMessage(
						message, 
						JanusJXTAGroup.MSG_NAMESPACE_SENDING, 
						JanusJXTAGroup.MSG_ELEM_OBJ);
				boolean isBroadcast = COMM_TYPE_BROADCAST.equals(MessageUtils.getStringFromMessage(message, MSG_NAMESPACE_SENDING, MSG_ELEM_COMM_TYPE));
				

				Address receiver = JanusJXTAGroup.this.processIncomingMessage(janusMessage, isBroadcast);
				
				if (!isBroadcast) {
					// REPLAY the receivers address
					net.jxta.endpoint.Message replay = new net.jxta.endpoint.Message();
					MessageUtils.addObjectToMessage(replay, 
							MSG_NAMESPACE_SENDING, 
							MSG_ELEM_REVEICER_RETURN_ADDRESS, 
							receiver);
					this.pipe.sendMessage(replay);
				}
				this.pipe.close();
				this.pipe.setMessageListener(null);
				this.pipe = null;
			}
			catch (AssertionError ae) {
				throw ae;
			}
			catch (Exception e) {
				Logger.getLogger(getClass().getName()).severe(Throwables.toString(e));
			}
		}
Exemple #22
0
 static void disconnect(boolean mustSendByeMessage) {
   try {
     if (mustSendByeMessage) {
       send(curSocketChannel, MessageUtils.bye());
     }
     if (curSocketChannel != null) {
       curSocketChannel.close();
       servers.remove(curHost);
       isConnected = false;
     }
   } catch (Exception ex) {
     System.err.println(ex.getMessage());
     System.exit(1);
   }
   System.out.println("You have successfully disconnected from the server");
 }
Exemple #23
0
  private void notifyGenomesAddedRemoved(List<GenomeListItem> selectedValues, boolean added) {
    if (selectedValues == null || selectedValues.size() == 0) return;
    int size = selectedValues.size();
    String msg = "";
    if (size == 1) {
      msg += selectedValues.get(0) + " genome";
    } else {
      msg += size + " genomes";
    }
    if (added) {
      msg += " added to";
    } else {
      msg += " removed from";
    }
    msg += " list";

    MessageUtils.setStatusBarMessage(msg);
  }
Exemple #24
0
 static void exit() {
   try {
     Iterator it = servers.entrySet().iterator();
     Map.Entry me;
     while (it.hasNext()) {
       me = (Map.Entry) it.next();
       SocketChannel scToClose = (SocketChannel) me.getValue();
       if (scToClose != null) {
         send(scToClose, MessageUtils.bye());
         scToClose.close();
       }
     }
   } catch (Exception ex) {
     System.err.println(ex.getMessage());
     System.exit(1);
   }
   servers.clear();
   System.out.println("Exit successfully.");
   System.exit(0);
 }
  @Override
  public int onStartCommand(final Intent intent, final int flags, final int startId) {
    super.onStartCommand(intent, flags, startId);

    if (intent == null) {
      mLogger.warning("request intent is null.");
      return START_STICKY;
    }

    String action = intent.getAction();
    if (action == null) {
      mLogger.warning("request action is null. ");
      return START_STICKY;
    }

    if (checkRequestAction(action)) {
      onRequest(intent, MessageUtils.createResponseIntent(intent));
    }

    return START_STICKY;
  }
		/**
		 * {@inheritDoc}
		 */
		@Override
		public void pipeMsgEvent(PipeMsgEvent event) {
			net.jxta.endpoint.Message message = event.getMessage();
			if (message == null) return;
			try {

				this.responseAddress = (AgentAddress) MessageUtils.getObjectFromMessage(
						message, 
						JanusJXTAGroup.MSG_NAMESPACE_SENDING, 
						JanusJXTAGroup.MSG_ELEM_REVEICER_RETURN_ADDRESS);
				synchronized (this.responseLock) {
					this.responseLock.notifyAll();
				}
			}
			catch (AssertionError ae) {
				throw ae;
			}
			catch (Exception e) {
				Logger.getLogger(getClass().getName()).severe(Throwables.toString(e));
			}
		}
 private static void handleQuotationMessage(MessageInfo messageInfo) {
   JSONObject jsonObject = null;
   RequestContext quoRequestContext =
       MessageUtils.getRequestContext(
           messageInfo, "com.kingdee.purchase.openapi", "quotation.getQuotationInfoById", "1");
   Map<String, Object> params = new HashMap<String, Object>();
   params.put("quotationId", messageInfo.getData().get("quotationId"));
   quoRequestContext.setBussinessParams(params);
   AbstractApiProcessor apiProcressor = new AbstractApiProcessor(null, null);
   try {
     jsonObject = apiProcressor.processApiService(quoRequestContext);
     QuotationInfo quoInfo = JSONUtil2.json2QuotationInfo(jsonObject, true);
     quoInfo.setId(new Long(messageInfo.getData().get("quotationId")));
     quoInfo.getSupplier().setDestId(quoInfo.getSupplierMemberId());
     SpringContextUtils.getBean(ISupplierService.class).saveSupplier(quoInfo.getSupplier());
     SpringContextUtils.getBean(IQuotationService.class).saveQuotationInfo(quoInfo);
   } catch (Exception e) {
     e.printStackTrace();
   }
   ;
 }
  @Override
  public boolean execute(MessageEvent event) throws Exception {
    String[] args = event.getMessage().split(" ");
    if (args.length == 2) {
      if (args[1].equalsIgnoreCase("again")) {
        MessageUtils.sendUserNotice(event, "Removing old login!");
        Main.Login.remove(event.getUser().getNick());
        Main.NotLoggedIn.remove(event.getUser().getNick());
        MessageUtils.sendUserNotice(event, "Logging in...");
        String account = Utils.getAccount(event.getUser(), event);
        Main.Login.put(event.getUser().getNick(), account);
        MessageUtils.sendUserNotice(event, "Logged in!");
        return true;
      }
      if (args[1].equalsIgnoreCase("info")) {
        MessageUtils.sendUserNotice(
            event, "You are logged in as: " + Main.Login.get(event.getUser().getNick()));
        MessageUtils.sendUserNotice(
            event,
            "You are in group: "
                + Group(
                    Main.Login.get(event.getUser().getNick()),
                    event.getChannel().getName().toLowerCase()));
        return true;
      }
    }

    if (Main.Login.containsKey(event.getUser().getNick())
        && !Main.NotLoggedIn.contains(event.getUser().getNick())) {
      MessageUtils.sendUserNotice(
          event,
          "You are already logged in! If you want to update login, use \""
              + config.getTrigger()
              + "login again\"");
      return true;
    }
    String account = Utils.getAccount(event.getUser(), event);
    Main.Login.put(event.getUser().getNick(), account);
    Main.NotLoggedIn.remove(event.getUser().getNick());
    MessageUtils.sendUserNotice(event, "You are now Logged in!");
    return true;
  }
Exemple #29
0
  public static void kill(StringTokenizer st) {
    try {
      if (st.hasMoreTokens()) {
        String clientName = st.nextToken();

        if (clients.containsKey(clientName)) {
          SocketChannel clientChannel = clients.get(clientName);
          clients.remove(clientName);
          sendMessage(clientChannel, MessageUtils.bye());
          notifyAllClients(clientName + " leave this chatroom");
          System.out.println(clientName + " leave this chatroom");
          Utils.tryClose(clientChannel);
        } else {
          System.err.println("kill: no such client");
        }
      } else {
        System.err.println("kill: no client name");
      }
    } catch (Exception expt) {
      Utils.printErrorAndExit(expt.getMessage());
    }
  }
Exemple #30
0
  public static void stop() {
    try {
      if (port[0] != -1) {

        for (Entry<String, SocketChannel> client : clients.entrySet()) {
          if (client.getValue().isConnected()) {
            sendMessage(client.getValue(), MessageUtils.bye());
            Utils.tryClose(client.getValue());
          }
        }

        Utils.tryClose(serverSocket);
        clients.clear();
        port[0] = -1;

      } else {
        System.err.println("stop: already stopped");
      }

    } catch (Exception expt) {
      Utils.printErrorAndExit(expt.getMessage());
    }
  }