Example usage for java.util TimerTask TimerTask

List of usage examples for java.util TimerTask TimerTask

Introduction

In this page you can find the example usage for java.util TimerTask TimerTask.

Prototype

protected TimerTask() 

Source Link

Document

Creates a new timer task.

Usage

From source file:cc.kune.core.server.manager.impl.UserManagerDefault.java

@Override
public User login(final String nickOrEmail, final String passwd) {
    User user;//from  w w w .  j  a va2 s. com
    try {
        user = userFinder.findByShortName(nickOrEmail);
    } catch (final NoResultException e) {
        try {
            user = userFinder.findByEmail(nickOrEmail);
        } catch (final NoResultException e2) {
            return null;
        }
    }
    if (PasswordDigest.from(user.getSalt(), user.getDiggest()).verify(passwd.toCharArray())) {
        final I18nLanguage lang = user.getLanguage();
        if (user.getLastLogin() == null) {
            final String userName = user.getShortName();
            final Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // FIXME: Use notifyService!
                    xmppManager.sendMessage(userName, i18n.tWithNT(lang, "This is the chat window. "
                            + "Here you can communicate with other users of [%s] but also with other users with compatible accounts (such as Gmail accounts). "
                            + "Just add a buddy and start chatting.", "",
                            i18n.tWithNT(lang, properties.getSiteCommonName(), "")));
                }
            }, 5000);
        }
        user.setLastLogin(System.currentTimeMillis());
        return user;
    } else {
        return null;
    }
}

From source file:sjizl.com.ChatActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (CommonUtilities.isInternetAvailable(getApplicationContext())) //returns true if internet available
    {//w  ww. j a v  a2s .  c  om

        SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
        pid = sp.getString("pid", null);
        naam = sp.getString("naam", null);
        username = sp.getString("username", null);
        password = sp.getString("password", null);
        foto = sp.getString("foto", null);
        foto_num = sp.getString("foto_num", null);
        Bundle bundle = getIntent().getExtras();
        pid_user = bundle.getString("pid_user");
        user = bundle.getString("user");
        user_foto_num = bundle.getString("user_foto_num");
        user_foto = bundle.getString("user_foto");

        // Toast.makeText(getApplicationContext(), "pid_user"+pid_user, Toast.LENGTH_SHORT).show();

        if (user.equalsIgnoreCase(naam.toString())) {
            Toast.makeText(getApplicationContext(), "You can't message yourself!", Toast.LENGTH_SHORT).show();
            finish();
        }

        AbsListViewBaseActivity.imageLoader.init(ImageLoaderConfiguration.createDefault(getBaseContext()));

        //registerReceiver(mHandleMessageReceiver2, new IntentFilter(DISPLAY_MESSAGE_ACTION));
        setContentView(R.layout.activity_chat);

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d1 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        imageLoader.loadImage("https://www.sjizl.com/fotos/" + foto_num + "/thumbs/" + foto + "",
                new SimpleImageLoadingListener() {
                    @Override
                    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {

                        d2 = new BitmapDrawable(getResources(), loadedImage);

                    }
                });

        smilbtn = (ImageView) findViewById(R.id.smilbtn);
        listView = (ListView) findViewById(android.R.id.list);
        underlayout = (LinearLayout) findViewById(R.id.underlayout);
        smiles_layout = (LinearLayout) findViewById(R.id.smiles);
        textView1_bgtext = (TextView) findViewById(R.id.textView1_bgtext);
        textView1_bgtext.setText(user);
        imageView2_dashboard = (ImageView) findViewById(R.id.imageView2_dashboard);
        imageView1_logo = (ImageView) findViewById(R.id.imageView1_logo);
        imageView_bericht = (ImageView) findViewById(R.id.imageView_bericht);
        textView2_under_title = (TextView) findViewById(R.id.textView2_under_title);
        right_lin = (LinearLayout) findViewById(R.id.right_lin);
        left_lin1 = (LinearLayout) findViewById(R.id.left_lin1);
        left_lin3 = (LinearLayout) findViewById(R.id.left_lin3);
        left_lin4 = (LinearLayout) findViewById(R.id.left_lin4);
        middle_lin = (LinearLayout) findViewById(R.id.middle_lin);
        smile_lin = (LinearLayout) findViewById(R.id.smile_lin);
        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        progressBar_hole = (ProgressBar) findViewById(R.id.progressBar_hole);
        progressBar_hole.setVisibility(View.INVISIBLE);
        imageLoader.displayImage("http://sjizl.com/fotos/" + user_foto_num + "/thumbs/" + user_foto,
                imageView2_dashboard, options);
        new UpdateChat().execute();
        mNewMessage = (EditText) findViewById(R.id.newmsg);

        ber_lin = (LinearLayout) findViewById(R.id.ber_lin);
        photosend = (ImageView) findViewById(R.id.photosend);

        /*
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    
                    
                    
            imageLoader.loadImage("http://sjizl.com/fotos/"+user_foto_num+"/thumbs/"+user_foto, new SimpleImageLoadingListener() {
               @Override
        public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        super.onLoadingComplete(imageUri, view, loadedImage);
                
        Bitmap LoadedImage2 = loadedImage;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
           if(loadedImage!=null){
        LoadedImage2 = CommonUtilities.fastblur16(loadedImage, 4,getApplicationContext());
           }
        }
                
        if (Build.VERSION.SDK_INT >= 16) {
                
           listView.setBackground(new BitmapDrawable(getApplicationContext().getResources(), LoadedImage2));
                
          } else {
                
             listView.setBackgroundDrawable(new BitmapDrawable(LoadedImage2));
          }
                
        }
        }
            );
        }
        */
        final ImageView left_button;
        left_button = (ImageView) findViewById(R.id.imageView1_back);
        CommonUtilities u = new CommonUtilities();
        u.setHeaderConrols(getApplicationContext(), this, right_lin, left_lin3, left_lin4, left_lin1,
                left_button);

        listView.setOnScrollListener(new OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                mScrollState = scrollState;
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
            }

        });
        listView.setLongClickable(true);
        registerForContextMenu(listView);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        viewPager_smiles = new ViewPager(this);
        viewPager_smiles.setId(0x1000);
        LayoutParams layoutParams555 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        layoutParams555.width = LayoutParams.MATCH_PARENT;
        layoutParams555.height = (metrics.heightPixels / 2);
        viewPager_smiles.setLayoutParams(layoutParams555);
        TabsPagerAdapter mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), mNewMessage);
        viewPager_smiles.setAdapter(mAdapter);
        LayoutInflater inflater = null;
        viewPager_smiles.setVisibility(View.VISIBLE);
        smiles_layout.addView(viewPager_smiles);
        smiles_layout.setVisibility(View.GONE);

        left_lin4.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });
        middle_lin.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    Intent profile = new Intent(getApplicationContext(), ProfileActivityMain.class);
                    profile.putExtra("user", user);
                    profile.putExtra("user_foto", user_foto);
                    profile.putExtra("user_foto_num", user_foto_num);
                    profile.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(profile);
                }
                return false;
            }
        });

        smile_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                opensmiles();
            }
        });

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent dashboard = new Intent(getApplicationContext(), ProfileActivityMain.class);
                dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                dashboard.putExtra("user", ArrChatLines.get(position).getNaam());
                dashboard.putExtra("user_foto", foto);
                dashboard.putExtra("user_foto_num", foto_num);
                startActivity(dashboard);
            }
        });

        mNewMessage.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    v.setFocusable(true);
                    v.setFocusableInTouchMode(true);

                    smiles_layout.setVisibility(View.GONE);
                    smilbtn.setImageResource(R.drawable.emoji_btn_normal);
                    return false;
                }
                return false;
            }
        });

        TextWatcher textWatcher = new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //after text changed
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    CommonUtilities.startandsendwebsock(
                            "" + pid_user + " " + naam + " " + pid + " is typing to you ...");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                /*
                 AsyncHttpClient.getDefaultInstance().websocket("ws://sjizl.com:9300", "my-protocol", new WebSocketConnectCallback() {
                  @Override
                     public void onCompleted(Exception ex, WebSocket webSocket) {
                         if (ex != null) {
                   ex.printStackTrace();
                   return;
                         }
                         webSocket.send(""+pid_user+" "+naam+" "+pid+" is typing to you ...");
                                 
                         webSocket.close();
                     }
                 });
                 */
            }
        };

        photosend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ArrChatLines.get(0).getblocked_profile().equals("1")) {

                } else if (ArrChatLines.get(0).getblocked_profile2().equals("1")) {

                } else {
                    openGallery(SELECT_FILE1);
                }
            }
        });

        mNewMessage.addTextChangedListener(textWatcher);

        ber_lin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SpannableStringBuilder spanStr = (SpannableStringBuilder) mNewMessage.getText();
                Spanned cs = (Spanned) mNewMessage.getText();
                String a = Html.toHtml(spanStr);
                String text = mNewMessage.getText().toString();
                mNewMessage.setText("");
                mNewMessage.requestFocus();
                mybmp2 = "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto;
                if (text.length() < 1) {
                } else {
                    addItem(foto, foto_num, "0", naam, text.toString(),
                            "http://sjizl.com/fotos/" + foto_num + "/thumbs/" + foto, "", a);
                }
            }
        });

        hideSoftKeyboard();

    } else {

        Intent dashboard = new Intent(getApplicationContext(), NoInternetActivity.class);
        dashboard.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dashboard);

        finish();
    }
    mNewMessage.clearFocus();
    listView.requestFocus();

    final String wsuri = "ws://sjizl.com:9300";

    WebSocketConnection mConnection8 = new WebSocketConnection();

    if (mConnection8.isConnected()) {
        mConnection8.reconnect();

    } else {
        try {
            mConnection8.connect(wsuri, new WebSocketConnectionHandler() {

                @Override
                public void onOpen() {
                    Log.d("TAG", "Status: Connected to " + wsuri);

                }

                @Override
                public void onTextMessage(String payload) {

                    if (payload.contains("message send")) {
                        String[] parts = payload.split(" ");
                        String zender = parts[0];
                        String send_from = parts[1];
                        String send_name = parts[2];
                        String send_foto = parts[3];
                        String send_foto_num = parts[4];
                        String send_xxx = parts[5];

                        //      Toast.makeText(getApplication(), "" +   "\n zender: "+zender+"" +   "\n pid_user: "+pid_user+"" +"\n pid: "+pid+"" +
                        //         "\n send_from: "+send_from, 
                        //                  Toast.LENGTH_LONG).show();
                        if (zender.equalsIgnoreCase(pid) || zender.equalsIgnoreCase(pid_user)) {

                            if (send_from.equalsIgnoreCase(pid_user) || send_from.equalsIgnoreCase(pid)) {

                                //Toast.makeText(getApplication(), "uu",    Toast.LENGTH_LONG).show();

                                new UpdateChat().execute();

                            }
                        }

                    } else if (payload.contains("is typing to you")) {

                        String[] parts = payload.split(" ");
                        String part1 = parts[0]; // 004
                        is_typing_name = parts[1]; // 034556
                        if (is_typing_name.equalsIgnoreCase(user)) {

                            if (ArrChatLines.size() > 0) {
                                oldvalue = ArrChatLines.get(0).getLaatstOnline();

                            } else {
                                oldvalue = textView2_under_title.getText().toString();
                            }

                            Timer t = new Timer(false);
                            t.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText("typing ...");
                                        }
                                    });
                                }
                            }, 2);

                            Timer t2 = new Timer(false);
                            t2.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            textView2_under_title.setText(oldvalue);
                                        }
                                    });
                                }
                            }, 2000);
                        }

                    }
                    Log.d("TAG", "Got echo: " + payload);
                }

                @Override
                public void onClose(int code, String reason) {
                    Log.d("TAG", "Connection lost.");
                }
            });
        } catch (WebSocketException e) {
            Log.d("TAG", e.toString());
        }
    }

}

From source file:com.sonicle.webtop.core.app.WebTopApp.java

private void scheduleWebappVersionCheckTask() {
    long period = 60000;
    webappVersionCheckTimer = new Timer("webappVersionCheck");
    webappVersionCheckTimer.schedule(new TimerTask() {
        @Override//from w  ww  .  j  a  v a 2  s  .com
        public void run() {
            ThreadState threadState = new SubjectThreadState(adminSubject);
            try {
                threadState.bind();
                instance.onWebappVersionCheck();
            } finally {
                threadState.clear();
            }
        }
    }, period, period);
    logger.info("Task 'webappVersionCheck' scheduled [{}sec]", period / 1000);
}

From source file:org.reunionemu.jreunion.server.MessageParser.java

String parse(Player player, String text) {
    text = text.trim();/*from   w  w w .  j  a v  a 2s . c  o m*/
    String words[] = text.split(" ");
    Client client = player.getClient();
    World world = client.getWorld();
    Command com = world.getCommand();

    if (words[0].equals("@levelup") && player.getAdminState() >= 210) {
        if (words.length > 1) {

            int maxLevel = 400;

            boolean hasMaxLevel = ((maxLevel != 0) ? true : false);

            int lvlup = Integer.parseInt(words[1]);

            if (hasMaxLevel && maxLevel < (player.getLevel() + lvlup)) {
                lvlup = maxLevel - player.getLevel();
            }
            int pCurrLvl = player.getLevel();
            int pSPup = 0;

            if (pCurrLvl < 250) {
                if (pCurrLvl + lvlup > 250) {
                    int pLVLto250 = 250 - pCurrLvl;
                    int pLVLupRest = lvlup - pLVLto250;
                    pSPup = pLVLto250 * 3 + pLVLupRest * 10;
                } else {
                    pSPup = lvlup * 3;
                }
            } else {
                pSPup = lvlup * 10;
            }

            player.setLevel(player.getLevel() + lvlup);
            player.setStatusPoints(player.getStatusPoints() + pSPup);
        }
    } else if (words[0].equals("@walkable") && player.getAdminState() >= 260) {
        Area area = player.getPosition().getLocalMap().getArea();

        int x = 0;
        int y = 0;

        if (words.length == 3) {
            x = Integer.parseInt(words[1]);
            y = Integer.parseInt(words[2]);
            client.sendPacket(Type.SAY, "using arguments");
        } else {
            x = player.getPosition().getX();
            y = player.getPosition().getY();
        }

        if (area.get(x / 10, y / 10, Field.MOB)) {
            client.sendPacket(Type.SAY, "Mob can walk here");
        } else {
            client.sendPacket(Type.SAY, "Mob can't walk here");
        }

        if (area.get(x / 10, y / 10, Field.PLAYER)) {
            client.sendPacket(Type.SAY, "Player can walk here");
        } else {
            client.sendPacket(Type.SAY, "Player can't walk here");
        }
    } else if (words[0].equals("@points")) {
        if (words.length == 3 && (words[1].equals("strength") || words[1].equals("wisdom")
                || words[1].equals("dex") || words[1].equals("strain") || words[1].equals("charisma"))) {
            long pointsToUpgrade = Integer.parseInt(words[2]);

            if (pointsToUpgrade > 0) {
                if (player.getStatusPoints() < pointsToUpgrade)
                    pointsToUpgrade = player.getStatusPoints();

                if (words[1].equals("strength"))
                    player.setStrength(player.getStrength() + pointsToUpgrade);
                else if (words[1].equals("wisdom"))
                    player.setWisdom(player.getWisdom() + pointsToUpgrade);
                else if (words[1].equals("dex"))
                    player.setDexterity(player.getDexterity() + pointsToUpgrade);
                else if (words[1].equals("strain"))
                    player.setConstitution(player.getConstitution() + pointsToUpgrade);
                else if (words[1].equals("charisma"))
                    player.setLeadership(player.getLeadership() + pointsToUpgrade);

                player.setStatusPoints(player.getStatusPoints() + pointsToUpgrade * -1);
            } else
                client.sendPacket(Type.SAY, "You can't enter values < 0");
        } else if (words[1].equals("reskill") && player.getAdminState() >= 120) {
            if (words.length == 7) {
                int strength = Integer.parseInt(words[2]);
                int wisdom = Integer.parseInt(words[3]);
                int dex = Integer.parseInt(words[4]);
                int strain = Integer.parseInt(words[5]);
                int charisma = Integer.parseInt(words[6]);

                boolean allowed = (((player.getRace() == Race.HYBRIDER && strength >= 5 && strength <= 30
                        && wisdom >= 5 && wisdom <= 10 && dex >= 5 && dex <= 10 && strain >= 5 && strain <= 25
                        && charisma >= 5 && charisma <= 5))
                                ? true
                                : (((player.getRace() == Race.AIDIA && strength >= 5 && strength <= 15
                                        && wisdom >= 5 && wisdom <= 30 && dex >= 5 && dex <= 20 && strain >= 5
                                        && strain <= 15 && charisma >= 5 && charisma <= 20))
                                                ? true
                                                : ((player.getRace() == Race.HUMAN && strength >= 5
                                                        && strength <= 15 && wisdom >= 5 && wisdom <= 5
                                                        && dex >= 5 && dex <= 30 && strain >= 5 && strain <= 20
                                                        && charisma >= 5 && charisma <= 10)
                                                                ? true
                                                                : ((player.getRace() == Race.KAILIPTON
                                                                        && strength >= 5 && strength <= 15
                                                                        && wisdom >= 5 && wisdom <= 30
                                                                        && dex >= 5 && dex <= 5 && strain >= 5
                                                                        && strain <= 15 && charisma >= 5
                                                                        && charisma <= 15)
                                                                                ? true
                                                                                : ((player
                                                                                        .getRace() == Race.BULKAN
                                                                                        && strength >= 5
                                                                                        && strength <= 30
                                                                                        && wisdom >= 5
                                                                                        && wisdom <= 5
                                                                                        && dex >= 5 && dex <= 5
                                                                                        && strain >= 5
                                                                                        && strain <= 30
                                                                                        && charisma >= 5
                                                                                        && charisma <= 10)
                                                                                                ? true
                                                                                                : false)))));

                int sumuSP = strength + wisdom + dex + strain + charisma;

                if (allowed) {
                    player.setStrength(strength);
                    player.setWisdom(wisdom);
                    player.setDexterity(dex);
                    player.setConstitution(strain);
                    player.setLeadership(charisma);

                    player.resetSkills();

                    sumuSP = 80 - sumuSP - 3;
                    player.setStatusPoints(player.getMaxStatusPoints() + sumuSP);
                } else
                    client.sendPacket(Type.SAY,
                            "Sum of Strength, Wisdom, Dex, Stain and charisma must be between 25 and 80");
            } else {
                player.setStrength(5);
                player.setWisdom(5);
                player.setDexterity(5);
                player.setConstitution(5);
                player.setLeadership(5);

                player.resetSkills();

                player.setStatusPoints(player.getMaxStatusPoints() + 55);
            }
        }
    } else if ((words[0].equals("@getlime") || words[0].equals("@gl")) && player.getAdminState() >= 260) {
        if (words.length == 2) {
            try {
                long playerAddLime = Long.parseLong(words[1]);
                long newLime = player.getLime() + playerAddLime;

                if (newLime > Long.MAX_VALUE) {
                    newLime = Long.MAX_VALUE;
                }

                if (newLime > 0) {
                    player.setLime(newLime);
                    client.sendPacket(Type.SAY, "New Lime :" + newLime);
                } else {
                    client.sendPacket(Type.SAY, "Your new Lime value cant be negative!");
                }
            } catch (Exception e) {
                client.sendPacket(Type.SAY, "Wrong Lime Value");
            }
        }
    } else if (words[0].equals("@guild")) {
        if (words[1].equals("create") && player.getAdminState() >= 120) {
            if (words.length == 3) {
                String name = (String) words[2];

                int guildId = DatabaseUtils.getDinamicInstance().addGuild(name);
                if (guildId != 0) {
                    player.setGuildId(guildId);
                    player.setGuildLevel(10);
                    player.setGuildName(name);

                    player.getClient().sendPacket(Type.GUILD_NAME, player);
                    player.getClient().sendPacket(Type.GUILD_GRADE, player);
                    player.getClient().sendPacket(Type.GUILD_LEVEL, player);

                    player.getInterested().sendPacket(Type.GUILD_NAME, player);
                    player.getInterested().sendPacket(Type.GUILD_GRADE, player);
                    player.getInterested().sendPacket(Type.GUILD_LEVEL, player);
                }
            } else if (words.length == 4) {
                String name = (String) words[2];

                int guildId = DatabaseUtils.getDinamicInstance().addGuild(name);
                if (guildId != 0) {
                    Player targetPlayer = Server.getInstance().getWorld().getPlayerManager()
                            .getPlayer(words[3]);

                    targetPlayer.setGuildId(guildId);
                    targetPlayer.setGuildLevel(10);
                    targetPlayer.setGuildName(name);

                    targetPlayer.getClient().sendPacket(Type.GUILD_NAME, targetPlayer);
                    targetPlayer.getClient().sendPacket(Type.GUILD_GRADE, targetPlayer);
                    targetPlayer.getClient().sendPacket(Type.GUILD_LEVEL, targetPlayer);

                    targetPlayer.getInterested().sendPacket(Type.GUILD_NAME, targetPlayer);
                    targetPlayer.getInterested().sendPacket(Type.GUILD_GRADE, targetPlayer);
                    targetPlayer.getInterested().sendPacket(Type.GUILD_LEVEL, targetPlayer);
                }
            }
        } else if (words[1].equals("add")) {
            if (player.getGuildId() != 0 && player.getGuildLvl() > 1) {
                Player targetPlayer = Server.getInstance().getWorld().getPlayerManager().getPlayer(words[2]);

                //client.sendPacket(Type.SAY, "Your Guild: "+player.getGuildName()+" req:"+targetPlayer.getGuildRequestName());

                if (targetPlayer.getGuildRequestName().equals(player.getGuildName())) {
                    targetPlayer.setGuildId(player.getGuildId());
                    targetPlayer.setGuildName(player.getGuildName());

                    if (words.length == 4)
                        targetPlayer.setGuildLevel(Integer.parseInt(words[3]));
                    else
                        targetPlayer.setGuildLevel(1);

                    targetPlayer.getClient().sendPacket(Type.GUILD_NAME, targetPlayer);
                    targetPlayer.getClient().sendPacket(Type.GUILD_GRADE, targetPlayer);
                    targetPlayer.getClient().sendPacket(Type.GUILD_LEVEL, targetPlayer);

                    targetPlayer.getInterested().sendPacket(Type.GUILD_NAME, targetPlayer);
                    targetPlayer.getInterested().sendPacket(Type.GUILD_GRADE, targetPlayer);
                    targetPlayer.getInterested().sendPacket(Type.GUILD_LEVEL, targetPlayer);

                    targetPlayer.getClient().sendPacket(Type.SAY, "You've been accepted to join guild");

                    client.sendPacket(Type.SAY, "Added Player " + targetPlayer.getName() + " to guild ");
                } else {
                    client.sendPacket(Type.SAY,
                            "Player " + targetPlayer.getName() + " didnt requested membership");
                }
            } else {
                client.sendPacket(Type.SAY, "You are not in a guild or you dont have permission to add member");
            }
        } else if (words[1].equals("changeMember")) {
            if (words.length == 4) {
                try {
                    Player targetPlayer = Server.getInstance().getWorld().getPlayerManager()
                            .getPlayer(words[2]);

                    if (targetPlayer.getGuildId() == player.getGuildId()
                            && (player.getGuildLvl() > targetPlayer.getGuildLvl()
                                    || player.getGuildLvl() == 10)) {
                        targetPlayer.setGuildLevel(Integer.parseInt(words[3]));

                        targetPlayer.getClient().sendPacket(Type.GUILD_GRADE, targetPlayer);
                        targetPlayer.getInterested().sendPacket(Type.GUILD_GRADE, targetPlayer);
                        targetPlayer.getClient().sendPacket(Type.GUILD_LEVEL, targetPlayer);
                        targetPlayer.getInterested().sendPacket(Type.GUILD_LEVEL, targetPlayer);

                        client.sendPacket(Type.SAY,
                                "Guildlevel of Player " + words[2] + " changed to " + words[3]);
                        targetPlayer.getClient().sendPacket(Type.SAY,
                                "Your Guildlevel changed by " + player.getName() + " to " + words[3]);
                    }
                } catch (Exception e) {
                    client.sendPacket(Type.SAY, "Player " + words[2] + " is not online!");
                }
            } else
                client.sendPacket(Type.SAY, "Wrong Parameters, @guild changeUser Name Level");
        } else if (words[1].equals("close")) {
            if (player.getGuildId() != 0 && player.getGuildLvl() == 10) {
                DatabaseUtils.getDinamicInstance().deleteGuild((int) player.getGuildId());

                Iterator<Player> iterPlayer = Server.getInstance().getWorld().getPlayerManager()
                        .getPlayerListIterator();

                long guildId = player.getGuildId();

                while (iterPlayer.hasNext()) {
                    Player currplayer = iterPlayer.next();

                    if (currplayer.getGuildId() == guildId) {
                        currplayer.setGuildId(0);
                        currplayer.setGuildName("");
                        currplayer.setGuildLevel(0);

                        currplayer.getClient().sendPacket(Type.GUILD_NAME, currplayer);

                        currplayer.getInterested().sendPacket(Type.GUILD_NAME, currplayer);
                    }
                }
            } else {
                client.sendPacket(Type.SAY, "You dont have a guild");
            }
        } else if (words[1].equals("req")) {
            if (words.length == 3) {
                if (player.getGuildId() != 0) {
                    client.sendPacket(Type.SAY,
                            "You are allready in guild " + player.getGuildName() + " leave that first");
                } else {
                    player.setGuildRequestName(words[2]);
                    client.sendPacket(Type.SAY, "You applyed for guild membership on " + words[2]);
                }
            }
        } else if (words[1].equals("leave")) {
            if (words.length == 2 && player.getGuildId() != -1) {
                player.setGuildId(0);
                player.setGuildLevel(0);
                player.setGuildName("");

                client.sendPacket(Type.GUILD_NAME, player);
                player.getInterested().sendPacket(Type.GUILD_NAME, player);

                client.sendPacket(Type.SAY, "You left your guild");
            } else {
                client.sendPacket(Type.SAY, "You are in no guild");
            }
        } else if (words[1].equals("kick")) {
            if (words.length == 3) {
                if (player.getGuildLvl() > 1) {
                    Player targetPlayer = Server.getInstance().getWorld().getPlayerManager()
                            .getPlayer(words[2]);

                    if (targetPlayer.getGuildId() == player.getGuildId()) {
                        if (player.getGuildLvl() > 8) {
                            targetPlayer.setGuildId(0);
                            targetPlayer.setGuildLevel(0);
                            targetPlayer.setGuildName("");

                            targetPlayer.getInterested().sendPacket(Type.GUILD_NAME, targetPlayer);
                            targetPlayer.getClient().sendPacket(Type.GUILD_NAME, targetPlayer);
                            targetPlayer.getClient().sendPacket(Type.SAY, "You've got kicked out of guild");
                            client.sendPacket(Type.SAY,
                                    "You've kicked " + targetPlayer.getName() + " out of guild");
                        }
                    }
                } else {
                    client.sendPacket(Type.SAY, "You don't have the right to kick players out of guild!");
                }
            }
        } else if (words[1].equals("info")) {
            Iterator<Player> iterPlayer = Server.getInstance().getWorld().getPlayerManager()
                    .getPlayerListIterator();

            long guildId = player.getGuildId();

            String gPlayer = "";

            boolean online = false;

            if (guildId != 0) {
                client.sendPacket(Type.SAY, "Who is online in your guild (" + player.getGuildName() + "):");
                while (iterPlayer.hasNext()) {
                    Player currplayer = iterPlayer.next();

                    if (currplayer.getGuildId() == guildId) {
                        online = true;
                        gPlayer = currplayer.getName() + " (Lv." + currplayer.getLevel() + " Map:"
                                + currplayer.getPosition().getMap().getName() + ")";

                        client.sendPacket(Type.SAY, gPlayer);
                    }
                }
                if (!online)
                    client.sendPacket(Type.SAY, "No guild member online!");
            }
        }

        //client.getWorld().sendPacket(Type.GUILD_SAY, data,player);
    } else if (words[0].equals("@online")) {
        if (player.getAdminState() >= 200) {
            Iterator<Player> iterPlayer = Server.getInstance().getWorld().getPlayerManager()
                    .getPlayerListIterator();

            if (player.getAdminState() >= 120) {
                client.sendPacket(Type.G_POS_START);
            }
            while (iterPlayer.hasNext()) {
                Player currplayer = iterPlayer.next();

                if (currplayer.getPosition().getMap() == player.getPosition().getMap() && currplayer != player)
                    client.sendPacket(Type.G_POS_BODY, currplayer);
            }
            if (player.getAdminState() >= 200) {
                client.sendPacket(Type.G_POS_END);
            }
        }
        client.sendPacket(Type.SAY,
                "Online Players: " + Server.getInstance().getWorld().getPlayerManager().getNumberOfPlayers());
    } else if (words[0].equals("@event") && player.getAdminState() >= 120) {
        if (words.length == 3) {
            if (words[1].equals("exp")) {
                if (Server.getInstance().getWorld().getServerSetings().getXp() < Long.parseLong(words[2]))
                    Server.getInstance().getWorld().sendPacket(Type.INFO,
                            "EXP Event (x" + words[2] + ") started!");
                else if (Server.getInstance().getWorld().getServerSetings().getXp() > Long.parseLong(words[2]))
                    Server.getInstance().getWorld().sendPacket(Type.INFO, "EXP Event has ended!");
                Server.getInstance().getWorld().getServerSetings().setXp(Long.parseLong(words[2]));
            } else if (words[1].equals("lime")) {
                if (Server.getInstance().getWorld().getServerSetings().getLime() < Long.parseLong(words[2]))
                    Server.getInstance().getWorld().sendPacket(Type.INFO,
                            "Lime Event (x" + words[2] + ") started!");
                else if (Server.getInstance().getWorld().getServerSetings().getLime() > Long
                        .parseLong(words[2]))
                    Server.getInstance().getWorld().sendPacket(Type.INFO, "Lime Event has ended!");
                Server.getInstance().getWorld().getServerSetings().setLime(Long.parseLong(words[2]));

            }
        }
    } else if (words[0].equals("@kick") && player.getAdminState() >= 200) {
        if (words.length == 2) {
            Player targetPlayer = Server.getInstance().getWorld().getPlayerManager().getPlayer(words[1]);

            client.sendPacket(Type.SAY, "Player " + targetPlayer.getName() + " kicked");

            targetPlayer.getClient().disconnect();
        }
    } else if (words[0].equals("@global") && player.getAdminState() >= 120) //Global chat is with -[space]Your message
    {
        int lengthofinfo = words.length;
        String data = "";
        for (int i = 1; i < lengthofinfo; i++) {
            data += " " + words[i];
        }
        client.getWorld().sendPacket(Type.SAY, data, player);
    }

    else if (words[0].equals("@shutdown") && player.getAdminState() >= 260) {
        final Iterator<Player> iterPlayer = Server.getInstance().getWorld().getPlayerManager()
                .getPlayerListIterator();
        final World worldShutdown = world;

        final Client clientU = client;
        Timer t = new Timer();
        t.schedule(new TimerTask() {
            int counter = 30;

            @Override
            public void run() {
                if (counter > 0) {
                    worldShutdown.sendPacket(Type.INFO,
                            "Server shutdown immediately! (" + counter + " Seconds)");
                }
                if (counter == 5) {
                    while (iterPlayer.hasNext()) {
                        Player currplayer = iterPlayer.next();
                        Client pClient = currplayer.getClient();
                        currplayer.save();
                        pClient.sendPacket(Type.SAY, currplayer.getName() + " saved ...");
                    }
                } else if (counter <= 0) {
                    System.exit(1);
                }
                counter -= 5;
            }
        }, 0, 5000); //all 5 seconds
    }

    else if (words[0].equals("@fp") && player.getAdminState() >= 260) {
        String packetData = "";
        for (int i = 1; i <= (words.length - 1); i++) {
            packetData = packetData + words[i];
            if (i < (words.length - 1))
                packetData = packetData + " ";
        }

        client.sendData(packetData);
    }

    else if (words[0].equals("@eid") && player.getAdminState() >= 260) {
        if (words.length == 1)
            client.sendPacket(Type.SAY, "Your EntityID is: " + player.getEntityId());
        else if (words.length > 1) {
            Player target = Server.getInstance().getWorld().getPlayerManager().getPlayer(words[1]);
            client.sendPacket(Type.SAY, "EntityID of " + words[1] + " is " + target.getEntityId());
        }
    }

    else if (words[0].equals("@testcol") && player.getAdminState() >= 260) {
        Player p = player;

        LocalMap map = p.getPosition().getLocalMap();
        Area area = map.getArea();

        String s1 = "" + area.get(p.getPosition().getX() / 10, p.getPosition().getY() / 10, Field.PLAYER);
        String s2 = "" + area.get(p.getPosition().getX() / 10, p.getPosition().getY() / 10, Field.MOB);
        String s3 = "" + area.get(p.getPosition().getX() / 10, p.getPosition().getY() / 10, Field.PVP);

        com.serverSay("(" + p.getPosition().getX() / 10 + "," + p.getPosition().getY() / 10 + ")"
                + "collision test: " + s1 + " " + s2 + " " + s3);
    } else if ((words[0].equals("@d") || words[0].equals("@drop")) && player.getAdminState() >= 259) { //Drop Item
        if (words.length >= 2) {
            ItemManager itemManager = world.getItemManager();
            try {

                Item<?> item = itemManager.create(Integer.parseInt(words[1]));
                player.getPosition().getLocalMap().createEntityId(item);

                if (words.length == 6) {
                    int gemNumber = 0;
                    if (item.getType().isUpgradable()) {
                        gemNumber = Integer.parseInt(words[2]);
                        gemNumber = gemNumber > 15 ? 15 : gemNumber;
                    } else {
                        client.sendPacket(Type.SAY, item.getType().getName() + " it's not upgradable.");
                    }
                    int extraStats = ((words[3].length() <= 8) ? Integer.parseInt(words[3]) : 0);
                    int unknown1 = Integer.parseInt(words[4]);
                    int unknown2 = Integer.parseInt(words[5]);

                    item.setGemNumber(gemNumber);
                    item.setExtraStats(extraStats);
                    item.setDurability(item.getType().getMaxDurability());
                    item.setUnknown1(unknown1);
                    item.setUnknown2(unknown2);
                } else {
                    item.setGemNumber(0);
                    item.setExtraStats(item.getType().getMaxExtraStats());
                    item.setDurability(item.getType().getMaxDurability());
                    item.setUnknown1(0);
                    item.setUnknown2(0);
                }
                RoamingItem roamingItem = com.dropItem(player.getPosition(), item, player);
                LoggerFactory.getLogger(MessageParser.class)
                        .info("Player " + player + " droped roaming item " + roamingItem);

            } catch (Exception e) {
                client.sendPacket(Type.SAY, "@drop failed (ID:" + words[1] + ")");
            }
        }
    } else if ((words[0].equals("@gi") || words[0].equals("@getitem")) && player.getAdminState() >= 258) {
        ItemManager itemManager = world.getItemManager();
        try {
            int amount = ((words.length == 2) ? 1 : Integer.parseInt(words[2]));

            for (int i = 1; i <= amount; i++) {
                Item<?> item = itemManager.create(Integer.parseInt(words[1]));
                player.getPosition().getLocalMap().createEntityId(item);
                if (words.length == 7) {
                    int gemNumber = 0;
                    if (item.getType().isUpgradable()) {
                        gemNumber = Integer.parseInt(words[3]);
                        gemNumber = gemNumber > 15 ? 15 : gemNumber;
                    } else {
                        client.sendPacket(Type.SAY, item.getType().getName() + " it's not upgradable.");
                    }
                    int extraStats = ((words[4].length() <= 8) ? Integer.parseInt(words[4]) : 0);
                    int unknown1 = Integer.parseInt(words[5]);
                    int unknown2 = Integer.parseInt(words[6]);

                    item.setGemNumber(gemNumber);
                    item.setExtraStats(extraStats);
                    item.setDurability(item.getType().getMaxDurability());
                    item.setUnknown1(unknown1);
                    item.setUnknown2(unknown2);
                } else {
                    item.setGemNumber(0);
                    item.setExtraStats(item.getType().getMaxExtraStats());
                    item.setDurability(item.getType().getMaxDurability());
                    item.setUnknown1(0);
                    item.setUnknown2(0);
                }
                int[] tabPosition = player.getInventory().getFreeSlots(item, -1);
                if (tabPosition == null) {
                    if (player.getInventory().getHoldingItem() == null) {
                        player.getInventory().setHoldingItem(new HandPosition(item));
                        player.getClient().sendPacket(Type.EXTRA, item);
                    } else {
                        player.getClient().sendPacket(Type.SAY,
                                "Inventory full. Please get some space available.");
                        player.getPosition().getLocalMap().removeEntity(item);
                        DatabaseUtils.getDinamicInstance().deleteItem(item.getItemId());
                        return null;
                    }
                } else {
                    player.pickItem(item, tabPosition[0]);
                }
            }
        } catch (Exception e) {
            client.sendPacket(Type.SAY, "@drop failed (ID:" + words[1] + ")");
        }
    } else if (words[0].equals("@info") && player.getAdminState() >= 120) {
        int lengthofinfo = words.length;
        String data = "";
        for (int i = 1; i < lengthofinfo; i++) {
            data += " " + words[i];
        }
        client.getWorld().sendPacket(Type.INFO, "- " + data + " -");
    } else if (words[0].equals("@addmob") && player.getAdminState() >= 200) { //Adds a mob type NPC 
        if (words.length == 2 || words.length == 3) {
            int count = 0;
            try {
                count = words.length == 3 ? Integer.parseInt(words[2]) : 1;

                if (count > 5)
                    count = 5;

                for (int x = 0; x < count; x++) {
                    NpcSpawn spawn = new NpcSpawn();
                    spawn.setPosition(player.getPosition().clone());
                    spawn.setNpcType(Integer.parseInt(words[1]));
                    spawn.setRadius(300);
                    spawn.setRespawnTime(-1);
                    spawn.spawn();
                }
            } catch (Exception NumberFormatException) {
                client.sendPacket(Type.SAY, "@addmob with " + count + " mob failed");
            }
        } else if (words.length == 6) {
            //LocalMap map = player.getPosition().getLocalMap();
            //Mob mobType = (Mob)Npc.create(Integer.parseInt(words[1]));
            Npc<?> mob = client.getWorld().getNpcManager().create(Integer.parseInt(words[1]));

            mob.getPosition().setX(player.getPosition().getX() + 10);
            mob.getPosition().setY(player.getPosition().getY() + 10);
            mob.setIsRunning(true);
            mob.setMutantType(Integer.parseInt(words[2]));
            mob.setUnknown1(Integer.parseInt(words[3]));
            mob.getType().setNeoProgmare(Integer.parseInt(words[4]));
            mob.setUnknown2(Integer.parseInt(words[5]));
            //Server.getInstance().getWorld().getMobManager().addMob(mob);
        }
    } else if (words[0].equals("@addnpc") && player.getAdminState() >= 200) { //adds a NPC
        try {
            if (words.length == 2) {

                NpcSpawn spawn = new NpcSpawn();

                spawn.setPosition(player.getPosition().clone());
                spawn.setNpcType(Integer.parseInt(words[1]));
                spawn.spawn();

            }
        } catch (Exception e) {
            //TODO: Fix the Mob id error server crash
            LoggerFactory.getLogger(this.getClass()).error("Npc id error detected");
        }
    } else if (words[0].equals("@tele") && player.getAdminState() >= 40) {
        try {
            String worldname = words[1];
            ParsedItem mapref = Reference.getInstance().getMapConfigReference().getItem(worldname);

            if (mapref != null) {
                int mapId = Integer.parseInt(mapref.getMemberValue("Id"));
                Map map = Server.getInstance().getWorld().getMap(mapId);

                if (map != null) {
                    com.GoToWorld(player, map, 0);
                }
            } else {
                client.sendPacket(Type.SAY, "@tele failed -> @tele worldname");
            }
        } catch (Exception e) {

        }
    } else if (words[0].equals("@goto") && player.getAdminState() >= 150) {
        if (words[1].equals("pos")) { //@goto pos [X] [Y]
            Position position = player.getPosition().clone();
            position.setX(Integer.parseInt(words[2]));
            position.setY(Integer.parseInt(words[3]));
            com.GoToPos(player, position);
        }
        if (words[1].equals("char")) { //@goto char
            com.GoToChar(player, words[2]);
        }

    } else if (words[0].equals("@save")) {
        if (words.length == 1) {
            player.save();
            client.sendPacket(Type.SAY, player.getName() + " saved ...");
        } else if (words.length == 2 && words[1].equals("all") && player.getAdminState() >= 200) {
            Iterator<Player> iterPlayer = Server.getInstance().getWorld().getPlayerManager()
                    .getPlayerListIterator();

            while (iterPlayer.hasNext()) {
                Player currplayer = iterPlayer.next();
                Client pclient = currplayer.getClient();
                currplayer.save();
                pclient.sendPacket(Type.SAY, currplayer.getName() + " saved ...");
            }
        } else if (words.length == 2 && player.getAdminState() >= 200) {
            try {
                Player target = Server.getInstance().getWorld().getPlayerManager().getPlayer(words[1]);
                target.save();
                client.sendPacket(Type.SAY, words[1] + " saved ...");
            } catch (Exception e) {
                client.sendPacket(Type.SAY, "Player " + words[1] + " is not online or saving failed");
            }
        }
    } else if (words[0].equals("@debug") && player.getAdminState() >= 260) {

        org.apache.log4j.Logger root = org.apache.log4j.Logger.getRootLogger();

        String host = words[1];
        InetAddress address = null;
        try {
            address = InetAddress.getByName(host);
            int port = Integer.parseInt(words[2]);
            SocketAppender socketAppender = new SocketAppender(address, port);
            socketAppender.setReconnectionDelay(10);
            root.addAppender(socketAppender);

        } catch (UnknownHostException e) {

            LoggerFactory.getLogger(MessageParser.class).warn("host(" + host + ") not found in @debug", e);
            com.serverTell(client, "Host not found");
        }
        client.sendPacket(Type.SAY, "Spawnpoint cannot be added");
        com.serverTell(client, "Logger connected");
    } else if (words[0].equals("@spot")) {
        client.sendPacket(Type.SAY, "{ X:" + player.getPosition().getX() + ", Y:" + player.getPosition().getY()
                + ", Z:" + player.getPosition().getZ() + "}");
    }

    else if (words[0].equals("@resetskills") && player.getAdminState() >= 260) {
        java.util.Map<Skill, Integer> affectedSkills = new HashMap<Skill, Integer>();

        if (words.length == 2) { //@resetskills [skillID]
            int skillId = Integer.parseInt(words[1]);
            Skill skill = player.getSkill(skillId);

            if (skill == null) {
                client.sendPacket(Type.SAY, "SkillID " + skillId + " don't bellong to " + player.getRace());
                return null;
            }

            affectedSkills.put(skill, player.getSkillLevel(skill));

        } else //@resetskills
            affectedSkills = player.getSkills();

        // reset player skills to its minimum level
        for (Skill skill : affectedSkills.keySet()) {
            skill.reset(player);
        }
    }
    // order a mob to attack player several times: @mobattack [mobUniqueID] [numberOfattacks]
    else if (words[0].equals("@mobattack") && player.getAdminState() >= 260) {
        if (words.length < 2) { // command to short
            client.sendPacket(Type.SAY,
                    "USAGE: @mobattack [mobUniqueID] / @mobattack [mobUniqueID] [numberOfAttacks]");
            return "";
        }
        int numberOfAttacks = 1;
        // get mob by entity
        Mob mob = (Mob) player.getPosition().getLocalMap().getEntity(Integer.parseInt(words[1]));
        if (words.length == 3) { // get number of attacks
            numberOfAttacks = Integer.parseInt(words[2]);
        }
        // sends the several mob attack packets
        for (int attacksCounter = numberOfAttacks; attacksCounter > 0; attacksCounter--) {
            mob.attack(player);
            player.getClient().sendPacket(Type.ATTACK, mob, player, 0);
            if (player.getHp() <= 0) {
                break;
            }
        }
    } else if (words[0].equals("@quest") && player.getAdminState() >= 260) {
        if (words.length == 2) {
            try {
                int questId = Integer.parseInt(words[1]);
                Quest quest = player.getQuest();

                if (quest != null)
                    player.setQuest(null);

                //quest = new Quest(questId); //used only to send the quest id packet
                //quest = QuestFactory.loadQuest(questId); //load full quest from database
                quest = questDao.findById(questId);

                player.setQuest(quest);

                player.getClient().sendPacket(Type.QT, "get " + quest.getId());

                /*
                player.getClient().sendPacket(Type.SAY, "Quest: "+quest.getID()+" "+quest.getDescrition()+" ("+quest.getType().byValue()+")");      
                for(Objective objective: quest.getObjectives()){
                   player.getClient().sendPacket(Type.SAY, "Objective: [ID] "+objective.getId()+" [QT] "+objective.getAmmount()+" [TYPE] "+objective.getType().byValue());
                }
                for(Reward reward: quest.getRewards()){
                   player.getClient().sendPacket(Type.SAY, "Reward: [ID] "+reward.getId()+" [QT] "+reward.getAmmount()+" [TYPE] "+reward.getType().byValue());
                }
                */

            } catch (Exception e) {
                client.sendPacket(Type.SAY, "@quest failed (ID:" + words[1] + ")");
            }
        } else {
            player.getClient().sendPacket(Type.SAY, "Correct usage: @quest [questID]");
        }
    } else if (words[0].equals("@mobs_movement") && player.getAdminState() >= 250) {
        if (words.length == 2) {
            if (words[1].equals("enable") || words[1].equals("1")) {
                Server.getInstance().getWorld().getServerSetings().setMobsMovement(1);
            } else if (words[1].equals("disable") || words[1].equals("0")) {
                Server.getInstance().getWorld().getServerSetings().setMobsMovement(0);
            } else if (words[1].equals("restart") || words[1].equals("2")) {
                player.getPosition().getLocalMap().stopMobsAI();
                player.getPosition().getLocalMap().startMobsAI(1000);
            } else {
                player.getClient().sendPacket(Type.SAY,
                        "USAGE: @mobs_movement [enable/disable] / @mobs_movement [0/1]");
            }
        } else {
            player.getClient().sendPacket(Type.SAY,
                    "USAGE: @mobs_movement [enable/disable] / @mobs_movement [0/1]");
        }
    } else if (words[0].equals("@delete") && player.getAdminState() >= 260) {
        if (words[1].equals("item")) {
            LocalMap localMap = player.getPosition().getLocalMap();

            if (words.length == 2) { //deletes all RoamingItems from LocalMap
                for (RoamingItem roamingItem : localMap.getRoamingItemList()) {
                    roamingItem.delete();
                    LoggerFactory.getLogger(MessageParser.class)
                            .info("Player " + player + " deleted roaming item " + roamingItem);
                }
            } else { //deletes only the given RoamingItem from LocalMap
                int roamingItementityId = Integer.parseInt(words[2]);
                RoamingItem roamingItem = (RoamingItem) localMap.getEntity(roamingItementityId);
                roamingItem.delete();
                LoggerFactory.getLogger(MessageParser.class)
                        .info("Player " + player + " deleted roaming item " + roamingItem);
            }
        }

    } else if (words[0].equals("@special") && player.getAdminState() >= 260) {
        int isActivated = 1;
        int typeId = 0;
        int[] availableTypeId = { 10003, 10011, 10012, 10013, 10014, 10015, 10016, 10017, 10018, 10019, 10020,
                10021, 10022, 10023, 10024, 10025, 10026, 10027, 10028 };

        if (words.length == 3) {
            typeId = Integer.parseInt(words[1]);
            isActivated = Integer.parseInt(words[2]);
        } else if (words.length == 2) {
            if (words[1].equals("alladd"))
                isActivated = 1;
            if (words[1].equals("allremove"))
                isActivated = 0;
            for (int id : availableTypeId) {
                player.getClient().sendPacket(Type.K, isActivated, player, id);
                player.getInterested().sendPacket(Type.K, isActivated, player, id);
            }
        } else if (words.length == 1) {
            int typeIdPos = 100;
            while (typeIdPos > 18)
                typeIdPos = (int) (Math.random() * 100);
            typeId = availableTypeId[typeIdPos];
        }

        player.getClient().sendPacket(Type.K, isActivated, player, typeId);
        player.getInterested().sendPacket(Type.K, isActivated, player, typeId);

        // (10003: fairy)**
        // (10011: gold pig)*
        // (10012: pink pig)*
        // (10013: black pig)
        // (10014: yellow pig)
        // (10015: red ghost)**
        // (10016: blue ghost)
        // (10017: yellow ghost)
        // (10018: red bat)**
        // (10019: red reindeer)**
        // (10020: ring of white light)**
        // (10021: ring of purple light)
        // (10022: ring of red light)
        // (10023: ring of blue light)
        // (10024: ring of green light)
        // (10025: black reindeer)
        // (10026: blue reindeer)
        // (10027: green reindeer)
        // (10028: yellow reindeer)
    }

    return text;
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * The main method for running the code @ param args[] the command line list
 * of string arguments, none are needed/*from w  w w.ja v a 2s  .c o m*/
 */
public static void main(String args[]) {

    try {
        // create a new instance of the StorXDispatcher object, and parse
        // the command
        // line arguments as settings for this instance
        final StorXDispatcher storXDispatcher = new StorXDispatcher();

        // Handle ctrl-c's and other abrupt death signals to the process
        Runtime.getRuntime().addShutdownHook(new Thread() {
            // stop the streaming process
            public void run() {
                Collection sourceCollection = storXDispatcher.sourceMap.values();
                for (Iterator iterator = sourceCollection.iterator(); iterator.hasNext();) {

                    Object sourceObject = iterator.next();

                    try {

                        // disconnect StorX sources
                        StorXSource source = (StorXSource) sourceObject;
                        logger.info("Disconnecting source: " + source.getRBNBClientName());
                        source.stopConnection();

                    } catch (java.lang.ClassCastException cce) {

                        // disconnect ISUS sources
                        try {
                            ISUSSource source = (ISUSSource) sourceObject;
                            logger.info("Disconnecting source: " + source.getRBNBClientName());
                            source.stopConnection();

                        } catch (java.lang.ClassCastException cce2) {

                            // disconnect CTD sources
                            CTDSource source = (CTDSource) sourceObject;
                            logger.info("Disconnecting source: " + source.getRBNBClientName());
                            source.stopConnection();

                        } // end try/catch

                    } // end try/catch

                } // end for()

            } // end run()

        } // end new Thread()

        ); // end addShutDownHook()

        // parse the commandline arguments to configure the connection, then
        // start the streaming connection between the source and the RBNB
        // server.
        if (storXDispatcher.parseArgs(args) && storXDispatcher.parseConfiguration()) {

            // establish the individual source connections with the RBNB
            if (storXDispatcher.connect()) {

                // fetch data on a schedule
                TimerTask fetchData = new TimerTask() {
                    public void run() {
                        logger.debug("TimerTask.run() called.");
                        storXDispatcher.execute();
                    }
                };

                Timer executeTimer = new Timer("Execute Timer");
                // run the fetchData timer task at the default interval
                executeTimer.scheduleAtFixedRate(fetchData, new Date(), storXDispatcher.executeInterval);

            } else {
                logger.info("Could not establish a connection to the DataTurbine. Exiting.");
                System.exit(0);
            }

        }

    } catch (Exception e) {
        logger.info("Error in main(): " + e.getMessage());
        e.printStackTrace();

    }
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.server.control.DispatchServ.java

/** Terminate the given session. Delete the clients involved in the session from the roster
 *  of the updateServ, shut down all remaining JTimers associated with the session, and
 *  tell the controlServ to drop all information regarding the session. Return true if
 *  termination succeeds. Wait the given number of seconds before terminating. This is needed
 *  because if we terminate immediately after a session ends, the clients may not have time
 *  to get the END_PERIOD_UPDATES */
private synchronized boolean terminateSession(int sessionId, int waitTime) {
    try {//from  w  ww  . j a  v a 2  s . c  o  m
        Timer timer = new Timer();
        final int sid = sessionId;
        final TradeEngine tradeServ = activeEngines.get(sid);

        TimerTask task = new TimerTask() {
            public void run() {
                int[] clients = controlServ.getSessionClients(sid);
                jTimer.terminateSession(sid);
                updateServ.deleteClients(clients);
                controlServ.terminateSession(sid);
                monitorServ.terminateSession(sid);
                tradeServ.terminateSession(sid);

                log.info("Session " + sid + " fully terminated, all remaining clients will be deactivated");
            }
        };

        timer.schedule(task, waitTime);

        return true;
    } catch (Exception e) {
        log.error("Failed to terminate session " + sessionId, e);
    }
    return false;
}

From source file:com.irccloud.android.activity.MainActivity.java

private void updateReconnecting() {
    if (conn == null)
        return;//  ww  w  .  j  a  v  a 2  s . co  m

    if (conn.getState() == NetworkConnection.STATE_CONNECTED) {
        getSupportActionBar().setTitle("Loading");
    } else if (conn.getState() == NetworkConnection.STATE_CONNECTING || conn.getReconnectTimestamp() > 0) {
        getSupportActionBar().setDisplayShowCustomEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        progressBar.setProgress(0);
        progressBar.setIndeterminate(true);
        if (progressBar.getVisibility() != View.VISIBLE) {
            if (Build.VERSION.SDK_INT >= 16) {
                progressBar.setAlpha(0);
                progressBar.animate().alpha(1).setDuration(200);
            }
            progressBar.setVisibility(View.VISIBLE);
        }
        if (conn.getState() == NetworkConnection.STATE_DISCONNECTED && conn.getReconnectTimestamp() > 0) {
            int seconds = (int) ((conn.getReconnectTimestamp() - System.currentTimeMillis()) / 1000);
            if (seconds < 1) {
                getSupportActionBar().setTitle("Connecting");
                errorMsg.setVisibility(View.GONE);
            } else if (seconds >= 10) {
                getSupportActionBar().setTitle("Reconnecting in 0:" + seconds);
                if (error != null && error.length() > 0) {
                    errorMsg.setText(error);
                    errorMsg.setVisibility(View.VISIBLE);
                } else {
                    errorMsg.setVisibility(View.GONE);
                    error = null;
                }
            } else {
                getSupportActionBar().setTitle("Reconnecting in 0:0" + seconds);
                errorMsg.setVisibility(View.GONE);
                error = null;
            }
            try {
                if (countdownTimer != null) {
                    if (countdownTimerTask != null)
                        countdownTimerTask.cancel();
                    countdownTimerTask = new TimerTask() {
                        public void run() {
                            if (conn != null) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        updateReconnecting();
                                    }
                                });
                            }
                        }
                    };
                    countdownTimer.schedule(countdownTimerTask, 1000);
                }
            } catch (Exception e) {
            }
        } else {
            getSupportActionBar().setTitle("Connecting");
            error = null;
            errorMsg.setVisibility(View.GONE);
        }
    } else {
        getSupportActionBar().setTitle("Offline");
        progressBar.setIndeterminate(false);
        progressBar.setProgress(0);
        getSupportActionBar().setDisplayShowCustomEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
    }
}

From source file:com.googlecode.fascinator.portal.HouseKeeper.java

/**
 * Callback function for incoming messages sent directly to housekeeping.
 * // w  w  w  .  j a va  2  s. co m
 * @param message The incoming message
 */
@Override
public void onMessage(Message message) {
    openLog();
    try {
        // Make sure thread priority is correct
        if (!Thread.currentThread().getName().equals(thread.getName())) {
            Thread.currentThread().setName(thread.getName());
            Thread.currentThread().setPriority(thread.getPriority());
        }

        String text = ((TextMessage) message).getText();
        JsonSimple msgJson = new JsonSimple(text);
        // log.debug("Message\n{}", msgJson.toString());

        String msgType = msgJson.getString(null, "type");
        if (msgType == null) {
            log.error("No message type set!");
            closeLog();
            return;
        }

        // Stop the system from working until a restart occurs
        if (msgType.equals("blocking-restart")) {
            UserAction ua = new UserAction();
            ua.block = true;
            ua.message = "Changes made to the system require a restart. "
                    + "Please restart the system before normal " + "functionality can resume.";
            storeAction(ua);
        }

        // Request a restart, not required though
        if (msgType.equals("basic-restart")) {
            UserAction ua = new UserAction();
            ua.block = false;
            ua.message = "Changes made to the system require a restart.";
            storeAction(ua);
        }

        // Harvest file update
        if (msgType.equals("harvest-update")) {
            String oid = msgJson.getString(null, "oid");
            if (oid != null) {
                UserAction ua = new UserAction();
                ua.block = false;
                ua.message = ("A harvest file has been updated: '" + oid + "'");
                storeAction(ua);
            } else {
                log.error("Invalid message, no harvest file OID provided!");
            }
        }

        // User notications
        if (msgType.equals("user-notice")) {
            String messageText = msgJson.getString(null, "message");
            if (messageText != null) {
                UserAction ua = new UserAction();
                ua.block = false;
                ua.message = messageText;
                storeAction(ua);
            } else {
                log.error("Invalid notice, no message text provided!");
            }
        }

        // Statistics update from Broker Monitor
        if (msgType.equals("broker-update")) {
            Map<String, JsonSimple> queues = JsonSimple.toJavaMap(msgJson.getObject("stats"));
            for (String q : queues.keySet()) {
                JsonSimple qData = queues.get(q);
                Map<String, String> qStats = new HashMap<String, String>();
                qStats.put("total", qData.getString(null, "total"));
                qStats.put("lost", qData.getString(null, "lost"));
                qStats.put("memory", qData.getString(null, "memory"));
                qStats.put("size", qData.getString(null, "size"));
                // Round to an integer value
                int spd = Float.valueOf(qData.getString("0.0", "speed")).intValue();
                qStats.put("speed", String.valueOf(spd));
                // Change from milliseconds to seconds
                float avg = Float.valueOf(qData.getString("0.0", "average")) / 1000;
                // Round to two digits
                avg = Math.round(avg * 100) / 100;
                qStats.put("average", String.valueOf(avg));
                stats.put(q, qStats);
            }
        }

        // 'Refresh' received, check config and reset timer
        if (msgType.equals("refresh")) {
            log.info("Refreshing House Keeping");
            globalConfig = new JsonSimpleConfig();
            timeout = globalConfig.getInteger(DEFAULT_TIMEOUT, "portal", "houseKeeping", "config", "frequency");
            log.info("Starting callback timer. Timeout = {}s", timeout);
            timer.cancel();
            timer = new Timer("HouseKeeping", true);
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    onTimeout();
                }
            }, 0, timeout * 1000);

            // Show a message for the user
            UserAction ua = new UserAction();
            ua.block = false;
            ua.message = ("House Keeping is restarting. Frequency = " + timeout + "s");
            storeAction(ua);
        }
    } catch (JMSException jmse) {
        log.error("Failed to receive message: {}", jmse.getMessage());
    } catch (IOException ioe) {
        log.error("Failed to parse message: {}", ioe.getMessage());
    }
    closeLog();
}

From source file:com.timemachine.controller.ControllerActivity.java

/**
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 *///from w w  w . j  av a  2 s.c  o m
private void setUpMap() {
    if (!isMapTimedUpdate) {
        // Send the new lat lng and zoom to the server when the view is changed
        GoogleMap.OnCameraChangeListener listener = new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition position) {
                if (socket != null) {
                    socket.emit("mapViewUpdate",
                            Double.toString(position.target.latitude) + " "
                                    + Double.toString(position.target.longitude) + " "
                                    + Float.toString(position.zoom - timeMachineAndGoogleMapZoomOffset));
                    // Limit the max zoom
                    if (position.zoom > maxZoom) {
                        mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                    }
                }
            }
        };
        mMap.setOnCameraChangeListener(listener);
    } else {
        // Setup a timer to update the map location
        Timer updateMapTimer = new Timer();
        updateMapTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mapUpdateHandler.post(new Runnable() {
                    public void run() {
                        if (socket != null && isMapTimedUpdate) {
                            CameraPosition position = mMap.getCameraPosition();
                            double currentLat = Math.round(position.target.latitude * roundTo) / roundTo;
                            double currentLng = Math.round(position.target.longitude * roundTo) / roundTo;
                            float currentZoom = Math.round(position.zoom * (float) roundTo) / (float) roundTo;
                            if (currentLat != lastLat || currentLng != lastLng || currentZoom != lastZoom) {
                                socket.emit("mapViewUpdate", Double.toString(currentLat) + " "
                                        + Double.toString(currentLng) + " "
                                        + Double.toString(currentZoom - timeMachineAndGoogleMapZoomOffset));
                            }
                            // Limit the max zoom
                            if (position.zoom > maxZoom) {
                                mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                            }
                            lastLat = currentLat;
                            lastLng = currentLng;
                            lastZoom = currentZoom;
                        }
                    }
                });
            }
        }, mapUpdateTime, mapUpdateTime);
    }
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setTiltGesturesEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(false);
}

From source file:com.connectsdk.service.AirPlayService.java

/**
 * We send periodically a command to keep connection alive and for avoiding 
 * stopping media session//  w w w.  j av a 2s  .  c o m
 * 
 * Fix for https://github.com/ConnectSDK/Connect-SDK-Cordova-Plugin/issues/5
 */
private void startTimer() {
    stopTimer();
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            Log.d("Timer", "Timer");
            getPlaybackPosition(new PlaybackPositionListener() {

                @Override
                public void onGetPlaybackPositionSuccess(long duration, long position) {
                    if (position >= duration) {
                        stopTimer();
                    }
                }

                @Override
                public void onGetPlaybackPositionFailed(ServiceCommandError error) {
                }
            });
        }
    }, KEEP_ALIVE_PERIOD, KEEP_ALIVE_PERIOD);

    updateTimer = new Timer();
    updateTimer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            getPlaybackInfo(new ResponseListener<Object>() {
                @Override
                public void onSuccess(Object object) {
                    PlayStateStatus playState = PlayStateStatus.Unknown;
                    try {
                        JSONObject response = new PListParser().parse(object.toString());
                        if (response.length() > 0) {
                            boolean readyToPlay = false;
                            if (response.has("readyToPlay")) {
                                readyToPlay = response.getBoolean("readyToPlay");
                            }

                            if (!readyToPlay) {
                                playState = PlayStateStatus.Buffering;
                            } else {
                                if (!response.has("rate")) {
                                    playState = PlayStateStatus.Finished;
                                } else {
                                    int rate = response.getInt("rate");
                                    if (rate == 0) {
                                        playState = PlayStateStatus.Paused;
                                    } else if (rate == 1) {
                                        playState = PlayStateStatus.Playing;
                                    }
                                }
                            }

                            if (mSubscriptions.size() > 0) {
                                for (URLServiceSubscription<?> subscription : mSubscriptions) {
                                    if (subscription.getTarget().equalsIgnoreCase(PLAY_STATE)) {
                                        for (int i = 0; i < subscription.getListeners().size(); i++) {
                                            @SuppressWarnings("unchecked")
                                            ResponseListener<Object> listener = (ResponseListener<Object>) subscription
                                                    .getListeners().get(i);
                                            Util.postSuccess(listener, playState);
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                    }
                }

                @Override
                public void onError(ServiceCommandError error) {
                }
            });
        }
    }, 0, UPDATE_PERIOD);
}