blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
410
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
51
| license_type
stringclasses 2
values | repo_name
stringlengths 5
132
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
80
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 5.85k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 131
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
9.45M
| extension
stringclasses 32
values | content
stringlengths 3
9.45M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
313
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
faa6fea66a302e79d31e51d0fc0377da7254fb07 | 2f05bf264bd87f533803906811ffc89685688dba | /Java_020_wordQuiz/src/com/callor/word/domain/WordVO.java | 6381586826b387f48efe67241f5816ec8f055030 | [] | no_license | dkdud8140/Biz_403_2021_03_Java | 3d6a9cf8cd692b78047606665fd888a8ca6ed80f | a24f241a8d12e13c9d6a8a6be78a6b66e5856c31 | refs/heads/master | 2023-06-23T03:51:46.025661 | 2021-07-26T08:35:43 | 2021-07-26T08:35:43 | 348,207,335 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 722 | java | package com.callor.word.domain;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/*
* model package
* MVC(Model View Controller) 패턴의 프로젝트에서는
* VO 클래스가 저장되는 package 를 보통 model로 작성을 한다
*
* domain package
* DBMS와 연동되는 프로젝트에서 사용하기도 하는 이름
*
* command package
*
*/
// Annotation
// @Override 처럼
// annotation으로 키워드를 지정하므로써 단순히 반복 작성해야하는
// 코드를 자동으로 만들어주는 효과를 낸다
@Getter
@Setter
@ToString
public class WordVO {
//정보의 은닉
private String english ;
private String korea ;
private Integer count ;
}
| [
"[email protected]"
] | |
95c81b5b2b9f2902281d4a89e9e3eff81032fc2f | f890f96b050919c100176dbe5354488139f39446 | /Architect_Day05/butterknife/src/test/java/com/butterknife/ExampleUnitTest.java | 3e57c7fe331849f2e4ab6d27787138d9c14eca34 | [] | no_license | zmMyp/myButterKnife | 40c32bf3cdbce12d49f2ee1af2b23555a98f557c | 58ffa5623489ac16cfbb5e79d644cf9595d1207e | refs/heads/master | 2020-05-16T01:20:53.089087 | 2019-04-22T01:16:23 | 2019-04-22T01:16:23 | 182,600,553 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package com.butterknife;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
a8bde6b3e5dbbb8b4ee2464b43f3470b3d7a5951 | b4f26885e77e581d406f63cee1d04fb7feedc6b1 | /EmpSSM/src/main/java/nsu/edu/cn/zsq/test/MBGTest.java | f9d8e570620782009ed62edae337bd05d91824f0 | [] | no_license | 0Zarathustra0/EmpSSM | bcdb70dc0deb5f1c04574abb8dd2fa462af554aa | 291f3c4462c5a780a4105104249e54a9c249d2e6 | refs/heads/master | 2020-03-12T05:00:46.958710 | 2018-11-05T08:25:02 | 2018-11-05T08:25:02 | 130,442,606 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 994 | java | package nsu.edu.cn.zsq.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
/**
* @author zhangshuqiang <br>
* @version 2018年4月21日 下午3:52:59 <br>
* 生成mybatis映射文件
*/
public class MBGTest {
public static void main(String[] args) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
}
| [
"[email protected]"
] | |
dbfd0ac18fd6e4f8aa256dfe2854a1a3d8221a31 | 210500e6df8862f9b4531e84d25f925a3bf0fd58 | /ll-javaUtils/src/main/java/gov/va/med/lom/javaUtils/xml/HashMapNamedNodeMap.java | 2dc7669108882e94fdf752da8af446061d6b269e | [
"Apache-2.0"
] | permissive | merwinn/AVS | e1db56e48dc9432e1f73f5043e96749b4799f6fd | 51f3316586059210d3d8a0a9d1761fed4b9b1826 | refs/heads/master | 2020-05-21T09:14:58.372161 | 2014-08-18T18:57:06 | 2014-08-18T18:57:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 799 | java | package gov.va.med.lom.javaUtils.xml;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Node;
/*
* A class representing a node in a meta-data tree, which implements
* the org.w3c.dom.NamedNodeMap
*/
class HashMapNamedNodeMap extends NamedNodeMapImpl {
/*
* HashMap of Node items.
*/
HashMap hNodes;
/*
* Constructs a HashMapNamedNodeMap from the given HashMap.
*/
public HashMapNamedNodeMap(HashMap nodes) {
super(new ArrayList(nodes.values()));
this.hNodes = nodes;
}
/*
* Returns the items count.
*/
public int getLength() {
return hNodes.size();
}
/*
* Returns the Node item with the given name.
*/
public Node getNamedItem(String name) {
return (Node) hNodes.get(name);
}
}
| [
"[email protected]"
] | |
e31593f03a385898764fda0f1c0b5e0655159053 | 15ae8d4bd9e1085e0ba7a54beae2f0c126a2dce4 | /src/codingInterviewGuide/part3tree/TraverseTree.java | 9b4bc28b2b5a18f0a0ff83569377022ba5743eae | [] | no_license | qdh0520/Algorithm | aae9cc61cc020ba371afe4e638bdb5bff11150cf | 40f626d95eb877005149631d4ffc228b2829cc89 | refs/heads/master | 2020-07-06T12:23:23.300710 | 2019-09-19T14:50:29 | 2019-09-19T14:50:29 | 203,016,025 | 1 | 0 | null | 2019-08-18T14:32:46 | 2019-08-18T14:32:45 | null | UTF-8 | Java | false | false | 1,875 | java | package codingInterviewGuide.part3tree;
import java.util.Stack;
/**
* 非递归实现遍历二叉树
* Created by Dell on 2017-09-03.
*/
public class TraverseTree {
public void preOrder(TreeNode root){
Stack<TreeNode> stack=new Stack<TreeNode>();
TreeNode cur=null;
stack.add(root);
while(!stack.isEmpty()){
cur=stack.pop();
System.out.print(cur.val+" ");
if(cur.right!=null){stack.add(cur.right);}
if(cur.left!=null){stack.add(cur.left);}
}
}
public void in(TreeNode root){
if(root==null){
return;
}
in(root.left);
System.out.println(root.val+" ");
in(root.right);
}
public void inOrder(TreeNode root){
if(root==null){
return;
}
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.add(root);
TreeNode cur=root.left;//cur指向栈顶的左孩子
while(cur!=null||!stack.isEmpty()){//压栈的顺序是左,右,根,
if(cur==null){
cur=stack.pop();
System.out.print(cur.val+" ");
cur=cur.right;
}else{
stack.add(cur);
cur=cur.left;
}
}
}
public void postOrder(TreeNode root){
if(root==null){
return;
}
Stack<TreeNode> stack=new Stack<TreeNode>();
stack.add(root);
TreeNode cur=root.left;//cur指向栈顶的左孩子
while(cur!=null||!stack.isEmpty()){//压栈的顺序是左,右,根,
if(cur==null){
cur=stack.pop();
System.out.print(cur.val+" ");
cur=cur.right;
}else{
stack.add(cur);
}
}
}
}
| [
"[email protected]"
] | |
4a7a911f148a95e2978f4b8b9a16727092751b73 | 0249151b2a494938a008f6cd1e842bca6799139b | /app/src/androidTest/java/com/example/instagram_clone/ExampleInstrumentedTest.java | 44bb66634b5722df93a853d01624e0d21673bf04 | [
"Apache-2.0"
] | permissive | mtkhawaja/Instagram_Clone | 50e5b146274e98301d8421780eee7a96ec8adc1e | 0ea2064157d155806a442a01cfe9601185c50f12 | refs/heads/master | 2021-06-25T09:57:12.346326 | 2021-01-20T03:51:29 | 2021-01-20T03:51:29 | 177,512,137 | 0 | 0 | null | 2021-01-20T03:51:30 | 2019-03-25T04:06:53 | Java | UTF-8 | Java | false | false | 738 | java | package com.example.instagram_clone;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.instagram_clone", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
c72aeaab7ac107272094d5e60fe4bb7571345aa0 | 4aa3d51c7c6d6c6d8707f90d7e3138177a2708fe | /ViewShed/src/java/database/DatabaseErrorLogManager.java | 34d01d51d80bffa2fd1ca09fac3ebef81c1d96a6 | [] | no_license | Neocyte/Viewshed-Viewer | eff2c838d26ca52281b3aacdb2fcaae21353e2bb | c098606ec9fa361029670e24d64a7da1c0a69b31 | refs/heads/master | 2023-05-30T20:49:31.152318 | 2021-06-09T17:16:41 | 2021-06-09T17:16:41 | 375,404,811 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 430 | java |
package database;
import common.ErrorLog;
import java.util.Collection;
/**
*
* @author Curt Jones
*/
public interface DatabaseErrorLogManager {
public Collection<ErrorLog> getAllErrorLogs();
public String getAllErrorLogsAsHTMLTable();
public void addErrorLog(ErrorLog errorLog);
public ErrorLog getErrorLogByID(int id);
public void deleteErrorLog(int id);
public void deleteAllErrorLogs();
}
| [
"[email protected]"
] | |
8b0b81d8ce1030530a9e93af54a0a8a73caded5c | 152e7337c93e371678af214f91e08e0d7685e2e9 | /Backend/src/main/java/com/example/Holidaymaker/repositories/ReviewRepo.java | 086592a47eeb8cdafa5ca181dfbc480a4390f336 | [] | no_license | xerox134/Holiday-maker | 5df87ec15b09bae03b9d05f3dae6bbb97110fe77 | befac749098415e1cc14a3215f4beaca923bad38 | refs/heads/main | 2023-05-31T02:50:10.721075 | 2021-06-14T09:34:40 | 2021-06-14T09:34:40 | 363,855,287 | 2 | 2 | null | 2021-06-04T14:24:16 | 2021-05-03T07:50:15 | JavaScript | UTF-8 | Java | false | false | 459 | java | package com.example.Holidaymaker.repositories;
import com.example.Holidaymaker.entities.Review;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface ReviewRepo extends JpaRepository<Review, Long> {
List<Review> findByUserId(long userId);
List<Review> findByHotelId(long hotelId);
}
| [
"[email protected]"
] | |
fd10121fd99da5a9b4ead7ad5726c840fba92db7 | 8ec9e03f427cf06b186e1f9e724762539f8a9156 | /LemmeTravel/app/src/main/java/com/lemmetravel/seniorproject/fragments/myArticleFragment.java | 80c6dad53a42511ed90aefaf143c5d8f424c847f | [] | no_license | thanapa049/Lemme-Travel | 2c3e363b7d39ab95d89e2f7eec4551dc13e61182 | fe687fcc83ea08b4439ee5af7503a0adb4230fcf | refs/heads/master | 2021-01-18T07:48:39.274070 | 2017-10-19T14:22:29 | 2017-10-19T14:22:29 | 100,352,757 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 783 | java | package com.lemmetravel.seniorproject.fragments;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.lemmetravel.seniorproject.R;
public class myArticleFragment extends Fragment {
public myArticleFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootview = inflater.inflate(R.layout.fragment_my_article, container, false);
return rootview;
}
}
| [
"[email protected]"
] | |
60a000a7e9b75b8fb2421dcadf9957959099d748 | a7ea1958846646794d1c2b8f124a775f8bff3382 | /BACK END/src/main/java/com/ecommerce/shoes/entity/User.java | 53df9a74ea28dd88fca4ac444053e02ba4b59cd8 | [] | no_license | devphan/E-Commerce-Shoes | 554fcf5b9e4a6a6e31bf01abb8ad3aadb27d1c4a | 9ee265ab0f6f4b599fc7f30a71e1dbd1be24e27e | refs/heads/main | 2023-04-05T21:22:18.412869 | 2021-04-28T08:17:36 | 2021-04-28T08:17:36 | 359,373,345 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 737 | java | package com.ecommerce.shoes.entity;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "User")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@NotNull
@Column(unique = true)
private String email;
@Column(name = "full_name")
private String name;
@Column(length = 10)
private String phone;
@Column
private String password;
@Column(name = "role", nullable = false, columnDefinition = "varchar(255) default 'USER'")
private String role;
}
| [
"[email protected]"
] | |
5ea11ae37008230f7f3eed7e123f255fd25e82fb | 1e147f7417a43d08defd98eb8820db3c263dc337 | /src/com/lewa/player/MediaPlaybackActivity.java | e57defa2c4e173245cf2ff9af9041c68765a24a0 | [] | no_license | chongbo2013/My-MusicPlayer | bd512b15ef2f0a60eb0645352cc1885b4596f97a | 3ba0356418c3d27da5f0e80e3853593c8e4ad6fe | refs/heads/master | 2021-05-29T20:23:49.054045 | 2015-08-25T06:14:23 | 2015-08-25T06:14:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 51,589 | java | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lewa.player;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.app.SearchManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.audiofx.AudioEffect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.Layout;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.lewa.player.MusicUtils.ServiceToken;
public class MediaPlaybackActivity extends Activity implements MusicUtils.Defs,
View.OnTouchListener, View.OnLongClickListener
{
private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
private boolean mSeeking = false;
private boolean mDeviceHasDpad;
private long mStartSeekPos = 0;
private long mLastSeekEventTime;
private IMediaPlaybackService mService = null;
private RepeatingImageButton mPrevButton;
private ImageButton mPauseButton;
private RepeatingImageButton mNextButton;
private ImageButton mRepeatButton;
private ImageButton mShuffleButton;
private ImageButton mQueueButton;
private Worker mAlbumArtWorker;
private AlbumArtHandler mAlbumArtHandler;
private Toast mToast;
private int mTouchSlop;
private ServiceToken mToken;
public MediaPlaybackActivity()
{
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mAlbumArtWorker = new Worker("album art worker");
mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.audio_player);
mCurrentTime = (TextView) findViewById(R.id.currenttime);
mTotalTime = (TextView) findViewById(R.id.totaltime);
mProgress = (ProgressBar) findViewById(android.R.id.progress);
mAlbum = (ImageView) findViewById(R.id.album);
mArtistName = (TextView) findViewById(R.id.artistname);
mAlbumName = (TextView) findViewById(R.id.albumname);
mTrackName = (TextView) findViewById(R.id.trackname);
View v = (View)mArtistName.getParent();
v.setOnTouchListener(this);
v.setOnLongClickListener(this);
v = (View)mAlbumName.getParent();
v.setOnTouchListener(this);
v.setOnLongClickListener(this);
v = (View)mTrackName.getParent();
v.setOnTouchListener(this);
v.setOnLongClickListener(this);
mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setRepeatListener(mRewListener, 260);
mPauseButton = (ImageButton) findViewById(R.id.pause);
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
mNextButton = (RepeatingImageButton) findViewById(R.id.next);
mNextButton.setOnClickListener(mNextListener);
mNextButton.setRepeatListener(mFfwdListener, 260);
seekmethod = 1;
mDeviceHasDpad = (getResources().getConfiguration().navigation ==
Configuration.NAVIGATION_DPAD);
mQueueButton = (ImageButton) findViewById(R.id.curplaylist);
mQueueButton.setOnClickListener(mQueueListener);
mShuffleButton = ((ImageButton) findViewById(R.id.shuffle));
mShuffleButton.setOnClickListener(mShuffleListener);
mRepeatButton = ((ImageButton) findViewById(R.id.repeat));
mRepeatButton.setOnClickListener(mRepeatListener);
if (mProgress instanceof SeekBar) {
SeekBar seeker = (SeekBar) mProgress;
seeker.setOnSeekBarChangeListener(mSeekListener);
}
mProgress.setMax(1000);
mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
}
int mInitialX = -1;
int mLastX = -1;
int mTextWidth = 0;
int mViewWidth = 0;
boolean mDraggingLabel = false;
TextView textViewForContainer(View v) {
View vv = v.findViewById(R.id.artistname);
if (vv != null) return (TextView) vv;
vv = v.findViewById(R.id.albumname);
if (vv != null) return (TextView) vv;
vv = v.findViewById(R.id.trackname);
if (vv != null) return (TextView) vv;
return null;
}
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
TextView tv = textViewForContainer(v);
if (tv == null) {
return false;
}
if (action == MotionEvent.ACTION_DOWN) {
v.setBackgroundColor(0xff606060);
mInitialX = mLastX = (int) event.getX();
mDraggingLabel = false;
} else if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_CANCEL) {
v.setBackgroundColor(0);
if (mDraggingLabel) {
Message msg = mLabelScroller.obtainMessage(0, tv);
mLabelScroller.sendMessageDelayed(msg, 1000);
}
} else if (action == MotionEvent.ACTION_MOVE) {
if (mDraggingLabel) {
int scrollx = tv.getScrollX();
int x = (int) event.getX();
int delta = mLastX - x;
if (delta != 0) {
mLastX = x;
scrollx += delta;
if (scrollx > mTextWidth) {
// scrolled the text completely off the view to the left
scrollx -= mTextWidth;
scrollx -= mViewWidth;
}
if (scrollx < -mViewWidth) {
// scrolled the text completely off the view to the right
scrollx += mViewWidth;
scrollx += mTextWidth;
}
tv.scrollTo(scrollx, 0);
}
return true;
}
int delta = mInitialX - (int) event.getX();
if (Math.abs(delta) > mTouchSlop) {
// start moving
mLabelScroller.removeMessages(0, tv);
// Only turn ellipsizing off when it's not already off, because it
// causes the scroll position to be reset to 0.
if (tv.getEllipsize() != null) {
tv.setEllipsize(null);
}
Layout ll = tv.getLayout();
// layout might be null if the text just changed, or ellipsizing
// was just turned off
if (ll == null) {
return false;
}
// get the non-ellipsized line width, to determine whether scrolling
// should even be allowed
mTextWidth = (int) tv.getLayout().getLineWidth(0);
mViewWidth = tv.getWidth();
if (mViewWidth > mTextWidth) {
tv.setEllipsize(TruncateAt.END);
v.cancelLongPress();
return false;
}
mDraggingLabel = true;
tv.setHorizontalFadingEdgeEnabled(true);
v.cancelLongPress();
return true;
}
}
return false;
}
Handler mLabelScroller = new Handler() {
@Override
public void handleMessage(Message msg) {
TextView tv = (TextView) msg.obj;
int x = tv.getScrollX();
x = x * 3 / 4;
tv.scrollTo(x, 0);
if (x == 0) {
tv.setEllipsize(TruncateAt.END);
} else {
Message newmsg = obtainMessage(0, tv);
mLabelScroller.sendMessageDelayed(newmsg, 15);
}
}
};
public boolean onLongClick(View view) {
CharSequence title = null;
String mime = null;
String query = null;
String artist;
String album;
String song;
long audioid;
try {
artist = mService.getArtistName();
album = mService.getAlbumName();
song = mService.getTrackName();
audioid = mService.getAudioId();
} catch (RemoteException ex) {
return true;
} catch (NullPointerException ex) {
// we might not actually have the service yet
return true;
}
if (MediaStore.UNKNOWN_STRING.equals(album) &&
MediaStore.UNKNOWN_STRING.equals(artist) &&
song != null &&
song.startsWith("recording")) {
// not music
return false;
}
if (audioid < 0) {
return false;
}
Cursor c = MusicUtils.query(this,
ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid),
new String[] {MediaStore.Audio.Media.IS_MUSIC}, null, null, null);
boolean ismusic = true;
if (c != null) {
if (c.moveToFirst()) {
ismusic = c.getInt(0) != 0;
}
c.close();
}
if (!ismusic) {
return false;
}
boolean knownartist =
(artist != null) && !MediaStore.UNKNOWN_STRING.equals(artist);
boolean knownalbum =
(album != null) && !MediaStore.UNKNOWN_STRING.equals(album);
if (knownartist && view.equals(mArtistName.getParent())) {
title = artist;
query = artist;
mime = MediaStore.Audio.Artists.ENTRY_CONTENT_TYPE;
} else if (knownalbum && view.equals(mAlbumName.getParent())) {
title = album;
if (knownartist) {
query = artist + " " + album;
} else {
query = album;
}
mime = MediaStore.Audio.Albums.ENTRY_CONTENT_TYPE;
} else if (view.equals(mTrackName.getParent()) || !knownartist || !knownalbum) {
if ((song == null) || MediaStore.UNKNOWN_STRING.equals(song)) {
// A popup of the form "Search for null/'' using ..." is pretty
// unhelpful, plus, we won't find any way to buy it anyway.
return true;
}
title = song;
if (knownartist) {
query = artist + " " + song;
} else {
query = song;
}
mime = "audio/*"; // the specific type doesn't matter, so don't bother retrieving it
} else {
throw new RuntimeException("shouldn't be here");
}
title = getString(R.string.mediasearch, title);
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.putExtra(SearchManager.QUERY, query);
if(knownartist) {
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
}
if(knownalbum) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
}
i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
startActivity(Intent.createChooser(i, title));
return true;
}
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
public void onStartTrackingTouch(SeekBar bar) {
mLastSeekEventTime = 0;
mFromTouch = true;
}
public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
if (!fromuser || (mService == null)) return;
long now = SystemClock.elapsedRealtime();
if ((now - mLastSeekEventTime) > 250) {
mLastSeekEventTime = now;
mPosOverride = mDuration * progress / 1000;
try {
mService.seek(mPosOverride);
} catch (RemoteException ex) {
}
// trackball event, allow progress updates
if (!mFromTouch) {
refreshNow();
mPosOverride = -1;
}
}
}
public void onStopTrackingTouch(SeekBar bar) {
mPosOverride = -1;
mFromTouch = false;
}
};
private View.OnClickListener mQueueListener = new View.OnClickListener() {
public void onClick(View v) {
startActivity(
new Intent(Intent.ACTION_EDIT)
.setDataAndType(Uri.EMPTY, "vnd.android.cursor.dir/track")
.putExtra("playlist", "nowplaying")
);
}
};
private View.OnClickListener mShuffleListener = new View.OnClickListener() {
public void onClick(View v) {
toggleShuffle();
}
};
private View.OnClickListener mRepeatListener = new View.OnClickListener() {
public void onClick(View v) {
cycleRepeat();
}
};
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
}
};
private View.OnClickListener mPrevListener = new View.OnClickListener() {
public void onClick(View v) {
if (mService == null) return;
try {
if (mService.position() < 2000) {
mService.prev();
} else {
mService.seek(0);
mService.play();
}
} catch (RemoteException ex) {
}
}
};
private View.OnClickListener mNextListener = new View.OnClickListener() {
public void onClick(View v) {
if (mService == null) return;
try {
mService.next();
} catch (RemoteException ex) {
}
}
};
private RepeatingImageButton.RepeatListener mRewListener =
new RepeatingImageButton.RepeatListener() {
public void onRepeat(View v, long howlong, int repcnt) {
scanBackward(repcnt, howlong);
}
};
private RepeatingImageButton.RepeatListener mFfwdListener =
new RepeatingImageButton.RepeatListener() {
public void onRepeat(View v, long howlong, int repcnt) {
scanForward(repcnt, howlong);
}
};
@Override
public void onStop() {
paused = true;
mHandler.removeMessages(REFRESH);
unregisterReceiver(mStatusListener);
MusicUtils.unbindFromService(mToken);
mService = null;
super.onStop();
}
@Override
public void onStart() {
super.onStart();
paused = false;
mToken = MusicUtils.bindToService(this, osc);
if (mToken == null) {
// something went wrong
mHandler.sendEmptyMessage(QUIT);
}
IntentFilter f = new IntentFilter();
f.addAction(MediaPlaybackService.PLAYSTATE_CHANGED);
f.addAction(MediaPlaybackService.META_CHANGED);
registerReceiver(mStatusListener, new IntentFilter(f));
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
}
@Override
public void onNewIntent(Intent intent) {
setIntent(intent);
}
@Override
public void onResume() {
super.onResume();
updateTrackInfo();
setPauseButtonImage();
}
@Override
public void onDestroy()
{
mAlbumArtWorker.quit();
super.onDestroy();
//System.out.println("***************** playback activity onDestroy\n");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Don't show the menu items if we got launched by path/filedescriptor, or
// if we're in one shot mode. In most cases, these menu items are not
// useful in those modes, so for consistency we never show them in these
// modes, instead of tailoring them to the specific file being played.
if (MusicUtils.getCurrentAudioId() >= 0) {
menu.add(0, GOTO_START, 0, R.string.goto_start).setIcon(R.drawable.ic_menu_music_library);
menu.add(0, PARTY_SHUFFLE, 0, R.string.party_shuffle); // icon will be set in onPrepareOptionsMenu()
SubMenu sub = menu.addSubMenu(0, ADD_TO_PLAYLIST, 0,
R.string.add_to_playlist).setIcon(android.R.drawable.ic_menu_add);
// these next two are in a separate group, so they can be shown/hidden as needed
// based on the keyguard state
menu.add(1, USE_AS_RINGTONE, 0, R.string.ringtone_menu_short)
.setIcon(R.drawable.ic_menu_set_as_ringtone);
menu.add(1, DELETE_ITEM, 0, R.string.delete_item)
.setIcon(R.drawable.ic_menu_delete);
Intent i = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
if (getPackageManager().resolveActivity(i, 0) != null) {
menu.add(0, EFFECTS_PANEL, 0, R.string.effectspanel).setIcon(R.drawable.ic_menu_eq);
}
return true;
}
return false;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (mService == null) return false;
MenuItem item = menu.findItem(PARTY_SHUFFLE);
if (item != null) {
int shuffle = MusicUtils.getCurrentShuffleMode();
if (shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
item.setIcon(R.drawable.ic_menu_party_shuffle);
item.setTitle(R.string.party_shuffle_off);
} else {
item.setIcon(R.drawable.ic_menu_party_shuffle);
item.setTitle(R.string.party_shuffle);
}
}
item = menu.findItem(ADD_TO_PLAYLIST);
if (item != null) {
SubMenu sub = item.getSubMenu();
// MusicUtils.makePlaylistMenu(this, sub);
}
KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
menu.setGroupVisible(1, !km.inKeyguardRestrictedInputMode());
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
try {
switch (item.getItemId()) {
case GOTO_START:
// intent = new Intent();
// intent.setClass(this, MusicBrowserActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(intent);
// finish();
break;
case USE_AS_RINGTONE: {
// Set the system setting to make this the current ringtone
if (mService != null) {
MusicUtils.setRingtone(this, mService.getAudioId());
}
return true;
}
case PARTY_SHUFFLE:
MusicUtils.togglePartyShuffle();
setShuffleButtonImage();
break;
case NEW_PLAYLIST: {
intent = new Intent();
intent.setClass(this, CreatePlaylist.class);
startActivityForResult(intent, NEW_PLAYLIST);
return true;
}
case PLAYLIST_SELECTED: {
long [] list = new long[1];
list[0] = MusicUtils.getCurrentAudioId();
long playlist = item.getIntent().getLongExtra("playlist", 0);
MusicUtils.addToPlaylist(this, list, playlist);
return true;
}
case DELETE_ITEM: {
if (mService != null) {
long [] list = new long[1];
list[0] = MusicUtils.getCurrentAudioId();
Bundle b = new Bundle();
String f;
if (android.os.Environment.isExternalStorageRemovable()) {
f = getString(R.string.delete_song_desc, mService.getTrackName());
} else {
f = getString(R.string.delete_song_desc_nosdcard, mService.getTrackName());
}
b.putString("description", f);
b.putLongArray("items", list);
intent = new Intent();
intent.setClass(this, DeleteItems.class);
intent.putExtras(b);
startActivityForResult(intent, -1);
}
return true;
}
case EFFECTS_PANEL: {
Intent i = new Intent(AudioEffect.ACTION_DISPLAY_AUDIO_EFFECT_CONTROL_PANEL);
i.putExtra(AudioEffect.EXTRA_AUDIO_SESSION, mService.getAudioSessionId());
startActivityForResult(i, EFFECTS_PANEL);
return true;
}
}
} catch (RemoteException ex) {
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case NEW_PLAYLIST:
Uri uri = intent.getData();
if (uri != null) {
long [] list = new long[1];
list[0] = MusicUtils.getCurrentAudioId();
int playlist = Integer.parseInt(uri.getLastPathSegment());
MusicUtils.addToPlaylist(this, list, playlist);
}
break;
}
}
private final int keyboard[][] = {
{
KeyEvent.KEYCODE_Q,
KeyEvent.KEYCODE_W,
KeyEvent.KEYCODE_E,
KeyEvent.KEYCODE_R,
KeyEvent.KEYCODE_T,
KeyEvent.KEYCODE_Y,
KeyEvent.KEYCODE_U,
KeyEvent.KEYCODE_I,
KeyEvent.KEYCODE_O,
KeyEvent.KEYCODE_P,
},
{
KeyEvent.KEYCODE_A,
KeyEvent.KEYCODE_S,
KeyEvent.KEYCODE_D,
KeyEvent.KEYCODE_F,
KeyEvent.KEYCODE_G,
KeyEvent.KEYCODE_H,
KeyEvent.KEYCODE_J,
KeyEvent.KEYCODE_K,
KeyEvent.KEYCODE_L,
KeyEvent.KEYCODE_DEL,
},
{
KeyEvent.KEYCODE_Z,
KeyEvent.KEYCODE_X,
KeyEvent.KEYCODE_C,
KeyEvent.KEYCODE_V,
KeyEvent.KEYCODE_B,
KeyEvent.KEYCODE_N,
KeyEvent.KEYCODE_M,
KeyEvent.KEYCODE_COMMA,
KeyEvent.KEYCODE_PERIOD,
KeyEvent.KEYCODE_ENTER
}
};
private int lastX;
private int lastY;
private boolean seekMethod1(int keyCode)
{
if (mService == null) return false;
for(int x=0;x<10;x++) {
for(int y=0;y<3;y++) {
if(keyboard[y][x] == keyCode) {
int dir = 0;
// top row
if(x == lastX && y == lastY) dir = 0;
else if (y == 0 && lastY == 0 && x > lastX) dir = 1;
else if (y == 0 && lastY == 0 && x < lastX) dir = -1;
// bottom row
else if (y == 2 && lastY == 2 && x > lastX) dir = -1;
else if (y == 2 && lastY == 2 && x < lastX) dir = 1;
// moving up
else if (y < lastY && x <= 4) dir = 1;
else if (y < lastY && x >= 5) dir = -1;
// moving down
else if (y > lastY && x <= 4) dir = -1;
else if (y > lastY && x >= 5) dir = 1;
lastX = x;
lastY = y;
try {
mService.seek(mService.position() + dir * 5);
} catch (RemoteException ex) {
}
refreshNow();
return true;
}
}
}
lastX = -1;
lastY = -1;
return false;
}
private boolean seekMethod2(int keyCode)
{
if (mService == null) return false;
for(int i=0;i<10;i++) {
if(keyboard[0][i] == keyCode) {
int seekpercentage = 100*i/10;
try {
mService.seek(mService.duration() * seekpercentage / 100);
} catch (RemoteException ex) {
}
refreshNow();
return true;
}
}
return false;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
try {
switch(keyCode)
{
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
if (mStartSeekPos < 1000) {
mService.prev();
} else {
mService.seek(0);
}
} else {
scanBackward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
mService.next();
} else {
scanForward(-1, event.getEventTime() - event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
}
} catch (RemoteException ex) {
}
return super.onKeyUp(keyCode, event);
}
private boolean useDpadMusicControl() {
if (mDeviceHasDpad && (mPrevButton.isFocused() ||
mNextButton.isFocused() ||
mPauseButton.isFocused())) {
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
int direction = -1;
int repcnt = event.getRepeatCount();
if((seekmethod==0)?seekMethod1(keyCode):seekMethod2(keyCode))
return true;
switch(keyCode)
{
/*
// image scale
case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0, 0.0, 0.0, 0.0,-1.0); break;
case KeyEvent.KEYCODE_E: av.adjustParams( 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break;
// image translate
case KeyEvent.KEYCODE_W: av.adjustParams( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0); break;
case KeyEvent.KEYCODE_X: av.adjustParams( 0.0, 0.0, 1.0, 0.0, 0.0, 0.0); break;
case KeyEvent.KEYCODE_A: av.adjustParams( 0.0,-1.0, 0.0, 0.0, 0.0, 0.0); break;
case KeyEvent.KEYCODE_D: av.adjustParams( 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break;
// camera rotation
case KeyEvent.KEYCODE_R: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0,-1.0); break;
case KeyEvent.KEYCODE_U: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); break;
// camera translate
case KeyEvent.KEYCODE_Y: av.adjustParams( 0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break;
case KeyEvent.KEYCODE_N: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0); break;
case KeyEvent.KEYCODE_G: av.adjustParams( 0.0, 0.0, 0.0,-1.0, 0.0, 0.0); break;
case KeyEvent.KEYCODE_J: av.adjustParams( 0.0, 0.0, 0.0, 1.0, 0.0, 0.0); break;
*/
case KeyEvent.KEYCODE_SLASH:
seekmethod = 1 - seekmethod;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (!mPrevButton.hasFocus()) {
mPrevButton.requestFocus();
}
scanBackward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (!mNextButton.hasFocus()) {
mNextButton.requestFocus();
}
scanForward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_S:
toggleShuffle();
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_SPACE:
doPauseResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void scanBackward(int repcnt, long delta) {
if(mService == null) return;
try {
if(repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos - delta;
if (newpos < 0) {
// move to previous track
mService.prev();
long duration = mService.duration();
mStartSeekPos += duration;
newpos += duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void scanForward(int repcnt, long delta) {
if(mService == null) return;
try {
if(repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos + delta;
long duration = mService.duration();
if (newpos >= duration) {
// move to next track
mService.next();
mStartSeekPos -= duration; // is OK to go negative
newpos -= duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0){
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void doPauseResume() {
try {
if(mService != null) {
if (mService.isPlaying()) {
mService.pause();
} else {
mService.play();
}
refreshNow();
setPauseButtonImage();
}
} catch (RemoteException ex) {
}
}
private void toggleShuffle() {
if (mService == null) {
return;
}
try {
int shuffle = mService.getShuffleMode();
if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
if (mService.getRepeatMode() == MediaPlaybackService.REPEAT_CURRENT) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
setRepeatButtonImage();
}
showToast(R.string.shuffle_on_notif);
} else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL ||
shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
showToast(R.string.shuffle_off_notif);
} else {
Log.e("MediaPlaybackActivity", "Invalid shuffle mode: " + shuffle);
}
setShuffleButtonImage();
} catch (RemoteException ex) {
}
}
private void cycleRepeat() {
if (mService == null) {
return;
}
try {
int mode = mService.getRepeatMode();
if (mode == MediaPlaybackService.REPEAT_NONE) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
showToast(R.string.repeat_all_notif);
} else if (mode == MediaPlaybackService.REPEAT_ALL) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
setShuffleButtonImage();
}
showToast(R.string.repeat_current_notif);
} else {
mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
showToast(R.string.repeat_off_notif);
}
setRepeatButtonImage();
} catch (RemoteException ex) {
}
}
private void showToast(int resid) {
if (mToast == null) {
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
mToast.setText(resid);
mToast.show();
}
private void startPlayback() {
if(mService == null)
return;
Intent intent = getIntent();
String filename = "";
Uri uri = intent.getData();
if (uri != null && uri.toString().length() > 0) {
// If this is a file:// URI, just use the path directly instead
// of going through the open-from-filedescriptor codepath.
String scheme = uri.getScheme();
if ("file".equals(scheme)) {
filename = uri.getPath();
} else {
filename = uri.toString();
}
try {
mService.stop();
mService.openFile(filename);
mService.play();
setIntent(new Intent());
} catch (Exception ex) {
Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
}
}
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
}
private ServiceConnection osc = new ServiceConnection() {
public void onServiceConnected(ComponentName classname, IBinder obj) {
mService = IMediaPlaybackService.Stub.asInterface(obj);
startPlayback();
try {
// Assume something is playing when the service says it is,
// but also if the audio ID is valid but the service is paused.
if (mService.getAudioId() >= 0 || mService.isPlaying() ||
mService.getPath() != null) {
// something is playing now, we're done
mRepeatButton.setVisibility(View.VISIBLE);
mShuffleButton.setVisibility(View.VISIBLE);
mQueueButton.setVisibility(View.VISIBLE);
setRepeatButtonImage();
setShuffleButtonImage();
setPauseButtonImage();
return;
}
} catch (RemoteException ex) {
}
// Service is dead or not playing anything. If we got here as part
// of a "play this file" Intent, exit. Otherwise go to the Music
// app start screen.
if (getIntent().getData() == null) {
// Intent intent = new Intent(Intent.ACTION_MAIN);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setClass(MediaPlaybackActivity.this, MusicBrowserActivity.class);
// startActivity(intent);
}
finish();
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private void setRepeatButtonImage() {
if (mService == null) return;
try {
switch (mService.getRepeatMode()) {
case MediaPlaybackService.REPEAT_ALL:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_all_btn);
break;
case MediaPlaybackService.REPEAT_CURRENT:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_once_btn);
break;
default:
mRepeatButton.setImageResource(R.drawable.ic_mp_repeat_off_btn);
break;
}
} catch (RemoteException ex) {
}
}
private void setShuffleButtonImage() {
if (mService == null) return;
try {
switch (mService.getShuffleMode()) {
case MediaPlaybackService.SHUFFLE_NONE:
mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_off_btn);
break;
case MediaPlaybackService.SHUFFLE_AUTO:
mShuffleButton.setImageResource(R.drawable.ic_mp_partyshuffle_on_btn);
break;
default:
mShuffleButton.setImageResource(R.drawable.ic_mp_shuffle_on_btn);
break;
}
} catch (RemoteException ex) {
}
}
private void setPauseButtonImage() {
try {
if (mService != null && mService.isPlaying()) {
mPauseButton.setImageResource(android.R.drawable.ic_media_pause);
} else {
mPauseButton.setImageResource(android.R.drawable.ic_media_play);
}
} catch (RemoteException ex) {
}
}
private ImageView mAlbum;
private TextView mCurrentTime;
private TextView mTotalTime;
private TextView mArtistName;
private TextView mAlbumName;
private TextView mTrackName;
private ProgressBar mProgress;
private long mPosOverride = -1;
private boolean mFromTouch = false;
private long mDuration;
private int seekmethod;
private boolean paused;
private static final int REFRESH = 1;
private static final int QUIT = 2;
private static final int GET_ALBUM_ART = 3;
private static final int ALBUM_ART_DECODED = 4;
private void queueNextRefresh(long delay) {
if (!paused) {
Message msg = mHandler.obtainMessage(REFRESH);
mHandler.removeMessages(REFRESH);
mHandler.sendMessageDelayed(msg, delay);
}
}
private long refreshNow() {
if(mService == null)
return 500;
try {
long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
if ((pos >= 0) && (mDuration > 0)) {
mCurrentTime.setText(MusicUtils.makeTimeString(this, pos / 1000));
int progress = (int) (1000 * pos / mDuration);
mProgress.setProgress(progress);
if (mService.isPlaying()) {
mCurrentTime.setVisibility(View.VISIBLE);
} else {
// blink the counter
int vis = mCurrentTime.getVisibility();
mCurrentTime.setVisibility(vis == View.INVISIBLE ? View.VISIBLE : View.INVISIBLE);
return 500;
}
} else {
mCurrentTime.setText("--:--");
mProgress.setProgress(1000);
}
// calculate the number of milliseconds until the next full second, so
// the counter can be updated at just the right time
long remaining = 1000 - (pos % 1000);
// approximate how often we would need to refresh the slider to
// move it smoothly
int width = mProgress.getWidth();
if (width == 0) width = 320;
long smoothrefreshtime = mDuration / width;
if (smoothrefreshtime > remaining) return remaining;
if (smoothrefreshtime < 20) return 20;
return smoothrefreshtime;
} catch (RemoteException ex) {
}
return 500;
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ALBUM_ART_DECODED:
mAlbum.setImageBitmap((Bitmap)msg.obj);
mAlbum.getDrawable().setDither(true);
break;
case REFRESH:
long next = refreshNow();
queueNextRefresh(next);
break;
case QUIT:
// This can be moved back to onCreate once the bug that prevents
// Dialogs from being started from onCreate/onResume is fixed.
new AlertDialog.Builder(MediaPlaybackActivity.this)
.setTitle(R.string.service_start_error_title)
.setMessage(R.string.service_start_error_msg)
.setPositiveButton(R.string.service_start_error_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
})
.setCancelable(false)
.show();
break;
default:
break;
}
}
};
private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MediaPlaybackService.META_CHANGED)) {
// redraw the artist/title info and
// set new max for progress bar
updateTrackInfo();
setPauseButtonImage();
queueNextRefresh(1);
} else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
setPauseButtonImage();
}
}
};
private static class AlbumSongIdWrapper {
public long albumid;
public long songid;
AlbumSongIdWrapper(long aid, long sid) {
albumid = aid;
songid = sid;
}
}
private void updateTrackInfo() {
if (mService == null) {
return;
}
try {
String path = mService.getPath();
if (path == null) {
finish();
return;
}
long songid = mService.getAudioId();
if (songid < 0 && path.toLowerCase().startsWith("http://")) {
// Once we can get album art and meta data from MediaPlayer, we
// can show that info again when streaming.
((View) mArtistName.getParent()).setVisibility(View.INVISIBLE);
((View) mAlbumName.getParent()).setVisibility(View.INVISIBLE);
mAlbum.setVisibility(View.GONE);
mTrackName.setText(path);
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(-1, -1)).sendToTarget();
} else {
((View) mArtistName.getParent()).setVisibility(View.VISIBLE);
((View) mAlbumName.getParent()).setVisibility(View.VISIBLE);
String artistName = mService.getArtistName();
if (MediaStore.UNKNOWN_STRING.equals(artistName)) {
artistName = getString(R.string.unknown_artist_name);
}
mArtistName.setText(artistName);
String albumName = mService.getAlbumName();
long albumid = mService.getAlbumId();
if (MediaStore.UNKNOWN_STRING.equals(albumName)) {
albumName = getString(R.string.unknown_album_name);
albumid = -1;
}
mAlbumName.setText(albumName);
mTrackName.setText(mService.getTrackName());
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART, new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
mAlbum.setVisibility(View.VISIBLE);
}
mDuration = mService.duration();
mTotalTime.setText(MusicUtils.makeTimeString(this, mDuration / 1000));
} catch (RemoteException ex) {
finish();
}
}
public class AlbumArtHandler extends Handler {
private long mAlbumId = -1;
public AlbumArtHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg)
{
long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
long songid = ((AlbumSongIdWrapper) msg.obj).songid;
if (msg.what == GET_ALBUM_ART && (mAlbumId != albumid || albumid < 0)) {
// while decoding the new image, show the default album art
Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
mHandler.removeMessages(ALBUM_ART_DECODED);
mHandler.sendMessageDelayed(numsg, 300);
// Don't allow default artwork here, because we want to fall back to song-specific
// album art if we can't find anything for the album.
Bitmap bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, albumid, false);
if (bm == null) {
bm = MusicUtils.getArtwork(MediaPlaybackActivity.this, songid, -1);
albumid = -1;
}
if (bm != null) {
numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
mHandler.removeMessages(ALBUM_ART_DECODED);
mHandler.sendMessage(numsg);
}
mAlbumId = albumid;
}
}
}
private static class Worker implements Runnable {
private final Object mLock = new Object();
private Looper mLooper;
/**
* Creates a worker thread with the given name. The thread
* then runs a {@link android.os.Looper}.
* @param name A name for the new thread
*/
Worker(String name) {
Thread t = new Thread(null, this, name);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
synchronized (mLock) {
while (mLooper == null) {
try {
mLock.wait();
} catch (InterruptedException ex) {
}
}
}
}
public Looper getLooper() {
return mLooper;
}
public void run() {
synchronized (mLock) {
Looper.prepare();
mLooper = Looper.myLooper();
mLock.notifyAll();
}
Looper.loop();
}
public void quit() {
mLooper.quit();
}
}
}
| [
"[email protected]"
] | |
baa98136023fb127bfee0f3b18342eadf9979f45 | ae70e6caef18ce046d58f79984002c95d789f996 | /app/src/main/java/com/qjf/sample/presenter/MainPresenter.java | de398dc4aba52a3feeb862cc8ab43fb64d8e1d28 | [] | no_license | Tobi1025/MvvpFrame | f5c92de74afe363c9fbba12db130b6b12e093e5b | e3f3f6d5301a664ea25b52c7a1588c9508577940 | refs/heads/master | 2021-08-28T13:33:44.122277 | 2017-12-12T09:55:50 | 2017-12-12T09:55:50 | 113,964,287 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,708 | java | package com.qjf.sample.presenter;
import com.qjf.sample.base.RxPresenter;
import com.qjf.sample.model.http.HttpManager;
import com.qjf.sample.model.http.request.NewsRequestCenter;
import com.qjf.sample.model.http.response.NewsHttpResponse;
import com.qjf.sample.presenter.contract.MainContract;
import com.qjf.sample.utils.RxUtil;
import java.util.List;
import java.util.Map;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
/**
* Created by qiaojingfei on 2017/12/1.
*/
public class MainPresenter extends RxPresenter<MainContract.IMainView> implements MainContract.IMainPresenter {
@Override
public void getDataList() {
Subscription newsSubscription = HttpManager.getNewsRequestCenter().newsList("shehui", NewsRequestCenter.APPKEY)
.compose(RxUtil.<NewsHttpResponse>rxNewsSchedulerHelper())
.compose(RxUtil.<Map<String, Object>>handleNewsResult())
.subscribe(new Action1<Map<String, Object>>() {
@Override
public void call(final Map<String, Object> res) {
if (res != null) {
List<Map<String, String>> data = (List<Map<String, String>>) res.get("data");
mView.showContent(data);
}
}
}, new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
}
}, new Action0() {
@Override
public void call() {
}
});
addSubscribe(newsSubscription);
}
}
| [
"[email protected]"
] | |
0217ee1e7d22675e54fb2e22d544985e3ec9c3d3 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_21f859e222cf78ca8485e0f479bffd38d85838a2/QueryMapper/2_21f859e222cf78ca8485e0f479bffd38d85838a2_QueryMapper_s.java | e0ed6b0fb3671c3fe7b84d400d4f6681cc5d5bd7 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 3,132 | java | /*
* Copyright (c) 2011 by the original author(s).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.document.mongodb.query;
import java.util.ArrayList;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.types.ObjectId;
import org.springframework.core.convert.ConversionFailedException;
import org.springframework.data.document.mongodb.MongoReader;
import org.springframework.data.document.mongodb.convert.MongoConverter;
import org.springframework.data.mapping.model.PersistentEntity;
/**
* A helper class to encapsulate any modifications of a Query object before it gets submitted to the database.
*
* @author Jon Brisbin <[email protected]>
*/
public class QueryMapper<T> {
final private DBObject query;
final private PersistentEntity<T> entity;
final private MongoReader<Object> reader;
public QueryMapper(DBObject query, PersistentEntity<T> entity, MongoReader<?> reader) {
this.query = query;
this.entity = entity;
this.reader = (MongoReader<Object>) reader;
}
public DBObject getMappedObject() {
String idKey = null;
if (null != entity) {
idKey = entity.getIdProperty().getName();
} else if (query.containsField("id")) {
idKey = "id";
} else if (query.containsField("_id")) {
idKey = "_id";
}
DBObject newDbo = new BasicDBObject();
for (String key : query.keySet()) {
String newKey = key;
Object value = query.get(key);
if (key.equals(idKey)) {
if (value instanceof DBObject) {
DBObject valueDbObj = (DBObject) value;
if ("$in".equals(key)) {
List<Object> ids = new ArrayList<Object>();
for (Object id : (Object[]) ((DBObject) value).get("$in")) {
if (null != reader && !(id instanceof ObjectId)) {
ObjectId oid = ((MongoConverter) reader).convertObjectId(id);
ids.add(oid);
} else {
ids.add(id);
}
}
newDbo.put("$in", ids.toArray(new ObjectId[ids.size()]));
}
if (null != reader) {
try {
value = reader.read(entity.getIdProperty().getType(), valueDbObj);
} catch (ConversionFailedException ignored) {
}
}
} else if (null != reader) {
try {
value = ((MongoConverter) reader).convertObjectId(value);
} catch (ConversionFailedException ignored) {
}
}
newKey = "_id";
} else {
// TODO: Implement other forms of key conversion (like @Alias and whatnot)
}
newDbo.put(newKey, value);
}
return newDbo;
}
}
| [
"[email protected]"
] | |
72f5938d5c87e9281cf42c61a69ae29af34111d4 | 904aad25a260a3668960c040c330e96f2e0087c7 | /API-Gateway/src/main/java/com/org/apigateway/ApiGatewayApplication.java | b745670b8340f1fcfd246465e629f6cf96e5c0b4 | [] | no_license | Mundiaem/Spring-Microservices | 74cd7f475414d0d3fb232307c73595185e1f3d83 | c5199081b95f5eb9cd83cc3dc493a514320aecfd | refs/heads/main | 2023-07-03T13:19:56.762762 | 2021-08-03T13:55:31 | 2021-08-03T13:55:31 | 392,334,041 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,382 | java | package com.org.apigateway;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient
@EnableHystrix
@ComponentScan(basePackages = {"com.org.apigateway.*"})
@EnableCircuitBreaker
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
// @Bean
// public Customizer<HystrixCircuitBreakerFactory> defaultConfig() {
// return factory -> factory.configureDefault(id -> HystrixCommand.Setter
// .withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
// .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
// .withExecutionTimeoutInMilliseconds(4000)));
// }
}
| [
"[email protected]"
] | |
52579574f4ff12f7efc9a7b50400071068e9a4c6 | 36c7d9828c5158370144b61eeb7f56ac8ed50162 | /src/main/java/org/opensha/sra/gui/BCR_Application.java | 8d338b622f9a2f4799073444ab3adcc91eac4385 | [
"Apache-2.0"
] | permissive | Aditya-Zutshi/opensha | 92f1a5112c855fec37afea27150b4588fd14d077 | d0e862a62bb3cdd262c4f33742b3a071da6b21b7 | refs/heads/master | 2023-08-28T05:00:38.792472 | 2021-10-26T08:13:18 | 2021-10-26T08:13:18 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 37,885 | java | /*******************************************************************************
* Copyright 2009 OpenSHA.org in partnership with
* the Southern California Earthquake Center (SCEC, http://www.scec.org)
* at the University of Southern California and the UnitedStates Geological
* Survey (USGS; http://www.usgs.gov)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package org.opensha.sra.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.SystemColor;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.DecimalFormat;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import org.apache.commons.lang3.SystemUtils;
import org.opensha.commons.data.Site;
import org.opensha.commons.data.function.ArbitrarilyDiscretizedFunc;
import org.opensha.commons.data.function.DiscretizedFunc;
import org.opensha.commons.geo.Location;
import org.opensha.commons.geo.LocationList;
import org.opensha.commons.gui.DisclaimerDialog;
import org.opensha.commons.param.event.ParameterChangeEvent;
import org.opensha.commons.param.event.ParameterChangeListener;
import org.opensha.commons.util.ApplicationVersion;
import org.opensha.commons.util.ExceptionUtils;
import org.opensha.commons.util.FileUtils;
import org.opensha.commons.util.ServerPrefUtils;
import org.opensha.commons.util.bugReports.BugReport;
import org.opensha.commons.util.bugReports.BugReportDialog;
import org.opensha.commons.util.bugReports.DefaultExceptoinHandler;
import org.opensha.sha.calc.HazardCurveCalculator;
import org.opensha.sha.calc.HazardCurveCalculatorAPI;
import org.opensha.sha.calc.params.MaxDistanceParam;
import org.opensha.sha.earthquake.BaseERF;
import org.opensha.sha.earthquake.ERF;
import org.opensha.sha.earthquake.ERF_Ref;
import org.opensha.sha.gui.beans.ERF_GuiBean;
import org.opensha.sha.gui.beans.IMR_GuiBean;
import org.opensha.sha.gui.beans.IMR_GuiBeanAPI;
import org.opensha.sha.gui.beans.Site_GuiBean;
import org.opensha.sha.gui.controls.SetMinSourceSiteDistanceControlPanel;
import org.opensha.sha.gui.controls.SetSiteParamsFromWebServicesControlPanel;
import org.opensha.sha.gui.controls.SitesOfInterestControlPanel;
import org.opensha.sha.gui.infoTools.CalcProgressBar;
import org.opensha.sha.gui.infoTools.IMT_Info;
import org.opensha.sha.imr.ScalarIMR;
import org.opensha.sha.imr.param.IntensityMeasureParams.PeriodParam;
import org.opensha.sha.imr.param.IntensityMeasureParams.SA_Param;
import org.opensha.sra.calc.BenefitCostCalculator;
import org.opensha.sra.calc.EALCalculator;
import org.opensha.sra.gui.components.BenefitCostBean;
import org.opensha.sra.gui.components.GuiBeanAPI;
import org.opensha.sra.vulnerability.AbstractVulnerability;
/**
* <p>Title: BCR_Application</p>
* <p>Description: </p>
* @author Nitin Gupta and Vipin Gupta
* Date : Feb , 2006
* @version 1.0
*/
public class BCR_Application extends JFrame
implements Runnable, ParameterChangeListener,
IMR_GuiBeanAPI{
protected static final String APP_NAME = "Benefit Cost Ratio Application";
protected static final String APP_SHORT_NAME = "BCR_Application";
private static final long serialVersionUID = 0x1B8589F;
/**
* Name of the class
*/
private final static String C = "BCR_Application";
// for debug purpose
protected final static boolean D = false;
// instances of the GUI Beans which will be shown in this applet
protected ERF_GuiBean erfGuiBean;
protected IMR_GuiBean imrGuiBean;
protected Site_GuiBean siteGuiBean;
private JLabel openshaImgLabel = new JLabel(new ImageIcon(FileUtils.loadImage("logos/PoweredByOpenSHA_Agua.jpg")));
private JLabel usgsImgLabel = new JLabel(new ImageIcon(FileUtils.loadImage("logos/usgs_resrisk.gif")));
private JLabel riskAgoraImgLabel = new JLabel(new ImageIcon(FileUtils.loadImage("logos/AgoraOpenRisk.jpg")));
// Strings for control pick list
protected final static String CONTROL_PANELS = "Control Panels";
protected final static String DISTANCE_CONTROL = "Max Source-Site Distance";
protected final static String SITES_OF_INTEREST_CONTROL = "Sites of Interest";
protected final static String CVM_CONTROL = "Set Site Params from Web Services";
// objects for control panels
protected SetMinSourceSiteDistanceControlPanel distanceControlPanel;
protected SitesOfInterestControlPanel sitesOfInterest;
protected SetSiteParamsFromWebServicesControlPanel cvmControlPanel;
private Insets plotInsets = new Insets( 4, 10, 4, 4 );
private Border border1;
// default insets
protected Insets defaultInsets = new Insets( 4, 4, 4, 4 );
// height and width of the applet
protected final static int W = 1100;
protected final static int H = 770;
//holds the ArbitrarilyDiscretizedFunc
protected ArbitrarilyDiscretizedFunc function;
protected String TITLE = new String("BCR Calculator");
private JPanel jPanel1 = new JPanel();
private Border border2;
private final static Dimension COMBO_DIM = new Dimension( 180, 30 );
private final static Dimension BUTTON_DIM = new Dimension( 80, 20 );
private Border border3;
private Border border4;
private Border border5;
private Border border6;
private Border border7;
private Border border8;
JSplitPane topSplitPane = new JSplitPane();
JButton clearButton = new JButton();
JPanel buttonPanel = new JPanel();
JCheckBox progressCheckBox = new JCheckBox();
JButton addButton = new JButton();
JComboBox controlComboBox = new JComboBox();
JSplitPane chartSplit = new JSplitPane();
JPanel panel = new JPanel();
/**
* adding scroll pane for showing data
*/
private JScrollPane dataScrollPane = new JScrollPane();
// text area to show the data values
private JTextArea pointsTextArea = new JTextArea();
GridBagLayout gridBagLayout9 = new GridBagLayout();
GridBagLayout gridBagLayout8 = new GridBagLayout();
JSplitPane imrSplitPane = new JSplitPane();
GridBagLayout gridBagLayout5 = new GridBagLayout();
JPanel erfTimespanPanel = new JPanel();
JPanel siteLocPanel = new JPanel();
JSplitPane controlsSplit = new JSplitPane();
JTabbedPane paramsTabbedPane = new JTabbedPane();
JPanel structuralPanel = new JPanel();
private BenefitCostBean bcbean ;
private JPanel bcPanel;
GridBagLayout gridBagLayout15 = new GridBagLayout();
GridBagLayout gridBagLayout13 = new GridBagLayout();
GridBagLayout gridBagLayout12 = new GridBagLayout();
JPanel imrPanel = new JPanel();
GridBagLayout gridBagLayout10 = new GridBagLayout();
BorderLayout borderLayout1 = new BorderLayout();
//instances of various calculators
HazardCurveCalculatorAPI calc;
CalcProgressBar progressClass;
protected CalcProgressBar startAppProgressClass;
//timer threads to show the progress of calculations
Timer timer;
//calculation thead
Thread calcThread;
//checks to see if HazardCurveCalculations are done
boolean isHazardCalcDone= false;
//counts the number of computation done till now
private int computationDisplayCount =0;
private DecimalFormat bcrFormat = new DecimalFormat("0.00");
/**this boolean keeps track when to plot the new data on top of other and when to
*add to the existing data.
* If it is true then add new data on top of existing data, but if it is false
* then add new data to the existing data(this option only works if it is ERF_List).
* */
boolean addData= true;
protected JButton cancelCalcButton = new JButton();
private FlowLayout flowLayout1 = new FlowLayout();
//Construct the applet
public BCR_Application() {
}
//Initialize the applet
public void init() {
try {
// initialize the control pick list
initControlList();
// initialize the GUI components
startAppProgressClass = new CalcProgressBar("Starting Application", "Initializing Application .. Please Wait");
jbInit();
// initialize the various GUI beans
initBenefitCostBean();
initIMR_GuiBean();
initSiteGuiBean();
try{
initERF_GuiBean();
}catch(RuntimeException e){
JOptionPane.showMessageDialog(this,"Connection to ERF's failed","Internet Connection Problem",
JOptionPane.OK_OPTION);
e.printStackTrace();
startAppProgressClass.dispose();
System.exit(0);
}
}
catch(Exception e) {
ExceptionUtils.throwAsRuntimeException(e);
}
startAppProgressClass.dispose();
((JPanel)getContentPane()).updateUI();
}
private static ApplicationVersion version;
/**
* Returns the Application version
* @return ApplicationVersion
*/
public static ApplicationVersion getAppVersion(){
if (version == null) {
try {
version = ApplicationVersion.loadBuildVersion();
} catch (IOException e) {
e.printStackTrace();
}
}
return version;
}
//Component initialization
protected void jbInit() throws Exception {
border1 = BorderFactory.createLineBorder(SystemColor.controlText,1);
border2 = BorderFactory.createLineBorder(SystemColor.controlText,1);
border3 = BorderFactory.createEmptyBorder();
border4 = BorderFactory.createLineBorder(SystemColor.controlText,1);
border5 = BorderFactory.createLineBorder(SystemColor.controlText,1);
border6 = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.white,Color.white,new Color(98, 98, 112),new Color(140, 140, 161));
border7 = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.white,Color.white,new Color(98, 98, 112),new Color(140, 140, 161));
border8 = BorderFactory.createBevelBorder(BevelBorder.RAISED,Color.white,Color.white,new Color(98, 98, 112),new Color(140, 140, 161));
this.getContentPane().setLayout(borderLayout1);
jPanel1.setLayout(gridBagLayout10);
jPanel1.setBackground(Color.white);
jPanel1.setBorder(border4);
jPanel1.setMinimumSize(new Dimension(959, 600));
jPanel1.setPreferredSize(new Dimension(959, 600));
//loading the OpenSHA Logo
topSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
clearButton.setText("Clear Results");
clearButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
clearButton_actionPerformed(e);
}
});
buttonPanel.setMinimumSize(new Dimension(568, 20));
buttonPanel.setLayout(flowLayout1);
progressCheckBox.setFont(new java.awt.Font("Dialog", 1, 12));
progressCheckBox.setSelected(true);
progressCheckBox.setText("Show Progress Bar");
addButton.setText("Compute");
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
addButton_actionPerformed(e);
}
});
controlComboBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
controlComboBox_actionPerformed(e);
}
});
panel.setLayout(gridBagLayout9);
panel.setBackground(Color.white);
panel.setBorder(border5);
panel.setMinimumSize(new Dimension(0, 0));
imrSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
dataScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
dataScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
dataScrollPane.setBorder( BorderFactory.createEtchedBorder() );
dataScrollPane.getViewport().add( pointsTextArea, null );
pointsTextArea.setEditable(false);
pointsTextArea.setLineWrap(true);
panel.add(dataScrollPane,new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0
, GridBagConstraints.CENTER, GridBagConstraints.BOTH, plotInsets, 0, 0 ) );
erfTimespanPanel.setLayout(gridBagLayout13);
erfTimespanPanel.setBackground(Color.white);
siteLocPanel.setLayout(gridBagLayout8);
siteLocPanel.setBackground(Color.white);
controlsSplit.setDividerSize(5);
structuralPanel.setLayout(gridBagLayout5);
structuralPanel.setBackground(Color.white);
structuralPanel.setBorder(border2);
structuralPanel.setMaximumSize(new Dimension(2147483647, 10000));
structuralPanel.setMinimumSize(new Dimension(2, 300));
structuralPanel.setPreferredSize(new Dimension(2, 300));
imrPanel.setLayout(gridBagLayout15);
imrPanel.setBackground(Color.white);
chartSplit.setLeftComponent(panel);
chartSplit.setRightComponent(paramsTabbedPane);
cancelCalcButton.setText("Cancel");
cancelCalcButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
cancelCalcButton_actionPerformed(e);
}
});
this.getContentPane().add(jPanel1, BorderLayout.CENTER);
jPanel1.add(topSplitPane, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(11, 4, 5, 6), 243, 231));
buttonPanel.add(controlComboBox, 0);
buttonPanel.add(addButton, 1);
buttonPanel.add(cancelCalcButton, 2);
buttonPanel.add(clearButton, 3);
buttonPanel.add(progressCheckBox, 4);
buttonPanel.add(usgsImgLabel, 5);
buttonPanel.add(openshaImgLabel, 6);
buttonPanel.add(riskAgoraImgLabel,7);
//making the cancel button not visible until user has started to do the calculation
cancelCalcButton.setVisible(false);
topSplitPane.add(chartSplit, JSplitPane.TOP);
chartSplit.add(panel, JSplitPane.LEFT);
chartSplit.add(paramsTabbedPane, JSplitPane.RIGHT);
imrSplitPane.add(imrPanel, JSplitPane.TOP);
imrSplitPane.add(siteLocPanel, JSplitPane.BOTTOM);
controlsSplit.add(imrSplitPane, JSplitPane.LEFT);
controlsSplit.add(erfTimespanPanel, JSplitPane.RIGHT);
paramsTabbedPane.add(structuralPanel, "Set Structural Type");
paramsTabbedPane.add(controlsSplit, "Set Hazard Curve");
topSplitPane.add(buttonPanel, JSplitPane.BOTTOM);
topSplitPane.setDividerLocation(590);
imrSplitPane.setDividerLocation(300);
controlsSplit.setDividerLocation(230);
structuralPanel.setLayout(gridBagLayout5);
chartSplit.setDividerLocation(590);
this.setSize(W,H);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation((dim.width - this.getSize().width) / 2, 0);
//EXIT_ON_CLOSE == 3
this.setDefaultCloseOperation(3);
this.setTitle("BCR Application ");
}
//Main method
public static void main(String[] args) {
new DisclaimerDialog(APP_NAME, APP_SHORT_NAME, getAppVersion());
DefaultExceptoinHandler exp = new DefaultExceptoinHandler(
APP_SHORT_NAME, getAppVersion(), null, null);
Thread.setDefaultUncaughtExceptionHandler(exp);
BCR_Application applet = new BCR_Application();
exp.setApp(applet);
exp.setParent(applet);
applet.init();
applet.setVisible(true);
}
//static initializer for setting look & feel
static {
String osName = System.getProperty("os.name");
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch(Exception e) {
}
}
/**
* this function is called when Add Graph button is clicked
* @param e
*/
void addButton_actionPerformed(ActionEvent e) {
cancelCalcButton.setVisible(true);
addButton();
}
/**
* Implementing the run method in the Runnable interface that creates a new thread
* to do Hazard Curve Calculation, this thread created is seperate from the
* timer thread, so that progress bar updation does not conflicts with Calculations.
*/
public void run() {
try{
computeHazardCurve();
cancelCalcButton.setVisible(false);
//disaggCalc = null;
calcThread = null;
}catch(Exception e){
setButtonsEnable(true);
e.printStackTrace();
BugReport bug = new BugReport(e, getParametersInfoAsString(), APP_SHORT_NAME, getAppVersion(), this);
BugReportDialog bugDialog = new BugReportDialog(this, bug, false);
bugDialog.setVisible(true);
}
}
/**
* This method creates the HazardCurveCalc and Disaggregation Calc(if selected) instances.
* If the internet connection is available then it creates a remote instances of
* the calculators on server where the calculations take place, else
* calculations are performed on the user's own machine.
*/
protected void createCalcInstance(){
try{
calc = new HazardCurveCalculator();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* this function is called to draw the graph
*/
protected void addButton() {
setButtonsEnable(false);
// do not show warning messages in IMR gui bean. this is needed
// so that warning messages for site parameters are not shown when Add graph is clicked
imrGuiBean.showWarningMessages(false);
try{
createCalcInstance();
}catch(Exception e){
setButtonsEnable(true);
e.printStackTrace();
BugReport bug = new BugReport(e, getParametersInfoAsString(), APP_SHORT_NAME, getAppVersion(), this);
BugReportDialog bugDialog = new BugReportDialog(this, bug, true);
bugDialog.setVisible(true);
}
// check if progress bar is desired and set it up if so
if(this.progressCheckBox.isSelected()) {
calcThread = new Thread(this);
calcThread.start();
timer = new Timer(200, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try{
int totRupture = calc.getTotRuptures();
int currRupture = calc.getCurrRuptures();
boolean totCurCalculated = true;
if(currRupture ==-1){
progressClass.setProgressMessage("Please wait, calculating total rutures ....");
totCurCalculated = false;
}
if(!isHazardCalcDone && totCurCalculated)
progressClass.updateProgress(currRupture, totRupture);
if (isHazardCalcDone) {
timer.stop();
progressClass.dispose();
}
}catch(Exception e){
e.printStackTrace();
}
}
});
}
else {
this.computeHazardCurve();
}
}
/**
*
* @return the application component
*/
protected Component getApplicationComponent(){
return this;
}
/**
* this function is called when "clear plot" is selected
*
* @param e
*/
void clearButton_actionPerformed(ActionEvent e) {
this.pointsTextArea.setText("");
computationDisplayCount = 0;
}
/**
* Any time a control paramater or independent paramater is changed
* by the user in a GUI this function is called, and a paramater change
* event is passed in. This function then determines what to do with the
* information ie. show some paramaters, set some as invisible,
* basically control the paramater lists.
*
* @param event
*/
public void parameterChange( ParameterChangeEvent event ) {
String S = C + ": parameterChange(): ";
if ( D ) System.out.println( "\n" + S + "starting: " );
String name1 = event.getParameterName();
// if IMR selection changed, update the site parameter list and supported IMT
if ( name1.equalsIgnoreCase(imrGuiBean.IMR_PARAM_NAME)) {
ScalarIMR imr = imrGuiBean.getSelectedIMR_Instance();
siteGuiBean.replaceSiteParams(imr.getSiteParamsIterator());
siteGuiBean.validate();
siteGuiBean.repaint();
}
if(name1.equalsIgnoreCase(bcbean.getCurrentVulnParam().getName())){
AbstractVulnerability currentModel = bcbean.getVulnModel(bcbean.CURRENT);
String currentIMT = currentModel.getIMT();
double currentPeriod = 0;
if(currentIMT.equals(SA_Param.NAME))
currentPeriod = currentModel.getPeriod();
AbstractVulnerability newModel = bcbean.getVulnModel(bcbean.RETRO);
String newIMT = newModel.getIMT();
double newPeriod = 0;
if(newIMT.equals(SA_Param.NAME))
newPeriod = newModel.getPeriod();
imrGuiBean.setIMRParamListAndEditor(currentIMT, newIMT, currentPeriod, newPeriod);
ScalarIMR imr = imrGuiBean.getSelectedIMR_Instance();
siteGuiBean.replaceSiteParams(imr.getSiteParamsIterator());
siteGuiBean.validate();
siteGuiBean.repaint();
}
}
/**
* Function to make the buttons enable or disable in the application.
* It is used in application to disable the button in the buttons panel
* if some computation is already going on.
* @param b
*/
protected void setButtonsEnable(boolean b){
addButton.setEnabled(b);
clearButton.setEnabled(b);
progressCheckBox.setEnabled(b);
}
/**
* Gets the probabilities functiion based on selected parameters
* this function is called when add Graph is clicked
*/
protected void computeHazardCurve() {
//starting the calculation
isHazardCalcDone = false;
BaseERF forecast = null;
// get the selected forecast model
try {
// whether to show progress bar in case of update forecast
erfGuiBean.showProgressBar(this.progressCheckBox.isSelected());
//get the selected ERF instance
forecast = erfGuiBean.getSelectedERF();
}
catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(this, e.getMessage(), "Incorrect Values",
JOptionPane.ERROR_MESSAGE);
setButtonsEnable(true);
return;
}
if (this.progressCheckBox.isSelected()) {
progressClass = new CalcProgressBar("Hazard-Curve Calc Status",
"Beginning Calculation ");
progressClass.displayProgressBar();
timer.start();
}
AbstractVulnerability currentModel = bcbean.getVulnModel(bcbean.CURRENT);
String currentIMT = currentModel.getIMT();
double currentPeriod = 0;
if(currentIMT.equals(SA_Param.NAME))
currentPeriod = currentModel.getPeriod();
// ArrayList<Double> currentIMLs = currentModel.getIMLVals();
double[] currentIMLs = currentModel.getIMLValues();
AbstractVulnerability newModel = bcbean.getVulnModel(bcbean.RETRO);
String newIMT = newModel.getIMT();
double newPeriod = 0;
if(newIMT.equals(SA_Param.NAME))
newPeriod = newModel.getPeriod();
// ArrayList<Double> newIMLs = newModel.getIMLVals();
double[] newIMLs = newModel.getIMLValues();
// get the selected IMR
ScalarIMR imr = imrGuiBean.getSelectedIMR_Instance();
// make a site object to pass to IMR
Site site = siteGuiBean.getSite();
LocationList locs = new LocationList();
Location loc = site.getLocation();
locs.add(loc);
// getting the wills site class values from servlet
// String siteClass="";
// try {
// ArrayList willsSiteClassList = ConnectToCVM.getWillsSiteTypeFromCVM(locs);
// siteClass = (String)willsSiteClassList.get(0);
// } catch (Exception e1) {
// e1.printStackTrace();
// }
// calculate the hazard curve
try {
if (distanceControlPanel != null) calc.setMaxSourceDistance(
distanceControlPanel.getDistance());
}
catch (Exception e) {
setButtonsEnable(true);
e.printStackTrace();
BugReport bug = new BugReport(e, getParametersInfoAsString(), APP_SHORT_NAME, getAppVersion(), this);
BugReportDialog bugDialog = new BugReportDialog(this, bug, false);
bugDialog.setVisible(true);
}
ArbitrarilyDiscretizedFunc currentHazardCurve = calcHazardCurve(currentIMT,currentPeriod,currentIMLs,site,forecast,imr);
ArbitrarilyDiscretizedFunc currentAnnualizedRates= null;
currentAnnualizedRates =
(ArbitrarilyDiscretizedFunc)calc.getAnnualizedRates(currentHazardCurve,
forecast.getTimeSpan().getDuration());
ArbitrarilyDiscretizedFunc retroHazardCurve = calcHazardCurve(newIMT,newPeriod,newIMLs,site,forecast,imr);
ArbitrarilyDiscretizedFunc retroAnnualizedRates = null;
retroAnnualizedRates =
(ArbitrarilyDiscretizedFunc)calc.getAnnualizedRates(retroHazardCurve,
forecast.getTimeSpan().getDuration());
EALCalculator currentCalc = new EALCalculator(currentAnnualizedRates,currentModel.getVulnerabilityFunc(),
bcbean.getCurrentReplaceCost());
double currentEALVal = currentCalc.computeEAL();
EALCalculator retroCalc = new EALCalculator(retroAnnualizedRates,newModel.getVulnerabilityFunc(),bcbean.getRetroReplaceCost());
double newEALVal = retroCalc.computeEAL();
BenefitCostCalculator bcCalc = new BenefitCostCalculator(currentEALVal,newEALVal,bcbean.getDiscountRate(),
bcbean.getDesignLife(),bcbean.getRetroCost());
double bcr = bcCalc.computeBCR();
double benefit = bcCalc.computeBenefit();
double cost = bcCalc.computeCost();
isHazardCalcDone = true;
displayData(currentHazardCurve,retroHazardCurve,currentEALVal,newEALVal,bcr,benefit,cost);
setButtonsEnable(true);
}
private void displayData(ArbitrarilyDiscretizedFunc currentHazardCurve,ArbitrarilyDiscretizedFunc retroHazardCurve,
double currentEALVal,double newEALVal,double bcr,double benefit,double cost){
++computationDisplayCount;
String data = pointsTextArea.getText();
if(computationDisplayCount !=1)
data +="\n\n";
data +="Benefit Cost Ratio Calculation # "+computationDisplayCount+"\n";
data +="BCR Desc. = "+bcbean.getDescription()+"\n";
// data +="Site Class = "+siteClass+"\n";
data +="Current EAL Val = "+currentEALVal+"\nRetrofitted EAL Val = "+newEALVal+"\n";
data +="Benefit = $"+bcrFormat.format(benefit)+"\nBenefit Cost Ratio = "+bcr+"\n";
data +="Curent Hazard Curve"+"\n"+currentHazardCurve.toString();
data +="Retrofitted Hazard Curve"+"\n"+retroHazardCurve.toString()+"\n\n";
pointsTextArea.setText(data);
}
// private ArbitrarilyDiscretizedFunc calcHazardCurve(String imt, double period, ArrayList<Double> imls,
// Site site,EqkRupForecastBaseAPI forecast,ScalarIntensityMeasureRelationshipAPI imr){
private ArbitrarilyDiscretizedFunc calcHazardCurve(String imt, double period, double[] imls,
Site site,BaseERF forecast,ScalarIMR imr){
// initialize the values in condProbfunc with log values as passed in hazFunction
// intialize the hazard function
ArbitrarilyDiscretizedFunc hazFunction = new ArbitrarilyDiscretizedFunc();
initX_Values(hazFunction,imls,imt);
imr.setIntensityMeasure(imt);
imr.getParameter(PeriodParam.NAME).setValue(period);
// ((AttenuationRelationship)imr).setIntensityMeasure(imt,period);
//System.out.println("22222222HazFunction: "+hazFunction.toString());
try {
// calculate the hazard curve
//eqkRupForecast = (EqkRupForecastAPI)FileUtils.loadObject("erf.obj");
try {
hazFunction = (ArbitrarilyDiscretizedFunc) calc.getHazardCurve(
hazFunction, site,imr, (ERF) forecast);
}
catch (Exception e) {
e.printStackTrace();
setButtonsEnable(true);
}
hazFunction = toggleHazFuncLogValues(hazFunction,imls);
hazFunction.setInfo(getParametersInfoAsString());
}
catch (RuntimeException e) {
JOptionPane.showMessageDialog(this, e.getMessage(),
"Parameters Invalid",
JOptionPane.INFORMATION_MESSAGE);
e.printStackTrace();
setButtonsEnable(true);
return null;
}
return hazFunction;
}
/**
* set x values in log space for Hazard Function to be passed to IMR
* if the selected IMT are SA , PGA , PGV or FaultDispl
* It accepts 1 parameters
*
* @param originalFunc : this is the function with X values set
*/
// private void initX_Values(DiscretizedFuncAPI arb,ArrayList<Double> imls, String imt){
private void initX_Values(DiscretizedFunc arb, double[] imls, String imt){
IMT_Info imtInfo = new IMT_Info();
if (imtInfo.isIMT_LogNormalDist(imt)) {
for(int i=0;i<imls.length;++i)
arb.set(Math.log(imls[i]),1);
//System.out.println("11111111111HazFunction: "+arb.toString());
}
else
throw new RuntimeException("Unsupported IMT");
}
/**
* Initialize the IMR Gui Bean
*/
protected void initIMR_GuiBean() {
AbstractVulnerability currentModel = bcbean.getVulnModel(bcbean.CURRENT);
String currentIMT = currentModel.getIMT();
double currentPeriod = 0;
if(currentIMT.equals(SA_Param.NAME))
currentPeriod = currentModel.getPeriod();
AbstractVulnerability newModel = bcbean.getVulnModel(bcbean.RETRO);
String newIMT = newModel.getIMT();
double newPeriod = 0;
if(newIMT.equals(SA_Param.NAME))
newPeriod = newModel.getPeriod();
imrPanel.removeAll();
imrGuiBean = new IMR_GuiBean(this,currentIMT,newIMT,currentPeriod,newPeriod);
imrGuiBean.getParameterEditor(imrGuiBean.IMR_PARAM_NAME).getParameter().addParameterChangeListener(this);
// show this gui bean the JPanel
imrPanel.add(this.imrGuiBean,new GridBagConstraints( 0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH, defaultInsets, 0, 0 ));
imrPanel.updateUI();
}
/**
* Initialize the site gui bean
*/
private void initSiteGuiBean() {
// get the selected IMR
ScalarIMR imr = imrGuiBean.getSelectedIMR_Instance();
// create the IMT Gui Bean object
siteGuiBean = new Site_GuiBean();
siteGuiBean.addSiteParams(imr.getSiteParamsIterator());
siteLocPanel.setLayout(gridBagLayout8);
siteLocPanel.add(siteGuiBean, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER,
GridBagConstraints.BOTH,
defaultInsets, 0, 0));
siteLocPanel.updateUI();
}
/**
* Initialize the ERF Gui Bean
*/
protected void initERF_GuiBean() {
if (erfGuiBean == null) {
try {
erfGuiBean = new ERF_GuiBean(ERF_Ref.get(false, ServerPrefUtils.SERVER_PREFS));
erfGuiBean.getParameter(erfGuiBean.ERF_PARAM_NAME).
addParameterChangeListener(this);
}
catch (InvocationTargetException e) {
e.printStackTrace();
//throw new RuntimeException("Connection to ERF's failed");
}
}
erfTimespanPanel.add(this.erfGuiBean, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0,
GridBagConstraints.CENTER, GridBagConstraints.BOTH, defaultInsets, 0, 0));
erfTimespanPanel.updateUI();
}
/**
* Initialize the Benefit cost GUI bean
*
*/
protected void initBenefitCostBean(){
// creates the instance of the BenefitCost bean
try {
bcbean = new BenefitCostBean();
} catch (IOException e) {
ExceptionUtils.throwAsRuntimeException(e);
}
bcPanel = (JPanel) bcbean.getVisualization(GuiBeanAPI.APPLICATION);
bcbean.getRetroVulnParam().addParameterChangeListener(this);
bcbean.getCurrentVulnParam().addParameterChangeListener(this);
structuralPanel.add(bcPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
structuralPanel.validate();
structuralPanel.repaint();
}
/**
* Initialize the items to be added to the control list
*/
protected void initControlList() {
controlComboBox.addItem(CONTROL_PANELS);
controlComboBox.addItem(DISTANCE_CONTROL);
controlComboBox.addItem(SITES_OF_INTEREST_CONTROL);
controlComboBox.addItem(CVM_CONTROL);
}
/**
* This function is called when controls pick list is chosen
* @param e
*/
void controlComboBox_actionPerformed(ActionEvent e) {
if(controlComboBox.getItemCount()<=0) return;
String selectedControl = controlComboBox.getSelectedItem().toString();
if(selectedControl.equalsIgnoreCase(this.DISTANCE_CONTROL))
initDistanceControl();
else if(selectedControl.equalsIgnoreCase(this.SITES_OF_INTEREST_CONTROL))
initSitesOfInterestControl();
else if(selectedControl.equalsIgnoreCase(this.CVM_CONTROL))
initCVMControl();
controlComboBox.setSelectedItem(this.CONTROL_PANELS);
}
/**
* Initialize the Min Source and site distance control.
* This function is called when user selects "Source Site Distance Control"
* from controls pick list
*/
private void initDistanceControl() {
if(this.distanceControlPanel==null)
distanceControlPanel = new SetMinSourceSiteDistanceControlPanel(this);
distanceControlPanel.pack();
distanceControlPanel.setVisible(true);
}
/**
* Initialize the Interesting sites control panel
* It will provide a pick list of interesting sites
*/
private void initSitesOfInterestControl() {
if(this.sitesOfInterest==null)
sitesOfInterest = new SitesOfInterestControlPanel(this, this.siteGuiBean);
sitesOfInterest.getComponent().pack();
sitesOfInterest.getComponent().setVisible(true);
}
/**
* Initialize the Interesting sites control panel
* It will provide a pick list of interesting sites
*/
private void initCVMControl() {
if(this.cvmControlPanel==null)
cvmControlPanel = new SetSiteParamsFromWebServicesControlPanel(this, this.imrGuiBean, this.siteGuiBean);
cvmControlPanel.pack();
cvmControlPanel.setVisible(true);
}
/**
* set x values back from the log space to the original linear values
* for Hazard Function after completion of the Hazard Calculations
* if the selected IMT are SA , PGA or PGV
* It accepts 1 parameters
*
* @param hazFunction : this is the function with X values set
*/
// private ArbitrarilyDiscretizedFunc toggleHazFuncLogValues(ArbitrarilyDiscretizedFunc hazFunc,ArrayList<Double> imls){
private ArbitrarilyDiscretizedFunc toggleHazFuncLogValues(ArbitrarilyDiscretizedFunc hazFunc,double[] imls){
int numPoints = hazFunc.size();
DiscretizedFunc tempFunc = hazFunc.deepClone();
hazFunc = new ArbitrarilyDiscretizedFunc();
// take log only if it is PGA, PGV ,SA or FaultDispl
for(int i=0;i<tempFunc.size();++i)
hazFunc.set(imls[i],tempFunc.getY(i));
return hazFunc;
}
/**
*
* @return the String containing the values selected for different parameters
*/
public String getParametersInfoAsString(){
return getMapParametersInfoAsHTML().replaceAll("<br>",SystemUtils.LINE_SEPARATOR);
}
/**
*
* @return the String containing the values selected for different parameters
*/
public String getMapParametersInfoAsHTML(){
String imrMetadata;
//if Probabilistic calculation then only add the metadata
//for visible parameters
imrMetadata = imrGuiBean.getVisibleParametersCloned().getParameterListMetadataString();
double maxSourceSiteDistance;
if (distanceControlPanel != null)
maxSourceSiteDistance = distanceControlPanel.getDistance();
else
maxSourceSiteDistance = MaxDistanceParam.DEFAULT;
return "<br>"+ "IMR Param List:" +"<br>"+
"---------------"+"<br>"+
imrMetadata+"<br><br>"+
"Site Param List: "+"<br>"+
"----------------"+"<br>"+
siteGuiBean.getParameterListEditor().getVisibleParametersCloned().getParameterListMetadataString()+"<br><br>"+
"Forecast Param List: "+"<br>"+
"--------------------"+"<br>"+
erfGuiBean.getERFParameterList().getParameterListMetadataString()+"<br><br>"+
"TimeSpan Param List: "+"<br>"+
"--------------------"+"<br>"+
erfGuiBean.getSelectedERFTimespanGuiBean().getParameterListMetadataString()+"<br><br>"+
"Max. Source-Site Distance = "+maxSourceSiteDistance;
}
/**
* This function stops the hazard curve calculation if started, so that user does not
* have to wait for the calculation to finish.
* Note: This function has one advantage , it starts over the calculation again, but
* if user has not changed any other parameter for the forecast, that won't
* be updated, so saves time and memory for not updating the forecast everytime,
* cancel is pressed.
* @param e
*/
void cancelCalcButton_actionPerformed(ActionEvent e) {
//stopping the Hazard Curve calculation thread
calcThread.stop();
calcThread = null;
//close the progress bar for the ERF GuiBean that displays "Updating Forecast".
erfGuiBean.closeProgressBar();
//stoping the timer thread that updates the progress bar
if(timer !=null && progressClass !=null){
timer.stop();
timer = null;
progressClass.dispose();
}
//stopping the Hazard Curve calculations on server
if(calc !=null){
try{
calc.stopCalc();
calc = null;
}catch(RuntimeException ee){
ee.printStackTrace();
setButtonsEnable(true);
BugReport bug = new BugReport(ee, getParametersInfoAsString(), APP_SHORT_NAME, getAppVersion(), this);
BugReportDialog bugDialog = new BugReportDialog(this, bug, false);
bugDialog.setVisible(true);
}
}
this.isHazardCalcDone = false;
//making the buttons to be visible
setButtonsEnable(true);
cancelCalcButton.setVisible(false);
}
/**
* This returns the Earthquake Forecast GuiBean which allows the the cybershake
* control panel to set the forecast parameters from cybershake control panel,
* similar to what they are set when calculating cybershaks curves.
*/
public ERF_GuiBean getEqkRupForecastGuiBeanInstance(){
return erfGuiBean;
}
/**
* This returns the Site Guibean using which allows to set the site locations
* in the OpenSHA application from cybershake control panel.
*/
public Site_GuiBean getSiteGuiBeanInstance() {
return siteGuiBean;
}
/**
* Updates the IMT_GuiBean to reflect the chnaged IM for the selected AttenuationRelationship.
* This method is called from the IMR_GuiBean to update the application with the Attenuation's
* supported IMs.
*
*/
public void updateIM() {
}
/**
* Updates the Site_GuiBean to reflect the chnaged SiteParams for the selected AttenuationRelationship.
* This method is called from the IMR_GuiBean to update the application with the Attenuation's
* Site Params.
*
*/
public void updateSiteParams() {
//get the selected IMR
ScalarIMR imr = imrGuiBean.getSelectedIMR_Instance();
siteGuiBean.replaceSiteParams(imr.getSiteParamsIterator());
siteGuiBean.validate();
siteGuiBean.repaint();
}
}
| [
"[email protected]"
] | |
77ee2d77adfdf43b2af32b3cd8c66ea7c54ea1d4 | af02ef11699eeda493977488913d166710dac23d | /src/com/resmanager/client/view/PullableScrollView.java | 125780fb079764d4abebad303e3c5207104106d6 | [] | no_license | Rachel-hsw/ResManagerClient | 3ac212ab91f5fe06893de445d3591170aadfee18 | f4b1f6958b0b3949e9e6e575877cf62a67e147e9 | refs/heads/master | 2021-06-29T18:47:45.628225 | 2017-09-13T10:16:36 | 2017-09-13T10:16:36 | 103,385,544 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 814 | java | package com.resmanager.client.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class PullableScrollView extends ScrollView implements Pullable
{
public PullableScrollView(Context context)
{
super(context);
}
public PullableScrollView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public PullableScrollView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
public boolean canPullDown()
{
if (getScrollY() == 0)
return true;
else
return false;
}
@Override
public boolean canPullUp()
{
if (getScrollY() >= (getChildAt(0).getHeight() - getMeasuredHeight()))
return true;
else
return false;
}
}
| [
"[email protected]"
] | |
c455054b1624f4ee1cadd1c45386170378bb41fb | 139960e2d7d55e71c15e6a63acb6609e142a2ace | /mobile_app1/leafModuleMin/src/main/java/leafModuleMinpackageJava0/Foo0.java | 9f5c58380b7a88a217aebf23d2a0c775d2b3e54f | [
"Apache-2.0"
] | permissive | uber-common/android-build-eval | 448bfe141b6911ad8a99268378c75217d431766f | 7723bfd0b9b1056892cef1fef02314b435b086f2 | refs/heads/master | 2023-02-18T22:25:15.121902 | 2023-02-06T19:35:34 | 2023-02-06T19:35:34 | 294,831,672 | 83 | 7 | Apache-2.0 | 2021-09-24T08:55:30 | 2020-09-11T23:27:37 | Java | UTF-8 | Java | false | false | 779 | java | package leafModuleMinpackageJava0;
import java.lang.Integer;
public class Foo0 {
Integer int0;
public void foo0() {
new module1055packageKt0.Foo0().foo4();
new module304packageKt0.Foo0().foo5();
new module1002packageJava0.Foo0().foo3();
new module491packageJava0.Foo0().foo5();
new module438packageKt0.Foo0().foo2();
new module1246packageJava0.Foo0().foo3();
new module288packageJava0.Foo0().foo0();
new module252packageJava0.Foo0().foo5();
new module410packageJava0.Foo0().foo1();
new module785packageJava0.Foo0().foo2();
new module648packageKt0.Foo0().foo8();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
}
| [
"[email protected]"
] | |
e88a6c684d59b8296aa87b4afe35c089da170481 | 85c3aadf4c8f3fbd8ad5a3f4c7437aea22291fb5 | /spring-introduction/src/main/java/com/example/ch02_factory/servlet/DemoServlet.java | 264b845ee2e627201d6bdbf81053605c46cb5811 | [
"Apache-2.0"
] | permissive | lijing0221/spring-framework-projects | a088ac5fb13a8f5b17f921b700af186baf06028e | eb07addffd7428d3483a40c4a55167ee444b1962 | refs/heads/master | 2023-01-14T16:10:48.434354 | 2020-11-20T11:34:03 | 2020-11-20T11:34:03 | 313,318,851 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 831 | java | package com.example.ch02_factory.servlet;
import com.example.ch02_factory.factory.BeanFactory;
import com.example.ch02_factory.service.DemoService;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* Servlet 测试示例
*
* @author lijing
* @date 2020/11/19 21:01
**/
@WebServlet(urlPatterns = "/factory")
public class DemoServlet extends HttpServlet {
public static final DemoService demoService = BeanFactory.getDemoService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
List<String> all = demoService.findAll();
resp.getWriter().println(all);
}
} | [
"[email protected]"
] | |
539b388a4b5b7963d83c093e60077d39414aa693 | 04208c15419cfbad47b8053e9f44101e5d9975d6 | /Multithreading/Thread-Pools/Application.java | c2a7422e9c2cb2a5fe63c1fc902d7f1392f5c1bd | [] | no_license | gauthamhs/Java | 7e88ce981ace631673102c93d038f65707535bc9 | 838e7fe71afb97175659e414d5c0b59f29682c2f | refs/heads/master | 2020-12-24T06:16:31.962654 | 2016-11-06T01:36:52 | 2016-11-06T01:36:52 | 30,766,102 | 0 | 1 | null | 2015-02-17T18:57:47 | 2015-02-13T16:58:09 | Java | UTF-8 | Java | false | false | 2,255 | java | //Thread Pool is a way of managing different threads at the same time so that the program can work efficiently.
//Its analogous to workers in a factory. There are say 5 tasks and each worker is given a specific task.
//In this method. when one worker is done with a task or say that a task is completed, the idle worker is
//assigned a new task.
//The first three output statements run at the same time.When a thread has completed a task, the same thread
//is assigned another task.
//Executor provides methods to manage termination and methods to keep tracking progress of one
//or more asynchronous tasks.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Worker implements Runnable{
private int id;
public Worker(int id) {
this.id = id;
}
public void run() {
System.out.println("Task Running: " + id);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Once the task is running, it has to wait 5 seconds to display
// The task completed.
e.printStackTrace();
}
System.out.println("Task completed: " + id) ;
}
}
public class Application {
public static void main(String[] args) {
// Worker worker = new Worker();
/*worker.run();
Thread t1 = new Thread(worker);
t1.start();*/
ExecutorService executor = Executors.newFixedThreadPool(3); // Setting up the no. of threads assigned
// for a task using the executor service. In this code, three threads from the thread pool are assigned
for(int i=0;i<10;i++){ // i pertains to the no. of tasks the thread has to perform
executor.submit(new Worker(i)); // All the tasks has been submitted.
}
executor.shutdown(); //The shutdown() method will allow previously submitted tasks to execute before terminating
System.out.println("All tasks submitted");
try {
executor.awaitTermination(1, TimeUnit.DAYS); //Tells the executor how much time it should wait
// until all tasks have completed execution.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("All Tasks Completed"); // Says when a task is completed.
}
}
| [
"[email protected]"
] | |
ce29df9a185e1beae2cb2b4571524559287e0b2f | 49e3e158eeffc61fcc522588831c25fd5aadba7b | /app/src/androidTest/java/com/muzi/numberview/ExampleInstrumentedTest.java | 730444fa1bafb7ecccdce69be84ce1a866dd2eb5 | [
"Apache-2.0"
] | permissive | xiangyutian/NumberView | f29c583ffea91c7e9e36f48d9f29127dcc69a4c3 | 1ef79b6ebcf9b59532ecf9d51d783b00c076213b | refs/heads/master | 2020-04-23T19:07:13.248914 | 2018-04-16T01:47:34 | 2018-04-16T01:47:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 739 | java | package com.muzi.numberview;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.muzi.numberview", appContext.getPackageName());
}
}
| [
"[email protected]"
] | |
0c5b32a8045deccb23640e9e0af9d382bba724d8 | 0be92950649594e8109ceacfeb6f08061974587c | /mybatis-mate/src/main/java/cn/newphy/druid/sql/visitor/functions/Trim.java | ba97cf607812d752e0877e4a226c8aa21b719624 | [] | no_license | Newphy/orm-mate | 73f4a02a9ee0438ee09a4c449777f71fb5ada8d7 | e74e0176a59f5b2956ea51db26a73a8a645a02a1 | refs/heads/master | 2020-03-27T17:10:17.436937 | 2018-08-31T06:30:25 | 2018-08-31T06:30:25 | 146,832,634 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,518 | java | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.newphy.druid.sql.visitor.functions;
import static cn.newphy.druid.sql.visitor.SQLEvalVisitor.EVAL_VALUE;
import cn.newphy.druid.sql.ast.SQLExpr;
import cn.newphy.druid.sql.ast.expr.SQLMethodInvokeExpr;
import cn.newphy.druid.sql.visitor.SQLEvalVisitor;
public class Trim implements Function {
public final static Trim instance = new Trim();
public Object eval(SQLEvalVisitor visitor, SQLMethodInvokeExpr x) {
if (x.getParameters().size() != 1) {
return SQLEvalVisitor.EVAL_ERROR;
}
SQLExpr param0 = x.getParameters().get(0);
param0.accept(visitor);
Object param0Value = param0.getAttributes().get(EVAL_VALUE);
if (param0Value == null) {
return SQLEvalVisitor.EVAL_ERROR;
}
String strValue = param0Value.toString();
String result = strValue.trim();
return result;
}
}
| [
"[email protected]"
] | |
6a15eec3e2f703cb63c389c7b91709cef2eed2a4 | 83df42e12908068e246e5b87facc034bab39fb9f | /src/main/java/org/smart4j/framework/helper/ConfigHelper.java | 43b66af870e706ae67fa408fb708420643133def | [] | no_license | RayZhangSB/smart_framework | c18e82c1ecfd993e887d4fd7914544e4551dfefe | d98d998d372afb707d7aaf16a3f5a957dce8cfd3 | refs/heads/master | 2020-03-15T23:52:07.191145 | 2018-05-24T08:05:01 | 2018-05-24T08:05:01 | 132,402,400 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | package org.smart4j.framework.helper;
import org.smart4j.framework.ConfigConstant;
import org.smart4j.framework.util.PropsUtil;
import java.util.Properties;
import static org.smart4j.framework.ConfigConstant.CONFIG_FILE;
/**
* @ClassName ConfigHelper
* @Description:属性文件助手
* @Author Raymond Zhang
* @Date 2018/5/6 17:59
* @Version 1.0
**/
public final class ConfigHelper {
private static final Properties CONFIG_PROPS = PropsUtil.loadProps(CONFIG_FILE);
public static String getJdbcDriver() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.JDBC_DRIVER);
}
public static String getJdbcUrl() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.JDBC_URL);
}
public static String getJdbcUserName() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.JDBC_USERNAME);
}
public static String getJdbcPassword() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.JDBC_PASSWORD);
}
public static String getAppBasePackage() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.APP_BASE_PACKAGE);
}
public static String getAppJspPath() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.APP_JSP_PATH, "/WEB-INF/view/");
}
public static String getAppAssetPath() {
return PropsUtil.getString(CONFIG_PROPS, ConfigConstant.APP_ASSET_PATH, "/asset/");
}
public static int getAppUploadLimit() {
return 50;
}
}
| [
"[email protected]"
] | |
35cc6ad1cf93c366c087ecfa3b21af7ff9ca2abe | 7c5ed6c01618d0ec5cea08692fb2384da90fb387 | /src/main/java/com/qy/sp/fee/modules/piplecode/bwhite/BWhiteService.java | 0bb8ab60fd1278ac6c83b2ae2aad3ac65f898146 | [] | no_license | xtgodlike/SPFee | f5dac9de5b2e6fb0ae46d1d2ce215270ce318ea2 | 045bb2aca00afcd36b014813ade5daa723f0304f | refs/heads/master | 2021-01-22T04:01:27.468202 | 2018-01-03T02:58:16 | 2018-01-03T02:58:16 | 92,421,411 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 8,251 | java | package com.qy.sp.fee.modules.piplecode.bwhite;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.qy.sp.fee.common.utils.DateTimeUtils;
import com.qy.sp.fee.common.utils.GlobalConst;
import com.qy.sp.fee.common.utils.KeyHelper;
import com.qy.sp.fee.common.utils.NumberUtil;
import com.qy.sp.fee.common.utils.StringUtil;
import com.qy.sp.fee.dao.TSdkConfigDao;
import com.qy.sp.fee.dao.TSdkconfigMobileBaseDao;
import com.qy.sp.fee.dto.TChannel;
import com.qy.sp.fee.dto.TOrder;
import com.qy.sp.fee.dto.TProduct;
import com.qy.sp.fee.dto.TSdkConfig;
import com.qy.sp.fee.dto.TSdkConfigQueryKey;
import com.qy.sp.fee.dto.TSdkconfigMobileBase;
import com.qy.sp.fee.entity.BaseChannelRequest;
import com.qy.sp.fee.entity.BaseResult;
import com.qy.sp.fee.modules.piplecode.base.ChannelService;
import net.sf.json.JSONObject;
@Service
public class BWhiteService extends ChannelService {
private Logger logger = LoggerFactory.getLogger(BWhiteService.class);
public static final String CONFIG_CODE_START_TIME ="codeStartTime";
@Resource
private TSdkConfigDao tSdkConfigDao;
@Resource
private TSdkconfigMobileBaseDao tSdkconfigMobileBaseDao;
@Override
public String getPipleId() {
return "14714136609207184697301";
}
@Override
public JSONObject processGetSMS(JSONObject requestBody) throws Exception {
String productCode = requestBody.optString("productCode");
String apiKey = requestBody.optString("apiKey");
String mobile = requestBody.optString("mobile");
String pipleId = requestBody.optString("pipleId");
String appId = requestBody.optString("appId");
String extData = requestBody.optString("extData");
String pipleOrderId = requestBody.optString("pipleOrderId");
String contentId = requestBody.optString("contentId");
String releaseChannelId = requestBody.optString("releaseChannelId");
String cpId = requestBody.optString("cpId");
String cId = requestBody.optString("cid");
String appVersion = requestBody.optString("appVersion");
logger.info("BWRequest:"+requestBody.toString());
JSONObject result = new JSONObject();
if(StringUtil.isEmptyString(productCode) || StringUtil.isEmptyString(apiKey) || StringUtil.isEmptyString(mobile)|| StringUtil.isEmptyString(appId) ){
result.put("resultCode",GlobalConst.CheckResult.MUST_PARAM_ISNULL+"");
result.put("resultMsg",GlobalConst.CheckResultDesc.message.get(GlobalConst.CheckResult.MUST_PARAM_ISNULL));
} else {
BaseChannelRequest req = new BaseChannelRequest();
req.setApiKey(apiKey);
req.setProductCode(productCode);
req.setPipleId(pipleId);
req.setMobile(mobile);
BaseResult bResult = this.accessVerify(req);
if (bResult != null) {// 返回不为空则校验不通过
result.put("resultCode",bResult.getResultCode());
result.put("resultMsg",bResult.getResultMsg());
logger.info("BWResoonse:"+result.toString());
return result;
} else {
TChannel tChannel = this.tChannelDao.selectByApiKey(apiKey);
TSdkConfigQueryKey key = new TSdkConfigQueryKey();
key.setAppId(appId);
key.setChannelId(tChannel.getChannelId());
key.setPipleId(getPipleId());
key.setProvinceId(req.getProvinceId()+"");
key.setConfigId(CONFIG_CODE_START_TIME);
TSdkConfig config = null;
List<TSdkConfig> configs = tSdkConfigDao.selectConfigurationsByConfigQueryKey(key);
if(configs.size() >0){
config = configs.get(0);
}
if(config != null){
try{
String codeStartTime = config.getConfigValue();
Date currentDate = DateTimeUtils.getCurrentTime();
currentDate.setYear(70);
currentDate.setMonth(0);
currentDate.setDate(1);
String times[] = codeStartTime.split(",");
boolean isTimeOk = false;
for(String time: times){
time = time.substring(1,time.length()-1);
String start = time.split("-")[0];
Date startDate = DateTimeUtils.toTime(start,"HH:mm:ss");
String end = time.split("-")[1];
Date endDate =DateTimeUtils.toTime(end,"HH:mm:ss");
if(currentDate.getTime() > startDate.getTime() && currentDate.getTime() < endDate.getTime()){
isTimeOk = true;
}
}
if(!isTimeOk){
result.put("resultCode","-1");
result.put("resultMsg","不在时间段内");
logger.info("BWResoonse:"+result.toString());
return result;
}
}catch(Exception e){
e.printStackTrace();
}
}
TSdkconfigMobileBase tSdkconfigMobileBase = new TSdkconfigMobileBase();
tSdkconfigMobileBase.setAppId(appId);
tSdkconfigMobileBase.setContentId(contentId);
tSdkconfigMobileBase.setCpId(cpId);
tSdkconfigMobileBase.setReleaseChannelId(releaseChannelId);
TSdkconfigMobileBase sdkconfigMobileConfig = tSdkconfigMobileBaseDao.selectByPrimaryKey(tSdkconfigMobileBase);
if(sdkconfigMobileConfig != null){
boolean isOPen = NumberUtil.getBoolean(sdkconfigMobileConfig.getIsOpen());
if(!isOPen){
result.put("resultCode","-1");
result.put("resultMsg","基地该渠道未打开,联系管理员");
logger.info("BWResoonse:"+result.toString());
return result;
}
boolean isBWhite = NumberUtil.getBoolean(sdkconfigMobileConfig.getIsUseBWhite());
if(!isBWhite){
result.put("resultCode","-1");
result.put("resultMsg","基地该渠道黑白包未开启");
logger.info("BWResoonse:"+result.toString());
return result;
}
String startCodeTime = sdkconfigMobileConfig.getStartCodeTime();
if(StringUtil.isNotEmptyString(startCodeTime)){
Date currentDate = DateTimeUtils.getCurrentTime();
currentDate.setYear(70);
currentDate.setMonth(0);
currentDate.setDate(1);
String times[] = startCodeTime.split(",");
boolean isTimeOk = false;
for(String time: times){
time = time.substring(1,time.length()-1);
String start = time.split("-")[0];
Date startDate = DateTimeUtils.toTime(start,"HH:mm:ss");
String end = time.split("-")[1];
Date endDate =DateTimeUtils.toTime(end,"HH:mm:ss");
if(currentDate.getTime() > startDate.getTime() && currentDate.getTime() < endDate.getTime()){
isTimeOk = true;
}
}
if(!isTimeOk){
result.put("resultCode","-1");
result.put("resultMsg","该基地渠道开放,不在时间段内");
logger.info("BWResoonse:"+result.toString());
return result;
}
}else{
result.put("resultCode","-1");
result.put("resultMsg","该省份时间段未开通。请开通");
logger.info("BWResoonse:"+result.toString());
return result;
}
}else{
result.put("resultCode","-1");
result.put("resultMsg","该版本没有配置策略。");
logger.info("BWResoonse:"+result.toString());
return result;
}
String groupId = KeyHelper.createKey();
TProduct tProduct = this.tProductDao.selectByCode(productCode);
statistics( STEP_GET_SMS_CHANNEL_TO_PLATFORM, groupId, requestBody.toString());
TOrder order = new TOrder();
order.setAmount(new BigDecimal(tProduct.getPrice()/100.0));
order.setChannelId(tChannel.getChannelId());
order.setCreateTime(DateTimeUtils.getCurrentTime());
order.setMobile(mobile);
order.setOrderId(KeyHelper.createKey());
order.setOrderStatus(GlobalConst.OrderStatus.INIT);
order.setPipleId(getPipleId());
order.setPipleOrderId(pipleOrderId);
order.setProductId(tProduct.getProductId());
order.setProvinceId(req.getProvinceId());
order.setSubStatus(GlobalConst.SubStatus.PAY_INIT);
order.setGroupId(groupId);
order.setExtData(extData);
order.setAppId(appId);
this.SaveOrderInsert(order);
result.put("resultCode",GlobalConst.Result.SUCCESS);
result.put("orderId",order.getOrderId());
result.put("resultMsg","获取成功");
statistics(STEP_BACK_SMS_PLATFORM_TO_CHANNEL, groupId, JSONObject.fromObject(result).toString());
}
}
logger.info("BWResoonse:"+result.toString());
return result;
}
@Override
protected boolean isUseableTradeDayAndMonth() {
return true;
}
}
| [
"[email protected]"
] | |
65ab237452d3305be775d2c09f88a4c8a7d2da50 | 0d5cbabdb8b7257d075c4470f90847e9493f80b8 | /app/src/main/java/com/jiubang/commerce/database/table/PkgRecordTable.java | 375bd08d2f9f6e80cf7170b28302944b1458b4f0 | [] | no_license | hgy413/filemanager | d214c692b862fdb6e76388f8454492335c5aadc9 | b445c4b46bcce08fb889875e342cf6a08e747d00 | refs/heads/master | 2022-07-06T20:51:46.342792 | 2020-05-19T12:55:11 | 2020-05-19T12:55:11 | 264,810,162 | 0 | 0 | null | 2020-05-18T02:58:47 | 2020-05-18T02:58:46 | null | UTF-8 | Java | false | false | 6,669 | java | package com.jiubang.commerce.database.table;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import com.jb.ga0.commerce.util.LogUtils;
import com.jiubang.commerce.database.DataBaseHelper;
public class PkgRecordTable {
public static final String CREATE_TABLE_SQL = "CREATE TABLE IF NOT EXISTS PkgRecordTable (packageName TEXT NOT NULL UNIQUE DEFAULT(-1), hash INTEGER, updateTime NUMERIC)";
public static final String HASH = "hash";
private static final int MAX_ROWS = 500;
public static final String PACKAGE_NAME = "packageName";
public static final String TABLE_NAME = "PkgRecordTable";
public static final String UPDATE_TIME = "updateTime";
private static PkgRecordTable sInstance;
private DataBaseHelper mDatabaseHelper;
private PkgRecordTable(Context context) {
this.mDatabaseHelper = DataBaseHelper.getInstance(context);
}
public static synchronized PkgRecordTable getInstance(Context context) {
PkgRecordTable pkgRecordTable;
synchronized (PkgRecordTable.class) {
if (sInstance == null) {
sInstance = new PkgRecordTable(context);
}
pkgRecordTable = sInstance;
}
return pkgRecordTable;
}
public boolean insertData(String packageName) {
boolean z = false;
if (!TextUtils.isEmpty(packageName)) {
SQLiteDatabase sqlDatabase = null;
try {
sqlDatabase = this.mDatabaseHelper.getWritableDatabase();
sqlDatabase.beginTransaction();
ContentValues values = new ContentValues();
values.put("packageName", packageName);
values.put(HASH, Integer.valueOf(packageName.hashCode()));
values.put("updateTime", Long.valueOf(System.currentTimeMillis()));
sqlDatabase.replace(TABLE_NAME, (String) null, values);
sqlDatabase.setTransactionSuccessful();
z = true;
if (sqlDatabase != null && sqlDatabase.inTransaction()) {
sqlDatabase.endTransaction();
}
} catch (Exception e) {
LogUtils.e("Ad_SDK", "PkgRecordTable--insertData Exception!", e);
if (sqlDatabase != null && sqlDatabase.inTransaction()) {
sqlDatabase.endTransaction();
}
} catch (Throwable th) {
if (sqlDatabase != null && sqlDatabase.inTransaction()) {
sqlDatabase.endTransaction();
}
throw th;
}
}
return z;
}
public boolean deleteDataBefore(long timePoint) {
boolean z = true;
if (timePoint <= 0) {
return false;
}
if (this.mDatabaseHelper.delete(TABLE_NAME, " updateTime < ? ", new String[]{String.valueOf(timePoint)}) <= 0) {
z = false;
}
return z;
}
/* JADX WARNING: Removed duplicated region for block: B:10:0x0060 */
/* JADX WARNING: Removed duplicated region for block: B:13:0x006b */
/* Code decompiled incorrectly, please refer to instructions dump. */
public android.util.SparseArray<com.jiubang.commerce.database.model.InstalledPkgBean> getAllData() {
/*
r20 = this;
android.util.SparseArray r16 = new android.util.SparseArray
r16.<init>()
java.util.ArrayList r14 = new java.util.ArrayList
r14.<init>()
r11 = 0
java.lang.String r9 = "updateTime DESC"
r0 = r20
com.jiubang.commerce.database.DataBaseHelper r2 = r0.mDatabaseHelper // Catch:{ Exception -> 0x007d }
java.lang.String r3 = "PkgRecordTable"
r4 = 0
r5 = 0
r6 = 0
r7 = 0
r8 = 0
android.database.Cursor r11 = r2.query(r3, r4, r5, r6, r7, r8, r9) // Catch:{ Exception -> 0x007d }
if (r11 == 0) goto L_0x005e
boolean r2 = r11.moveToFirst() // Catch:{ Exception -> 0x007d }
if (r2 == 0) goto L_0x005e
r10 = 0
L_0x0025:
com.jiubang.commerce.database.model.InstalledPkgBean r10 = new com.jiubang.commerce.database.model.InstalledPkgBean // Catch:{ Exception -> 0x007d }
r10.<init>() // Catch:{ Exception -> 0x007d }
java.lang.String r2 = "packageName"
int r2 = r11.getColumnIndex(r2) // Catch:{ Exception -> 0x007d }
java.lang.String r15 = r11.getString(r2) // Catch:{ Exception -> 0x007d }
java.lang.String r2 = "hash"
int r2 = r11.getColumnIndex(r2) // Catch:{ Exception -> 0x007d }
int r13 = r11.getInt(r2) // Catch:{ Exception -> 0x007d }
java.lang.String r2 = "updateTime"
int r2 = r11.getColumnIndex(r2) // Catch:{ Exception -> 0x007d }
long r18 = r11.getLong(r2) // Catch:{ Exception -> 0x007d }
r10.setPackageName(r15) // Catch:{ Exception -> 0x007d }
r0 = r18
r10.setUpdateTime(r0) // Catch:{ Exception -> 0x007d }
r14.add(r10) // Catch:{ Exception -> 0x007d }
r0 = r16
r0.put(r13, r10) // Catch:{ Exception -> 0x007d }
boolean r2 = r11.moveToNext() // Catch:{ Exception -> 0x007d }
if (r2 != 0) goto L_0x0025
L_0x005e:
if (r11 == 0) goto L_0x0063
r11.close()
L_0x0063:
int r2 = r14.size()
r3 = 500(0x1f4, float:7.0E-43)
if (r2 <= r3) goto L_0x007c
r2 = 499(0x1f3, float:6.99E-43)
java.lang.Object r2 = r14.get(r2)
com.jiubang.commerce.database.model.InstalledPkgBean r2 = (com.jiubang.commerce.database.model.InstalledPkgBean) r2
long r2 = r2.getUpdateTime()
r0 = r20
r0.deleteDataBefore(r2)
L_0x007c:
return r16
L_0x007d:
r12 = move-exception
r12.printStackTrace() // Catch:{ all -> 0x0087 }
if (r11 == 0) goto L_0x0063
r11.close()
goto L_0x0063
L_0x0087:
r2 = move-exception
if (r11 == 0) goto L_0x008d
r11.close()
L_0x008d:
throw r2
*/
throw new UnsupportedOperationException("Method not decompiled: com.jiubang.commerce.database.table.PkgRecordTable.getAllData():android.util.SparseArray");
}
}
| [
"[email protected]"
] | |
c8529516304b8b4dc260a3b7d0821d572e3c6a02 | c2745516073be0e243c2dff24b4bb4d1d94d18b8 | /sdk/communication/azure-communication-email/src/main/java/com/azure/communication/email/implementation/AzureCommunicationServicesClientImpl.java | 1fd74f5f9f9c458ad1458acc06976b8c249bef14 | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-3-Clause",
"CC0-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later"
] | permissive | milismsft/azure-sdk-for-java | 84b48d35e3fca8611933b3f86929788e5e8bceed | f4827811c870d09855417271369c592412986861 | refs/heads/master | 2022-09-25T19:29:44.973618 | 2022-08-17T14:43:22 | 2022-08-17T14:43:22 | 90,779,733 | 1 | 0 | MIT | 2021-12-21T21:11:58 | 2017-05-09T18:37:49 | Java | UTF-8 | Java | false | false | 4,441 | java | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.communication.email.implementation;
import com.azure.communication.email.EmailServiceVersion;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.HttpPipelineBuilder;
import com.azure.core.http.policy.CookiePolicy;
import com.azure.core.http.policy.RetryPolicy;
import com.azure.core.http.policy.UserAgentPolicy;
import com.azure.core.util.serializer.JacksonAdapter;
import com.azure.core.util.serializer.SerializerAdapter;
/** Initializes a new instance of the AzureCommunicationServicesClient type. */
public final class AzureCommunicationServicesClientImpl {
/** The communication resource, for example https://my-resource.communication.azure.com. */
private final String endpoint;
/**
* Gets The communication resource, for example https://my-resource.communication.azure.com.
*
* @return the endpoint value.
*/
public String getEndpoint() {
return this.endpoint;
}
/** Service version. */
private final EmailServiceVersion serviceVersion;
/**
* Gets Service version.
*
* @return the serviceVersion value.
*/
public EmailServiceVersion getServiceVersion() {
return this.serviceVersion;
}
/** The HTTP pipeline to send requests through. */
private final HttpPipeline httpPipeline;
/**
* Gets The HTTP pipeline to send requests through.
*
* @return the httpPipeline value.
*/
public HttpPipeline getHttpPipeline() {
return this.httpPipeline;
}
/** The serializer to serialize an object into a string. */
private final SerializerAdapter serializerAdapter;
/**
* Gets The serializer to serialize an object into a string.
*
* @return the serializerAdapter value.
*/
public SerializerAdapter getSerializerAdapter() {
return this.serializerAdapter;
}
/** The EmailsImpl object to access its operations. */
private final EmailsImpl emails;
/**
* Gets the EmailsImpl object to access its operations.
*
* @return the EmailsImpl object.
*/
public EmailsImpl getEmails() {
return this.emails;
}
/**
* Initializes an instance of AzureCommunicationServicesClient client.
*
* @param endpoint The communication resource, for example https://my-resource.communication.azure.com.
* @param serviceVersion Service version.
*/
public AzureCommunicationServicesClientImpl(
String endpoint, EmailServiceVersion serviceVersion) {
this(
new HttpPipelineBuilder()
.policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy())
.build(),
JacksonAdapter.createDefaultSerializerAdapter(),
endpoint,
serviceVersion);
}
/**
* Initializes an instance of AzureCommunicationServicesClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param endpoint The communication resource, for example https://my-resource.communication.azure.com.
* @param serviceVersion Service version.
*/
public AzureCommunicationServicesClientImpl(
HttpPipeline httpPipeline, String endpoint, EmailServiceVersion serviceVersion) {
this(httpPipeline, JacksonAdapter.createDefaultSerializerAdapter(), endpoint, serviceVersion);
}
/**
* Initializes an instance of AzureCommunicationServicesClient client.
*
* @param httpPipeline The HTTP pipeline to send requests through.
* @param serializerAdapter The serializer to serialize an object into a string.
* @param endpoint The communication resource, for example https://my-resource.communication.azure.com.
* @param serviceVersion Service version.
*/
public AzureCommunicationServicesClientImpl(
HttpPipeline httpPipeline,
SerializerAdapter serializerAdapter,
String endpoint,
EmailServiceVersion serviceVersion) {
this.httpPipeline = httpPipeline;
this.serializerAdapter = serializerAdapter;
this.endpoint = endpoint;
this.serviceVersion = serviceVersion;
this.emails = new EmailsImpl(this);
}
}
| [
"[email protected]"
] | |
0ba0606c9fd1fb63fc2e6053773a27572614a8cd | d7c5121237c705b5847e374974b39f47fae13e10 | /airspan.netspan/src/main/java/Netspan/NBI_14_50/API/Statistics/LinkAdaptationRawGet.java | 0dd7b80045060f62728573fb9ff14dcfafe4e692 | [] | no_license | AirspanNetworks/SWITModules | 8ae768e0b864fa57dcb17168d015f6585d4455aa | 7089a4b6456621a3abd601cc4592d4b52a948b57 | refs/heads/master | 2022-11-24T11:20:29.041478 | 2020-08-09T07:20:03 | 2020-08-09T07:20:03 | 184,545,627 | 1 | 0 | null | 2022-11-16T12:35:12 | 2019-05-02T08:21:55 | Java | UTF-8 | Java | false | false | 4,529 | java |
package Netspan.NBI_14_50.API.Statistics;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="NodeName" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="NodeId" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/>
* <element name="DateStart" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* <element name="DateEnd" type="{http://www.w3.org/2001/XMLSchema}dateTime"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"nodeName",
"nodeId",
"dateStart",
"dateEnd"
})
@XmlRootElement(name = "LinkAdaptationRawGet")
public class LinkAdaptationRawGet {
@XmlElement(name = "NodeName")
protected List<String> nodeName;
@XmlElement(name = "NodeId")
protected List<String> nodeId;
@XmlElement(name = "DateStart", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar dateStart;
@XmlElement(name = "DateEnd", required = true)
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar dateEnd;
/**
* Gets the value of the nodeName property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nodeName property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNodeName().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNodeName() {
if (nodeName == null) {
nodeName = new ArrayList<String>();
}
return this.nodeName;
}
/**
* Gets the value of the nodeId property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nodeId property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNodeId().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getNodeId() {
if (nodeId == null) {
nodeId = new ArrayList<String>();
}
return this.nodeId;
}
/**
* Gets the value of the dateStart property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateStart() {
return dateStart;
}
/**
* Sets the value of the dateStart property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateStart(XMLGregorianCalendar value) {
this.dateStart = value;
}
/**
* Gets the value of the dateEnd property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getDateEnd() {
return dateEnd;
}
/**
* Sets the value of the dateEnd property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateEnd(XMLGregorianCalendar value) {
this.dateEnd = value;
}
}
| [
"build.Airspan.com"
] | build.Airspan.com |
634ef746e58af02aa4404f51895fc4afcd2bbd9e | d1a6d1e511df6db8d8dd0912526e3875c7e1797d | /genny_JavaWithoutLambdas/applicationModule/src/main/java/applicationModulepackageJava8/Foo148.java | 54ff0e32059e7092f5a91036352d719058468296 | [] | no_license | NikitaKozlov/generated-project-for-desugaring | 0bc1443ab3ddc84cd289331c726761585766aea7 | 81506b3711004185070ca4bb9a93482b70011d36 | refs/heads/master | 2020-03-20T00:35:06.996525 | 2018-06-12T09:30:37 | 2018-06-12T09:30:37 | 137,049,317 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 346 | java | package applicationModulepackageJava8;
public class Foo148 {
public void foo0() {
new applicationModulepackageJava8.Foo147().foo5();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
public void foo5() {
foo4();
}
}
| [
"[email protected]"
] | |
a9765991dfa7c50fe0cecfff5aa402df7051abe6 | 98190029d1de72d493e6a730ff4607a50a858946 | /src/main/java/l2d/game/network/L2GamePacketHandler.java | 9290053f3cb0a00eb22268064d6b7c1a6cf41b73 | [] | no_license | iBezneR/interlude | e9777e24330b0342c2657eee8ada7914cfd6d1d0 | 764c889874034cf04d8e7b67792d705bee4ef719 | refs/heads/master | 2023-03-02T13:48:24.884131 | 2018-08-29T09:37:41 | 2018-08-29T09:37:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 22,485 | java | package l2d.game.network;
import static l2d.game.network.L2GameClient.GameClientState.IN_GAME;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.util.concurrent.RejectedExecutionException;
import java.util.logging.Logger;
import l2d.Config;
import l2d.ext.network.HeaderInfo;
import l2d.ext.network.IClientFactory;
import l2d.ext.network.IMMOExecutor;
import l2d.ext.network.IPacketHandler;
import l2d.ext.network.MMOConnection;
import l2d.ext.network.ReceivablePacket;
import l2d.ext.network.TCPHeaderHandler;
import l2d.game.ThreadPoolManager;
import l2d.game.clientpackets.*;
import l2d.game.model.L2Player;
import l2d.game.network.L2GameClient.GameClientState;
/**
* Stateful Packet Handler<BR>
* The Stateful approach prevents the server from handling inconsistent packets, examples:<BR>
* <li>Clients sends a MoveToLocation packet without having a character attached. (Potential errors handling the packet).</li>
* <li>Clients sends a RequestAuthLogin being already authed. (Potential exploit).</li>
* <BR><BR>
* Note: If for a given exception a packet needs to be handled on more then one state, then it should be added to all these states.
*/
public final class L2GamePacketHandler extends TCPHeaderHandler<L2GameClient> implements IPacketHandler<L2GameClient>, IClientFactory<L2GameClient>, IMMOExecutor<L2GameClient>
{
private static final Logger _log = Logger.getLogger(L2GamePacketHandler.class.getName());
/**
* @param subHeaderHandler
*/
public L2GamePacketHandler()
{
super(null);
}
// implementation
@Override
public ReceivablePacket<L2GameClient> handlePacket(ByteBuffer buf, L2GameClient client)
{
int opcode = buf.get() & 0xFF;
ReceivablePacket<L2GameClient> msg = null;
GameClientState state = client.getState();
switch(state)
{
case CONNECTED:
if(opcode == 0x00)
msg = new ProtocolVersion();
else if(opcode == 0x08)
msg = new AuthLogin();
else
{
//printDebug(opcode, buf, state, client);
}
break;
case AUTHED:
switch(opcode)
{
case 0x09:
msg = new Logout();
break;
case 0x0b:
msg = new CharacterCreate();
break;
case 0x0c:
msg = new CharacterDelete();
break;
case 0x0d:
msg = new CharacterSelected();
break;
case 0x0e:
msg = new NewCharacter();
break;
case 0x62:
msg = new CharacterRestore();
break;
case 0x68:
msg = new RequestPledgeCrest();
break;
default:
//printDebug(opcode, buf, state, client);
break;
}
break;
case IN_GAME:
switch(opcode)
{
case 0x01:
msg = new MoveBackwardToLocation();
break;
// case 0x02:
// // Say ... not used any more ??
// break;
case 0x03:
msg = new EnterWorld();
break;
case 0x04:
msg = new Action();
break;
case 0x09:
msg = new Logout();
break;
case 0x0a:
msg = new AttackRequest();
break;
case 0x0f:
msg = new RequestItemList();
break;
// case 0x10:
// // RequestEquipItem ... not used any more, instead "useItem"
// break;
case 0x11:
msg = new RequestUnEquipItem();
break;
case 0x12:
msg = new RequestDropItem();
break;
case 0x14:
msg = new UseItem();
break;
case 0x15:
msg = new TradeRequest();
break;
case 0x16:
msg = new AddTradeItem();
break;
case 0x17:
msg = new TradeDone();
break;
case 0x1a:
msg = new DummyPacket();
break;
case 0x1b:
msg = new RequestSocialAction();
break;
case 0x1c:
msg = new ChangeMoveType2();
break;
case 0x1d:
msg = new ChangeWaitType2();
break;
case 0x1e:
msg = new RequestSellItem();
break;
case 0x1f:
msg = new RequestBuyItem();
break;
case 0x20:
msg = new RequestLinkHtml();
break;
case 0x21:
msg = new RequestBypassToServer();
break;
case 0x22:
msg = new RequestBBSwrite();
break;
case 0x23:
msg = new DummyPacket();
break;
case 0x24:
msg = new RequestJoinPledge();
break;
case 0x25:
msg = new RequestAnswerJoinPledge();
break;
case 0x26:
msg = new RequestWithdrawalPledge();
break;
case 0x27:
msg = new RequestOustPledgeMember();
break;
// case 0x28:
// // RequestDismissPledge
// break;
case 0x29:
msg = new RequestJoinParty();
break;
case 0x2a:
msg = new RequestAnswerJoinParty();
break;
case 0x2b:
msg = new RequestWithDrawalParty();
break;
case 0x2c:
msg = new RequestOustPartyMember();
break;
case 0x2d:
// RequestDismissParty
break;
case 0x2e:
msg = new DummyPacket();
break;
case 0x2f:
msg = new RequestMagicSkillUse();
break;
case 0x30:
msg = new Appearing(); // (after death)
break;
case 0x31:
if(Config.ALLOW_WAREHOUSE)
msg = new SendWareHouseDepositList();
break;
case 0x32:
msg = new SendWareHouseWithDrawList();
break;
case 0x33:
msg = new RequestShortCutReg();
break;
case 0x34:
msg = new DummyPacket();
break;
case 0x35:
msg = new RequestShortCutDel();
break;
case 0x36:
msg = new CannotMoveAnymore();
break;
case 0x37:
msg = new RequestTargetCanceld();
break;
case 0x38:
msg = new Say2C();
break;
case 0x3c:
msg = new RequestPledgeMemberList();
break;
case 0x3e:
msg = new DummyPacket();
break;
case 0x3f:
msg = new RequestMagicSkillList();
break;
// case 0x41:
// // MoveWithDelta ... unused ?? or only on ship ??
// break;
case 0x42:
msg = new RequestGetOnVehicle();
break;
case 0x43:
msg = new RequestGetOffVehicle();
break;
case 0x44:
msg = new AnswerTradeRequest();
break;
case 0x45:
msg = new RequestActionUse();
break;
case 0x46:
msg = new RequestRestart();
break;
// case 0x47:
// // RequestSiegeInfo
// break;
case 0x48:
msg = new ValidatePosition();
break;
// case 0x49:
// // RequestSEKCustom
// break;
// THESE ARE NOW TEMPORARY DISABLED
case 0x4a:
new StartRotating();
break;
case 0x4b:
new FinishRotating();
break;
case 0x4d:
msg = new RequestStartPledgeWar();
break;
case 0x4e:
//msg = new RequestReplyStartPledgeWar();
break;
case 0x4f:
msg = new RequestStopPledgeWar();
break;
case 0x50:
//msg = new RequestReplyStopPledgeWar();
break;
case 0x51:
// msg = new RequestSurrenderPledgeWar();
break;
case 0x52:
/// msg = new RequestReplySurrenderPledgeWar();
break;
case 0x53:
msg = new RequestSetPledgeCrest();
break;
case 0x55:
msg = new RequestGiveNickName();
break;
case 0x57:
msg = new RequestShowBoard();
break;
case 0x58:
msg = new RequestEnchantItem();
break;
case 0x59:
msg = new RequestDestroyItem();
break;
case 0x5b:
msg = new SendBypassBuildCmd();
break;
case 0x5c:
msg = new RequestMoveToLocationInVehicle();
break;
case 0x5d:
msg = new CannotMoveAnymoreInVehicle();
break;
case 0x5e:
msg = new RequestFriendInvite();
break;
case 0x5f:
msg = new RequestFriendAddReply();
break;
case 0x60:
msg = new RequestFriendList();
break;
case 0x61:
msg = new RequestFriendDel();
break;
case 0x63:
msg = new RequestQuestList();
break;
case 0x64:
msg = new RequestQuestAbort();
break;
case 0x66:
msg = new RequestPledgeInfo();
break;
// case 0x67:
// // RequestPledgeExtendedInfo
// break;
case 0x68:
msg = new RequestPledgeCrest();
break;
case 0x69:
// msg = new RequestSurrenderPersonally();
break;
// case 0x6a:
// // Ride
// break;
case 0x6b: // send when talking to trainer npc, to show list of available skills
msg = new RequestAquireSkillInfo();// --> [s] 0xa4;
break;
case 0x6c: // send when a skill to be learned is selected
msg = new RequestAquireSkill();
break;
case 0x6d:
msg = new RequestRestartPoint();
break;
case 0x6e:
msg = new RequestGMCommand();
break;
case 0x6f:
msg = new RequestPartyMatchConfig();
break;
case 0x70:
msg = new RequestPartyMatchList();
break;
case 0x71:
msg = new RequestPartyMatchDetail();
break;
case 0x72:
msg = new RequestCrystallizeItem();
break;
case 0x73:
msg = new RequestPrivateStoreManageSell();
break;
case 0x74:
msg = new SetPrivateStoreList();
break;
// case 0x75:
// msg = new RequestPrivateStoreManageCancel(data, _client);
// break;
case 0x76:
msg = new RequestPrivateStoreQuitSell();
break;
case 0x77:
msg = new SetPrivateStoreMsgSell();
break;
// case 0x78:
// // RequestPrivateStoreList
// break;
case 0x79:
msg = new RequestPrivateStoreBuy();
break;
case 0x7a:
//ReviveReply
break;
case 0x7b:
msg = new RequestTutorialLinkHtml();
break;
case 0x7c:
msg = new RequestTutorialPassCmdToServer();
break;
case 0x7d:
msg = new RequestTutorialQuestionMark();
break;
case 0x7e:
msg = new RequestTutorialClientEvent();
break;
case 0x7f:
msg = new RequestPetition();
break;
case 0x80:
msg = new RequestPetitionCancel();
break;
case 0x81:
msg = new RequestGmList();
break;
case 0x82:
msg = new RequestJoinAlly();
break;
case 0x83:
msg = new RequestAnswerJoinAlly();
break;
case 0x84:
msg = new RequestWithdrawAlly();
break;
case 0x85:
msg = new RequestOustAlly();
break;
case 0x86:
msg = new RequestDismissAlly();
break;
case 0x87:
msg = new RequestSetAllyCrest();
break;
case 0x88:
msg = new RequestAllyCrest();
break;
case 0x89:
msg = new RequestChangePetName();
break;
case 0x8a:
msg = new RequestPetUseItem();
break;
case 0x8b:
msg = new RequestGiveItemToPet();
break;
case 0x8c:
msg = new RequestGetItemFromPet();
break;
case 0x8e:
msg = new RequestAllyInfo();
break;
case 0x8f:
msg = new RequestPetGetItem();
break;
case 0x90:
msg = new RequestPrivateStoreManageBuy();
break;
case 0x91:
msg = new SetPrivateStoreBuyList();
break;
// case 0x92:
// // RequestPrivateStoreBuyManageCancel
// break;
case 0x93:
msg = new RequestPrivateStoreQuitBuy();
break;
case 0x94:
msg = new SetPrivateStoreMsgBuy();
break;
// case 0x95:
// RequestPrivateStoreBuyList
// break;
case 0x96:
msg = new SendPrivateStoreBuyBuyList(); // ?
break;
// case 0x97:
// SendTimeCheckPacket
// break;
// case 0x98:
// // RequestStartAllianceWar
// break;
// case 0x99:
// // ReplyStartAllianceWar
// break;
// case 0x9a:
// // RequestStopAllianceWar
// break;
// case 0x9b:
// // ReplyStopAllianceWar
// break;
// case 0x9c:
// // RequestSurrenderAllianceWar
// break;
case 0x9d:
// RequestSkillCoolTime
/*if (Config.DEBUG)
_log.info("Request Skill Cool Time .. ignored");
msg = null;*/
break;
case 0x9e:
msg = new RequestPackageSendableItemList();
break;
case 0x9f:
msg = new RequestPackageSend();
break;
case 0xa0:
msg = new RequestBlock();
break;
// case 0xa1:
// // RequestCastleSiegeInfo
// break;
case 0xa2:
msg = new RequestSiegeAttackerList();
break;
case 0xa3:
msg = new RequestSiegeDefenderList();
break;
case 0xa4:
msg = new RequestJoinSiege();
break;
case 0xa5:
msg = new RequestConfirmSiegeWaitingList();
break;
// case 0xa6:
// // RequestSetCastleSiegeTime
// break;
case 0xa7:
msg = new RequestMultiSellChoose();
break;
// case 0xa8:
// // NetPing
// break;
case 0xaa:
msg = new BypassUserCmd();
break;
case 0xab:
msg = new SnoopQuit();
break;
case 0xac: // we still need this packet to handle BACK button of craft dialog
msg = new RequestRecipeBookOpen();
break;
case 0xad:
msg = new RequestRecipeItemDelete();
break;
case 0xae:
msg = new RequestRecipeItemMakeInfo();
break;
case 0xaf:
msg = new RequestRecipeItemMakeSelf();
break;
//case 0xb0:
// msg = new RequestRecipeShopManageList(data, client);
// break;
case 0xb1:
msg = new RequestRecipeShopMessageSet();
break;
case 0xb2:
msg = new RequestRecipeShopListSet();
break;
case 0xb3:
msg = new RequestRecipeShopManageQuit();
break;
case 0xb5:
msg = new RequestRecipeShopMakeInfo();
break;
case 0xb6:
msg = new RequestRecipeShopMakeDo();
break;
case 0xb7:
msg = new RequestRecipeShopMakeInfo();
break;
case 0xb8:
msg = new RequestObserverEnd();
break;
case 0xb9:
msg = new RequestEvaluate();
break;
case 0xba:
msg = new RequestHennaList();
break;
case 0xbb:
msg = new RequestHennaItemInfo();
break;
case 0xbc:
msg = new RequestHennaEquip();
break;
case 0xc0:
// Clan Privileges
msg = new RequestPledgePower();
break;
case 0xc1:
msg = new RequestMakeMacro();
break;
case 0xc2:
msg = new RequestDeleteMacro();
break;
// Manor
case 0xc3:
msg = new RequestProcureCropList();
break;
case 0xc4:
msg = new RequestBuySeed();
break;
case 0xc5:
msg = new ConfirmDlg();
break;
case 0xc6:
msg = new RequestPreviewItem();
break;
case 0xc7:
msg = new RequestSSQStatus();
break;
case 0xCA:
//msg = new GameGuardReply();
break;
case 0xcc:
msg = new RequestSendL2FriendSay();
break;
case 0xcd:
msg = new RequestShowMiniMap();
break;
case 0xce: // MSN dialogs so that you dont see them in the console.
break;
case 0xcf:
msg = new RequestReload(); // record video
break;
case 0xd0:
int id2 = -1;
if(buf.remaining() >= 2)
id2 = buf.getShort() & 0xffff;
else
{
_log.warning("Client: " + client.toString() + " sent a 0xd0 without the second opcode.");
break;
}
switch(id2)
{
case 1:
msg = new RequestOustFromPartyRoom();
break;
case 2:
msg = new RequestDismissPartyRoom();
break;
case 3:
msg = new RequestWithdrawPartyRoom();
break;
case 4:
msg = new RequestHandOverPartyMaster();
break;
case 5:
msg = new RequestAutoSoulShot();
break;
case 6:
msg = new RequestExEnchantSkillInfo();
break;
case 7:
msg = new RequestExEnchantSkill();
break;
case 8:
msg = new RequestManorList();
break;
case 9:
msg = new RequestProcureCropList();
break;
case 0x0a:
msg = new RequestSetSeed();
break;
case 0x0b:
msg = new RequestSetCrop();
break;
case 0x0c:
msg = new RequestWriteHeroWords();
break;
case 0x0d:
msg = new RequestExMPCCAskJoin();
break;
case 0x0e:
msg = new RequestExMPCCAcceptJoin();
break;
case 0x0f:
msg = new RequestExOustFromMPCC();
break;
case 0x10:
msg = new RequestPledgeCrestLarge();
break;
case 0x11:
msg = new RequestSetPledgeCrestLarge();
break;
case 0x12:
msg = new RequestOlympiadObserverEnd();
break;
case 0x13:
//msg = new RequestOlympiadMatchList();
break;
case 0x14:
msg = new RequestAskJoinPartyRoom();
break;
case 0x15:
msg = new AnswerJoinPartyRoom();
break;
case 0x16:
msg = new RequestListPartyMatchingWaitingRoom();
break;
case 0x17:
msg = new RequestExitPartyMatchingWaitingRoom();
break;
case 0x18:
msg = new RequestGetBossRecord();
break;
case 0x19:
msg = new RequestPledgeSetAcademyMaster();
break;
case 0x1a:
msg = new RequestPledgePowerGradeList();
break;
case 0x1b:
msg = new RequestPledgeMemberPowerInfo();
break;
case 0x1c:
msg = new RequestPledgeSetMemberPowerGrade();
break;
case 0x1d:
msg = new RequestPledgeMemberInfo();
break;
case 0x1e:
msg = new RequestPledgeWarList();
break;
case 0x1f:
msg = new RequestExFishRanking();
break;
case 0x20:
msg = new RequestPCCafeCouponUse();
break;
// couldnt find it 0x21 :S
case 0x22:
msg = new RequestCursedWeaponList();
break;
case 0x23:
msg = new RequestCursedWeaponLocation();
break;
case 0x24:
msg = new RequestPledgeReorganizeMember();
break;
// couldnt find it 0x25 :S
case 0x26:
msg = new RequestExMPCCShowPartyMembersInfo();
break;
case 0x27:
msg = new RequestDuelStart();
break;
case 0x28:
msg = new RequestDuelAnswerStart();
break;
case 0x29:
msg = new RequestConfirmTargetItem();
break;
case 0x2a:
msg = new RequestConfirmRefinerItem();
break;
case 0x2b:
msg = new RequestConfirmGemStone();
break;
case 0x2c:
msg = new RequestRefine();
break;
case 0x2d:
msg = new RequestConfirmCancelItem();
break;
case 0x2e:
msg = new RequestRefineCancel();
break;
case 0x2f:
msg = new RequestExMagicSkillUseGround();
break;
case 0x30:
msg = new RequestDuelSurrender(buf, client);
break;
default:
//printDebugDoubleOpcode(opcode, id2, buf, state, client);
break;
}
break;
/*case 0xee:
msg = new RequestChangePartyLeader(data, _client);
break;*/
default:
//printDebug(opcode, buf, state, client);
break;
}
break;
}
return msg;
}
// impl
@Override
public L2GameClient create(MMOConnection<L2GameClient> con)
{
return new L2GameClient(con);
}
@Override
public void execute(ReceivablePacket<L2GameClient> rp)
{
try
{
if(rp.getClient().getState() == IN_GAME)
ThreadPoolManager.getInstance().executePacket(rp);
else
ThreadPoolManager.getInstance().executeIOPacket(rp);
}
catch(RejectedExecutionException e)
{
// if the server is shutdown we ignore
if(!ThreadPoolManager.getInstance().isShutdown())
_log.severe("Failed executing: " + rp.getClass().getSimpleName() + " for Client: " + rp.getClient().toString());
}
}
public static String printData(byte[] data, int len)
{
StringBuffer result = new StringBuffer();
int counter = 0;
for(int i = 0; i < len; i++)
{
if(counter % 16 == 0)
result.append(fillHex(i, 4) + ": ");
result.append(fillHex(data[i] & 0xff, 2) + " ");
counter++;
if(counter == 16)
{
result.append(" ");
int charpoint = i - 15;
for(int a = 0; a < 16; a++)
{
int t1 = data[charpoint++];
if(t1 > 0x1f && t1 < 0x80)
result.append((char) t1);
else
result.append('.');
}
result.append("\n");
counter = 0;
}
}
int rest = data.length % 16;
if(rest > 0)
{
for(int i = 0; i < 17 - rest; i++)
result.append(" ");
int charpoint = data.length - rest;
for(int a = 0; a < rest; a++)
{
int t1 = data[charpoint++];
if(t1 > 0x1f && t1 < 0x80)
result.append((char) t1);
else
result.append('.');
}
result.append("\n");
}
return result.toString();
}
private static String fillHex(int data, int digits)
{
String number = Integer.toHexString(data);
for(int i = number.length(); i < digits; i++)
number = "0" + number;
return number;
}
public void handleIncompletePacket(L2GameClient client)
{
L2Player activeChar = client.getActiveChar();
if(activeChar == null)
_log.warning("Packet not completed. Maybe cheater. IP:" + client.getIpAddr() + ", account:" + client.getLoginName());
else
_log.warning("Packet not completed. Maybe cheater. IP:" + client.getIpAddr() + ", account:" + client.getLoginName() + ", character:" + activeChar.getName());
client.onClientPacketFail();
}
@SuppressWarnings("unchecked")
@Override
public HeaderInfo<L2GameClient> handleHeader(SelectionKey key, ByteBuffer buf)
{
if(buf.remaining() >= 2)
{
int dataPending = (buf.getShort() & 0xffff) - 2;
L2GameClient client = ((MMOConnection<L2GameClient>) key.attachment()).getClient();
return getHeaderInfoReturn().set(0, dataPending, false, client);
}
L2GameClient client = ((MMOConnection<L2GameClient>) key.attachment()).getClient();
return getHeaderInfoReturn().set(2 - buf.remaining(), 0, false, client);
}
}
| [
"[email protected]"
] | |
693e59de0f4ac7cc9decdccc9131309b251246d2 | 31922011f3f1b6a043b8c423bce097d93f05711c | /src/hao/test/fbapidemo/FacebookUtility.java | 9ed3954871257188a78560bb3750bb66e0c1a2ec | [] | no_license | sfavors3/FacebookAPIDemo | 5e601fb3580bf0ac268ae2554139d4c7a4075acd | 29a42fcfe168173500e6420d26597c0553b8dd22 | refs/heads/master | 2021-01-17T10:24:10.626973 | 2014-01-15T03:22:04 | 2014-01-15T03:22:04 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package hao.test.fbapidemo;
import android.content.SharedPreferences;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
public class FacebookUtility
{
public static Facebook fb = null;
public static AsyncFacebookRunner runner = null;
public static SharedPreferences prefs;
} | [
"[email protected]"
] | |
231d5b789b590a10152d94ccd7a13c538411c232 | 5e8eec6ed490c0c1d4711ce6a9158aec4d4719ee | /shopping/src/com/company/shopping/action/TestAction.java | 3123a6dca5d0d4c9695deabdf0de62a702685e6f | [] | no_license | PengLi1990/eclipse_backup | 11466fecd9c2af576354199736faeffc6915e056 | dab0f53d11a8296115190098245cddd384564384 | refs/heads/master | 2021-01-17T19:23:33.800457 | 2016-06-22T13:13:20 | 2016-06-22T13:13:20 | 57,083,724 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 493 | java | package com.company.shopping.action;
import java.io.PrintWriter;
import org.apache.struts2.ServletActionContext;
public class TestAction {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String execute() throws Exception{
PrintWriter out = ServletActionContext.getResponse().getWriter();
out.println("Hello,World");
return null;
}
}
| [
"[email protected]"
] | |
bb86d2e4a712fc7af4ffb5705b66e641273a5f13 | c7df5077b4966513e8280dbb6f00fabc730e9529 | /src/main/java/com/yin/pattern/prototype/v2/Test.java | fc1c623540d8ce79aba00eb256437a94de4f8041 | [] | no_license | guanqunyin/DesignPattern | c95726d5bf1ecad29761287cac1ee35ccaea4a88 | bde9b46b3d2ab1d9afac73ba8346e851fec2c6c9 | refs/heads/master | 2020-08-03T16:01:10.298983 | 2019-11-13T09:41:28 | 2019-11-13T09:41:28 | 211,808,025 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,439 | java | package com.yin.pattern.prototype.v2;
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Person person = new Person();
Person clone = (Person)person.clone();
System.out.println("age:" + clone.age +" score:"+ clone.score);
System.out.println(clone.location);
System.out.println(person.location==clone.location);
clone.location.roomStreet="test";
System.out.println(person.location);
}
}
class Person implements Cloneable {
int age = 8;
int score = 100;
Location location = new Location("bj", 22);
@Override
public Object clone() throws CloneNotSupportedException {
Person personClone = (Person)super.clone();
Location locClone = (Location)personClone.location.clone();
personClone.location = locClone;
return personClone;
}
}
class Location implements Cloneable{
String roomStreet;
int number;
public Location(String roomStreet, int number) {
this.roomStreet = roomStreet;
this.number = number;
}
@Override
public String toString() {
return "Location{" +
"roomStreet='" + roomStreet + '\'' +
", number=" + number +
'}';
}
//重写clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| [
"[email protected]"
] | |
9bc0a5f7f7dfd41488e9106039bf41ba0303e3fd | dafcdd6347a1be928df01b5a5bf47527f38d029f | /Sample4GoogleGCM/src/com/example/sample4googlegcm/GcmIntentService.java | 9079cd8035d02c398642f6209fc304fc2b010744 | [] | no_license | sunleesi/android-education-project | b62e63076619cb927490fe1585c6a7a0169c79a5 | 31c1e520275ba0445b3288e0626fe5717193bd7b | refs/heads/master | 2021-01-10T03:06:12.607555 | 2015-06-01T06:38:54 | 2015-06-01T06:38:54 | 36,643,841 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 3,204 | java | package com.example.sample4googlegcm;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
public class GcmIntentService extends IntentService {
private static final String TAG="GcmIntengService";
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
String time = intent.getStringExtra("time");
sendNotification("Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| [
"[email protected]"
] | |
8408800c83263b82bfbe0a5e3fed4a30f75a961b | 68edc10c26c008b348419f0997b768e8dd014827 | /module_2/src/bai1_introduction_to_java/thuc_hanh/KhaiBaoVaSuDungBien.java | f273fe2f4654658bd6b36cc2dbebfdba49cdf3f4 | [] | no_license | thanhhau052/C0221G1-DuongThanhHau | 4332a3f8db425dc56db96c74ed98afe9ce6de6d6 | 94379b8e44d757c2db5b79b30759a9db26e4fbcb | refs/heads/main | 2023-06-26T18:21:49.711919 | 2021-07-31T16:51:04 | 2021-07-31T16:51:04 | 342,121,420 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 524 | java | package bai1_introduction_to_java.thuc_hanh;
public class KhaiBaoVaSuDungBien {
public static void main(String[] args) {
int i = 10;
float f = 20.5f;
double d = 20.5;
boolean b = true;
char c = 'a';
String s = "Hà Nội";
System.out.println("i = " + i);
System.out.println("f = " + f);
System.out.println("d = " + d);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("s = " + s);
}
}
| [
"[email protected]"
] | |
6ccf60888ef24fc9e80b7a77484dd4fb583558c6 | b34d08d309984ddd1b7a0fba4c92f40d3d8f51fd | /src/sample/Controller/RequestFormController.java | f882b44adedec6347a1c1e04266a9b84ffa3d790 | [] | no_license | Lojini/JavaFX-Public-Transport-Ticketing-System | 75a43af897ce037147bd517853d3bb5d19811571 | ecf518092eb5452ad7a5e600fdff2c356d49f2b5 | refs/heads/master | 2022-11-13T01:34:01.883840 | 2020-07-01T06:12:49 | 2020-07-01T06:12:49 | 276,057,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 67 | java | package sample.Controller;
public class RequestFormController {
}
| [
"[email protected]"
] | |
fd64e40ded68834aa9f9689b63f6c5312d39d206 | e823bebfaf4d1ff71c674b7349258e4b43b9be5a | /BeTraffic/src/com/profete162/WebcamWallonnes/adapter/ImageMapReceivedCallback.java | d93c260b94714f9c90163a5d77aab384c7da726d | [] | no_license | KhalidElSayed/BeTraffic-Android-Client | f55599e846ef36fe454d1a1c4d92505b2122ac02 | ac3ba347bacca2a582a2919043a165fb759f1a5e | refs/heads/master | 2021-01-18T10:22:00.837445 | 2012-03-02T09:22:33 | 2012-03-02T09:22:33 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 259 | java | package com.profete162.WebcamWallonnes.adapter;
import com.profete162.WebcamWallonnes.CamerasActivity;
public interface ImageMapReceivedCallback
{
// Called when an image is rendered
public void onImageReceived(CamerasActivity.ImageDisplayer displayer);
} | [
"[email protected]"
] | |
0b055367cb11e8b5b7cc9af774ebea0dea72d5e3 | 743540992a26e435939620c6d8ea9260a52fd9e2 | /university-dal/src/main/java/com/pavel/university/entity/ObjectProfessor.java | d1b71f8ff749b7730de3badb0a906a6dec1bb2ae | [] | no_license | birladeanuPavel/University | e1886171b31f52f38262c6df46525a7713c8551a | dfadb43fdc7b217ec0ebb2b24a10b54612b4dcdc | refs/heads/master | 2016-09-06T21:28:08.250041 | 2014-05-04T14:51:37 | 2014-05-04T14:51:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,019 | java | package com.pavel.university.entity;
import javax.persistence.*;
import java.io.Serializable;
/**
* Created by Pavel on 28.04.2014.
*/
@Entity
@Table(name = "object_professor")
public class ObjectProfessor implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;
@ManyToOne
@JoinColumn(name = "id_object")
private Object object;
@ManyToOne
@JoinColumn(name = "id_professor")
private Professor professor;
public ObjectProfessor() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public Professor getProfessor() {
return professor;
}
public void setProfessor(Professor professor) {
this.professor = professor;
}
}
| [
"[email protected]"
] | |
2f456f12af6af30be9bf26cd3d77c7521aa216c8 | 7ddcb906c12f9b522326da141ca74bfb584ae423 | /src/main/java/com/smart/smartcontactmanager/com/smart/smartcontactmanager/config/CustomUserDetails.java | 35558e0855a52d97f9e0b5f9fb734aa0aa036c5f | [] | no_license | abhinav-repository-007/ContactManager | e5b7ddf510340df849b14732da4118c80190583e | ea6c7b7a1c23086db831db3038a33f42a9eac3f1 | refs/heads/master | 2023-03-31T07:20:51.340106 | 2021-04-09T04:37:44 | 2021-04-09T04:37:44 | 347,838,252 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,345 | java | package com.smart.smartcontactmanager.com.smart.smartcontactmanager.config;
import com.smart.smartcontactmanager.com.smart.smartcontactmanager.entities.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class CustomUserDetails implements UserDetails {
private User user;
public CustomUserDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority= new SimpleGrantedAuthority(user.getRole());
return List.of(simpleGrantedAuthority);
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getEmail();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| [
"[email protected]"
] | |
039a105b7ca1ad0ef06e5ba7c0967502e40c21da | f8358e34a8151d377f7ad476d50bb9c840fd7afd | /ImageHoster/src/main/java/ImageHoster/controller/ImageController.java | 957a441e4c80f5ef5abc5340c17d6b03868331fd | [] | no_license | deepanshu-g/imagehosterproject | 23a6cf8003cd86de277be868b2dc671e3bc3d9c5 | 998dc3fcc794793bfdceaeba7198127ca1a1f159 | refs/heads/master | 2020-04-13T01:36:38.152773 | 2018-12-23T17:49:47 | 2018-12-23T17:49:47 | 162,878,937 | 2 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,380 | java | package ImageHoster.controller;
import ImageHoster.model.Comment;
import ImageHoster.model.Image;
import ImageHoster.model.Tag;
import ImageHoster.model.User;
import ImageHoster.service.CommentService;
import ImageHoster.service.ImageService;
import ImageHoster.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
@Controller
public class ImageController {
@Autowired
private ImageService imageService;
@Autowired
private TagService tagService;
@Autowired
private CommentService commentService;
//This method displays all the images in the user home page after successful login
@RequestMapping("images")
public String getUserImages(Model model) {
List<Image> images = imageService.getAllImages();
model.addAttribute("images", images);
return "images";
}
//This method is called when the details of the specific image with corresponding title are to be displayed
//The logic is to get the image from the databse with corresponding title. After getting the image from the database the details are shown
//First receive the dynamic parameter in the incoming request URL in a string variable 'title' and also the Model type object
//Call the getImageByTitle() method in the business logic to fetch all the details of that image
//Add the image in the Model type object with 'image' as the key
//Return 'images/image.html' file
//Also now you need to add the tags of an image in the Model type object
//Here a list of tags is added in the Model type object
//this list is then sent to 'images/image.html' file and the tags are displayed
@RequestMapping("/images/{id}/{title}")
public String showImage(@PathVariable("title") String title, @PathVariable("id") Integer id, Model model) {
Image image = imageService.getImageByTitle(title ,id);
model.addAttribute("comments",image.getComment());
model.addAttribute("image", image);
model.addAttribute("tags", image.getTags());
return "images/image";
}
//This controller method is called when the request pattern is of type 'images/upload'
//The method returns 'images/upload.html' file
@RequestMapping("/images/upload")
public String newImage() {
return "images/upload";
}
//This controller method is called when the request pattern is of type 'images/upload' and also the incoming request is of POST type
//The method receives all the details of the image to be stored in the database, and now the image will be sent to the business logic to be persisted in the database
//After you get the imageFile, set the user of the image by getting the logged in user from the Http Session
//Convert the image to Base64 format and store it as a string in the 'imageFile' attribute
//Set the date on which the image is posted
//After storing the image, this method directs to the logged in user homepage displaying all the images
//Get the 'tags' request parameter using @RequestParam annotation which is just a string of all the tags
//Store all the tags in the database and make a list of all the tags using the findOrCreateTags() method
//set the tags attribute of the image as a list of all the tags returned by the findOrCreateTags() method
@RequestMapping(value = "/images/upload", method = RequestMethod.POST)
public String createImage(@RequestParam("file") MultipartFile file, @RequestParam("tags") String tags, Image newImage, HttpSession session) throws IOException {
User user = (User) session.getAttribute("loggeduser");
newImage.setUser(user);
String uploadedImageData = convertUploadedFileToBase64(file);
newImage.setImageFile(uploadedImageData);
List<Tag> imageTags = findOrCreateTags(tags);
newImage.setTags(imageTags);
newImage.setDate(new Date());
imageService.uploadImage(newImage);
return "redirect:/images";
}
//This controller method is called when the request pattern is of type 'editImage'
//This method fetches the image with the corresponding id from the database and adds it to the model with the key as 'image'
//The method then returns 'images/edit.html' file wherein you fill all the updated details of the image
//The method first needs to convert the list of all the tags to a string containing all the tags separated by a comma and then add this string in a Model type object
//This string is then displayed by 'edit.html' file as previous tags of an image
@RequestMapping(value = "/editImage")
public String editImage(@RequestParam("imageId") Integer imageId,@RequestParam("title") String title,@RequestParam("userId") Integer userId ,HttpSession session ,Model model) {
//title and userid is fetched with the help of requestparameter
//here we are creating the logged in user object with the help of session
//finally the view is returned on the basis of logged in user and image owner(userId)
User loggeduser = (User) session.getAttribute("loggeduser");
if(userId != loggeduser.getId()){
Image image = imageService.getImageByTitle(title ,imageId);
model.addAttribute("editError", true);
model.addAttribute("image", image);
model.addAttribute("tags", image.getTags());
return "images/image";
}
else {
Image image = imageService.getImage(imageId);
String tags = convertTagsToString(image.getTags());
model.addAttribute("image", image);
model.addAttribute("tags", tags);
return "images/edit";
}
}
//This controller method is called when the request pattern is of type 'images/edit' and also the incoming request is of PUT type
//The method receives the imageFile, imageId, updated image, along with the Http Session
//The method adds the new imageFile to the updated image if user updates the imageFile and adds the previous imageFile to the new updated image if user does not choose to update the imageFile
//Set an id of the new updated image
//Set the user using Http Session
//Set the date on which the image is posted
//Call the updateImage() method in the business logic to update the image
//Direct to the same page showing the details of that particular updated image
//The method also receives tags parameter which is a string of all the tags separated by a comma using the annotation @RequestParam
//The method converts the string to a list of all the tags using findOrCreateTags() method and sets the tags attribute of an image as a list of all the tags
@RequestMapping(value = "/editImage", method = RequestMethod.PUT)
public String editImageSubmit(@RequestParam("file") MultipartFile file, @RequestParam("imageId") Integer imageId, @RequestParam("tags") String tags, Image updatedImage, HttpSession session) throws IOException {
Image image = imageService.getImage(imageId);
String updatedImageData = convertUploadedFileToBase64(file);
List<Tag> imageTags = findOrCreateTags(tags);
if (updatedImageData.isEmpty())
updatedImage.setImageFile(image.getImageFile());
else {
updatedImage.setImageFile(updatedImageData);
}
updatedImage.setId(imageId);
User user = (User) session.getAttribute("loggeduser");
updatedImage.setUser(user);
updatedImage.setTags(imageTags);
updatedImage.setDate(new Date());
imageService.updateImage(updatedImage);
return "redirect:/images/" + imageId + "/"+ updatedImage.getTitle();
}
//This controller method is called when the request pattern is of type 'deleteImage' and also the incoming request is of DELETE type
//The method calls the deleteImage() method in the business logic passing the id of the image to be deleted
//Looks for a controller method with request mapping of type '/images'
@RequestMapping(value = "/deleteImage", method = RequestMethod.DELETE)
public String deleteImageSubmit(@RequestParam(name = "imageId") Integer imageId,@RequestParam("title") String title,@RequestParam("userId") Integer userId ,HttpSession session ,Model model) {
//getting the logged user with the help of session
User loggeduser = (User) session.getAttribute("loggeduser");
//deleting the post if the user belongs to the owner of the image
if(userId != loggeduser.getId()){
Image image = imageService.getImageByTitle(title ,imageId);
model.addAttribute("deleteError", true);
model.addAttribute("image", image);
model.addAttribute("tags", image.getTags());
return "images/image";
}
else {
imageService.deleteImage(imageId);
return "redirect:/images";
}
}
//This method converts the image to Base64 format
private String convertUploadedFileToBase64(MultipartFile file) throws IOException {
return Base64.getEncoder().encodeToString(file.getBytes());
}
//findOrCreateTags() method has been implemented, which returns the list of tags after converting the ‘tags’ string to a list of all the tags and also stores the tags in the database if they do not exist in the database. Observe the method and complete the code where required for this method.
//Try to get the tag from the database using getTagByName() method. If tag is returned, you need not to store that tag in the database, and if null is returned, you need to first store that tag in the database and then the tag is added to a list
//After adding all tags to a list, the list is returned
private List<Tag> findOrCreateTags(String tagNames) {
StringTokenizer st = new StringTokenizer(tagNames, ",");
List<Tag> tags = new ArrayList<Tag>();
while (st.hasMoreTokens()) {
String tagName = st.nextToken().trim();
Tag tag = tagService.getTagByName(tagName);
if (tag == null) {
Tag newTag = new Tag(tagName);
tag = tagService.createTag(newTag);
}
tags.add(tag);
}
return tags;
}
//The method receives the list of all tags
//Converts the list of all tags to a single string containing all the tags separated by a comma
//Returns the string
private String convertTagsToString(List<Tag> tags) {
StringBuilder tagString = new StringBuilder();
for (int i = 0; i <= tags.size() - 2; i++) {
tagString.append(tags.get(i).getName()).append(",");
}
Tag lastTag = tags.get(tags.size() - 1);
tagString.append(lastTag.getName());
return tagString.toString();
}
}
| [
"[email protected]"
] | |
5d42566261e11f93d3f94bdbbfd926cf1a740c7e | bd5081e8f7d3d028f0c04ee6c0210b77b61532c6 | /src/test/java/AOPTest.java | 85dc045f03def5101854a4203a6b22f30c3ce382 | [] | no_license | LOLtoulan/spring_annoaop | ffa5fa7f10d05c1e064ade9d0add9835c1d44257 | 364be275c59cc01b7d15070dfebc137971569f29 | refs/heads/master | 2021-01-03T17:41:05.811872 | 2020-02-13T04:07:56 | 2020-02-13T04:07:56 | 240,173,737 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 697 | java | import com.toulan.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @Author LOL_toulan
* @Time 2020/2/12 19:29
* @Message
*/
public class AOPTest {
public static void main(String[] args) {
//获取容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//获取容器中对象
AccountService as = (AccountService) ac.getBean("accountService");
//执行方法
as.saveAccount();
System.out.println();
// as.updateAccount(5);
System.out.println();
// as.deleteAccount();
}
}
| [
"[email protected]"
] | |
5aec546b13cbcf2b56d8c71d810a316c8c4f67b0 | 0e06e096a9f95ab094b8078ea2cd310759af008b | /sources/com/vungle/warren/network/APKDirectDownloader.java | a2de418d9e24bcb54c7f3923d09fd55e4e4b66cb | [] | no_license | Manifold0/adcom_decompile | 4bc2907a057c73703cf141dc0749ed4c014ebe55 | fce3d59b59480abe91f90ba05b0df4eaadd849f7 | refs/heads/master | 2020-05-21T02:01:59.787840 | 2019-05-10T00:36:27 | 2019-05-10T00:36:27 | 185,856,424 | 1 | 2 | null | 2019-05-10T00:36:28 | 2019-05-09T19:04:28 | Java | UTF-8 | Java | false | false | 966 | java | package com.vungle.warren.network;
import android.content.Context;
import com.tonyodev.fetch.Fetch.Settings;
import java.util.Map.Entry;
public class APKDirectDownloader extends FetchDownloader {
public APKDirectDownloader(Context context) {
super(context);
new Settings(context).setConcurrentDownloadsLimit(5).enableLogging(true).apply();
}
public void pause() {
if (this.operations != null) {
for (Entry entry : this.operations.entrySet()) {
this.fetch.pause(((Long) entry.getKey()).longValue());
}
}
}
public void resume() {
if (this.operations != null) {
for (Entry entry : this.operations.entrySet()) {
this.fetch.resume(((Long) entry.getKey()).longValue());
}
}
}
public boolean isDownloadTaskRunning() {
return (this.operations == null || this.operations.isEmpty()) ? false : true;
}
}
| [
"[email protected]"
] | |
066244c1b75c9eaa25de6e41812cbf5b99870916 | 814ccf2b4b70136e995648aaae9593ed163f6fa6 | /OllysEnhancedList/src/main/java/com/polydelic/oliverdixon/ollysenhancedlist/src/ListModels/ListItemPaginationSpinner.java | 873d2f630ed137ea9e8c3956af74b1450bd314a6 | [] | no_license | ollyde/enhanced-recycle-list-android | 315df7a5e316b92bbfefbe5e961e16caab573b28 | 171d47e39417441c768824f1c93c157cde02d72d | refs/heads/master | 2023-02-20T03:38:27.426287 | 2017-09-25T12:37:55 | 2017-09-25T12:37:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 847 | java | package com.polydelic.oliverdixon.ollysenhancedlist.src.ListModels;
import com.polydelic.oliverdixon.ollysenhancedlist.R;
import com.polydelic.oliverdixon.ollysenhancedlist.src.IListModel;
import com.polydelic.oliverdixon.ollysenhancedlist.src.BaseViewHolder;
public class ListItemPaginationSpinner extends ListModelTemporary implements IListModel {
@Override
public int getViewLayoutId() {
if (getCustomLayout() != null) {
return getCustomLayout();
}
return R.layout.list_item_pagination;
}
@Override
public Class getViewClass() {
return BaseView.class;
}
/**
* BaseView for this list item.
*/
public static class BaseView extends BaseViewHolder {
public BaseView(android.view.View createdView) {
super(createdView);
}
}
}
| [
"[email protected]"
] | |
4fc5cf2a1f44846186a819aa1cceb1e9439e2bfc | 1d35f3630148deb0e22ccedb15980ba004023549 | /qrcode/src/main/java/com/aisino/qrcode/activity/CaptureActivity.java | c9ee8de9e24f98a956d837827466b743bd327eca | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | wwan12/SimpleExample_v1 | 95aa6f912911754d3edc19d8ac1a613e982a0fad | 8b6675c8ab9d251086429a038d100a8c9d9098b2 | refs/heads/master | 2023-08-13T22:17:36.922406 | 2023-06-25T09:14:57 | 2023-06-25T09:14:57 | 174,499,736 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,916 | java | /*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.aisino.qrcode.activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.aisino.qrcode.R;
import com.aisino.qrcode.camera.CameraManager;
import com.aisino.qrcode.decode.DecodeThread;
import com.aisino.qrcode.utils.BeepManager;
import com.aisino.qrcode.utils.CaptureActivityHandler;
import com.aisino.qrcode.utils.InactivityTimer;
import com.google.zxing.Result;
import java.io.IOException;
import java.lang.reflect.Field;
/**
* This activity opens the camera and does the actual scanning on a background
* thread. It draws a viewfinder to help the user place the barcode correctly,
* shows feedback as the image processing is happening, and then overlays the
* results when a scan is successful.
*
* @author [email protected] (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private SurfaceView scanPreview = null;
private RelativeLayout scanContainer;
private RelativeLayout scanCropView;
private ImageView scanLine;
private Rect mCropRect = null;
private boolean isHasSurface = false;
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_capture);
scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
scanLine = (ImageView) findViewById(R.id.capture_scan_line);
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation
.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT,
0.9f);
animation.setDuration(4500);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.RESTART);
scanLine.startAnimation(animation);
}
@Override
protected void onResume() {
super.onResume();
cameraManager = new CameraManager(getApplication());
handler = null;
if (isHasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(scanPreview.getHolder());
} else {
// Install the callback and wait for surfaceCreated() to init the
// camera.
scanPreview.getHolder().addCallback(this);
}
inactivityTimer.onResume();
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
beepManager.close();
cameraManager.closeDriver();
if (!isHasSurface) {
scanPreview.getHolder().removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* @param rawResult The contents of the barcode.
* @param bundle The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
inactivityTimer.onActivity();
beepManager.playBeepSoundAndVibrate();
Intent resultIntent = new Intent();
bundle.putInt("width", mCropRect.width());
bundle.putInt("height", mCropRect.height());
bundle.putString("result", rawResult.getText());
resultIntent.putExtras(bundle);
this.setResult(RESULT_OK, resultIntent);
CaptureActivity.this.finish();
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE);
}
initCrop();
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
// camera error
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("");
builder.setMessage("相机发生错误");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
}
public Rect getCropRect() {
return mCropRect;
}
/**
* 初始化截取的矩形区域
*/
private void initCrop() {
int cameraWidth = cameraManager.getCameraResolution().y;
int cameraHeight = cameraManager.getCameraResolution().x;
/** 获取布局中扫描框的位置信息 */
int[] location = new int[2];
scanCropView.getLocationInWindow(location);
int cropLeft = location[0];
int cropTop = location[1] - getStatusBarHeight();
int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight();
/** 获取布局容器的宽高 */
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight();
/** 计算最终截取的矩形的左上角顶点x坐标 */
int x = cropLeft * cameraWidth / containerWidth;
/** 计算最终截取的矩形的左上角顶点y坐标 */
int y = cropTop * cameraHeight / containerHeight;
/** 计算最终截取的矩形的宽度 */
int width = cropWidth * cameraWidth / containerWidth;
/** 计算最终截取的矩形的高度 */
int height = cropHeight * cameraHeight / containerHeight;
/** 生成最终的截取的矩形 */
mCropRect = new Rect(x, y, width + x, height + y);
}
private int getStatusBarHeight() {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
} | [
"[email protected]"
] | |
3adf71aacaf51b142143a12bfff59de1ccd09502 | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/29/29_e2bc2614fabc2bdee8f52d764f84f474b859ea84/RedisAsyncConnection/29_e2bc2614fabc2bdee8f52d764f84f474b859ea84_RedisAsyncConnection_t.java | 7b75f962c0008516a76bb4e6b7d0288e7ee9aa3a | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 44,772 | java | // Copyright (C) 2011 - Will Glozer. All rights reserved.
package com.lambdaworks.redis;
import com.lambdaworks.codec.Base16;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.output.*;
import com.lambdaworks.redis.protocol.*;
import org.jboss.netty.channel.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.*;
import static com.lambdaworks.redis.protocol.CommandKeyword.*;
import static com.lambdaworks.redis.protocol.CommandType.*;
/**
* An asynchronous thread-safe connection to a redis server. Multiple threads may
* share one {@link RedisAsyncConnection} provided they avoid blocking and transactional
* operations such as {@link #blpop} and {@link #multi()}/{@link #exec}.
*
* A {@link ConnectionWatchdog} monitors each connection and reconnects
* automatically until {@link #close} is called. All pending commands will be
* (re)sent after successful reconnection.
*
* @author Will Glozer
*/
public class RedisAsyncConnection<K, V> extends SimpleChannelUpstreamHandler {
protected BlockingQueue<Command<K, V, ?>> queue;
protected RedisCodec<K, V> codec;
protected Channel channel;
protected long timeout;
protected TimeUnit unit;
protected MultiOutput<K, V> multi;
private String password;
private int db;
private boolean closed;
/**
* Initialize a new connection.
*
* @param queue Command queue.
* @param codec Codec used to encode/decode keys and values.
* @param timeout Maximum time to wait for a response.
* @param unit Unit of time for the timeout.
*/
public RedisAsyncConnection(BlockingQueue<Command<K, V, ?>> queue, RedisCodec<K, V> codec, long timeout, TimeUnit unit) {
this.queue = queue;
this.codec = codec;
this.timeout = timeout;
this.unit = unit;
}
/**
* Set the command timeout for this connection.
*
* @param timeout Command timeout.
* @param unit Unit of time for the timeout.
*/
public void setTimeout(long timeout, TimeUnit unit) {
this.timeout = timeout;
this.unit = unit;
}
public Future<Long> append(K key, V value) {
return dispatch(APPEND, new IntegerOutput<K, V>(codec), key, value);
}
public String auth(String password) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(password);
Command<K, V, String> cmd = dispatch(AUTH, new StatusOutput<K, V>(codec), args);
String status = await(cmd, timeout, unit);
if ("OK".equals(status)) this.password = password;
return status;
}
public Future<String> bgrewriteaof() {
return dispatch(BGREWRITEAOF, new StatusOutput<K, V>(codec));
}
public Future<String> bgsave() {
return dispatch(BGSAVE, new StatusOutput<K, V>(codec));
}
public Future<Long> bitcount(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(BITCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitcount(K key, long start, long end) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(end);
return dispatch(BITCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopAnd(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(AND).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopNot(K destination, K source) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(NOT).addKey(destination).addKey(source);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopOr(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(OR).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> bitopXor(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(XOR).addKey(destination).addKeys(keys);
return dispatch(BITOP, new IntegerOutput<K, V>(codec), args);
}
public Future<KeyValue<K, V>> blpop(long timeout, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys).add(timeout);
return dispatch(BLPOP, new KeyValueOutput<K, V>(codec), args);
}
public Future<KeyValue<K, V>> brpop(long timeout, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys).add(timeout);
return dispatch(BRPOP, new KeyValueOutput<K, V>(codec), args);
}
public Future<V> brpoplpush(long timeout, K source, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(source).addKey(destination).add(timeout);
return dispatch(BRPOPLPUSH, new ValueOutput<K, V>(codec), args);
}
public Future<K> clientGetname() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GETNAME);
return dispatch(CLIENT, new KeyOutput<K, V>(codec), args);
}
public Future<String> clientSetname(K name) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(SETNAME).addKey(name);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<String> clientKill(String addr) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(KILL).add(addr);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<String> clientList() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LIST);
return dispatch(CLIENT, new StatusOutput<K, V>(codec), args);
}
public Future<List<String>> configGet(String parameter) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET).add(parameter);
return dispatch(CONFIG, new StringListOutput<K, V>(codec), args);
}
public Future<String> configResetstat() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(RESETSTAT);
return dispatch(CONFIG, new StatusOutput<K, V>(codec), args);
}
public Future<String> configSet(String parameter, String value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(SET).add(parameter).add(value);
return dispatch(CONFIG, new StatusOutput<K, V>(codec), args);
}
public Future<Long> dbsize() {
return dispatch(DBSIZE, new IntegerOutput<K, V>(codec));
}
public Future<String> debugObject(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(OBJECT).addKey(key);
return dispatch(DEBUG, new StatusOutput<K, V>(codec), args);
}
public Future<Long> decr(K key) {
return dispatch(DECR, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> decrby(K key, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(DECRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> del(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(DEL, new IntegerOutput<K, V>(codec), args);
}
public Future<String> discard() {
multi = null;
return dispatch(DISCARD, new StatusOutput<K, V>(codec));
}
public Future<byte[]> dump(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(DUMP, new ByteArrayOutput<K, V>(codec), args);
}
public Future<V> echo(V msg) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addValue(msg);
return dispatch(ECHO, new ValueOutput<K, V>(codec), args);
}
public <T> Future<T> eval(V script, ScriptOutputType type, K[] keys, V... values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addValue(script).add(keys.length).addKeys(keys).addValues(values);
CommandOutput<K, V, T> output = newScriptOutput(codec, type);
return dispatch(EVAL, output, args);
}
public <T> Future<T> evalsha(String digest, ScriptOutputType type, K[] keys, V... values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(digest).add(keys.length).addKeys(keys).addValues(values);
CommandOutput<K, V, T> output = newScriptOutput(codec, type);
return dispatch(EVALSHA, output, args);
}
public Future<Boolean> exists(K key) {
return dispatch(EXISTS, new BooleanOutput<K, V>(codec), key);
}
public Future<Boolean> expire(K key, long seconds) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(seconds);
return dispatch(EXPIRE, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> expireat(K key, Date timestamp) {
return expireat(key, timestamp.getTime() / 1000);
}
public Future<Boolean> expireat(K key, long timestamp) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(timestamp);
return dispatch(EXPIREAT, new BooleanOutput<K, V>(codec), args);
}
public Future<List<Object>> exec() {
MultiOutput<K, V> multi = this.multi;
this.multi = null;
if (multi == null) multi = new MultiOutput<K, V>(codec);
return dispatch(EXEC, multi);
}
public Future<String> flushall() throws Exception {
return dispatch(FLUSHALL, new StatusOutput<K, V>(codec));
}
public Future<String> flushdb() throws Exception {
return dispatch(FLUSHDB, new StatusOutput<K, V>(codec));
}
public Future<V> get(K key) {
return dispatch(GET, new ValueOutput<K, V>(codec), key);
}
public Future<Long> getbit(K key, long offset) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset);
return dispatch(GETBIT, new IntegerOutput<K, V>(codec), args);
}
public Future<V> getrange(K key, long start, long end) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(end);
return dispatch(GETRANGE, new ValueOutput<K, V>(codec), args);
}
public Future<V> getset(K key, V value) {
return dispatch(GETSET, new ValueOutput<K, V>(codec), key, value);
}
public Future<Long> hdel(K key, K... fields) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKeys(fields);
return dispatch(HDEL, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> hexists(K key, K field) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field);
return dispatch(HEXISTS, new BooleanOutput<K, V>(codec), args);
}
public Future<V> hget(K key, K field) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field);
return dispatch(HGET, new ValueOutput<K, V>(codec), args);
}
public Future<Long> hincrby(K key, K field, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).add(amount);
return dispatch(HINCRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> hincrbyfloat(K key, K field, double amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).add(amount);
return dispatch(HINCRBYFLOAT, new DoubleOutput<K, V>(codec), args);
}
public Future<Map<K, V>> hgetall(K key) {
return dispatch(HGETALL, new MapOutput<K, V>(codec), key);
}
public Future<List<K>> hkeys(K key) {
return dispatch(HKEYS, new KeyListOutput<K, V>(codec), key);
}
public Future<Long> hlen(K key) {
return dispatch(HLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<List<V>> hmget(K key, K... fields) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKeys(fields);
return dispatch(HMGET, new ValueListOutput<K, V>(codec), args);
}
public Future<String> hmset(K key, Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(map);
return dispatch(HMSET, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> hset(K key, K field, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).addValue(value);
return dispatch(HSET, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> hsetnx(K key, K field, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(field).addValue(value);
return dispatch(HSETNX, new BooleanOutput<K, V>(codec), args);
}
public Future<List<V>> hvals(K key) {
return dispatch(HVALS, new ValueListOutput<K, V>(codec), key);
}
public Future<Long> incr(K key) {
return dispatch(INCR, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> incrby(K key, long amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(INCRBY, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> incrbyfloat(K key, double amount) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount);
return dispatch(INCRBYFLOAT, new DoubleOutput<K, V>(codec), args);
}
public Future<String> info() {
return dispatch(INFO, new StatusOutput<K, V>(codec));
}
public Future<String> info(String section) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(section);
return dispatch(INFO, new StatusOutput<K, V>(codec), args);
}
public Future<List<K>> keys(K pattern) {
return dispatch(KEYS, new KeyListOutput<K, V>(codec), pattern);
}
public Future<Date> lastsave() {
return dispatch(LASTSAVE, new DateOutput<K, V>(codec));
}
public Future<V> lindex(K key, long index) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(index);
return dispatch(LINDEX, new ValueOutput<K, V>(codec), args);
}
public Future<Long> linsert(K key, boolean before, V pivot, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(before ? BEFORE : AFTER).addValue(pivot).addValue(value);
return dispatch(LINSERT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> llen(K key) {
return dispatch(LLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<V> lpop(K key) {
return dispatch(LPOP, new ValueOutput<K, V>(codec), key);
}
public Future<Long> lpush(K key, V... values) {
return dispatch(LPUSH, new IntegerOutput<K, V>(codec), key, values);
}
public Future<Long> lpushx(K key, V value) {
return dispatch(LPUSHX, new IntegerOutput<K, V>(codec), key, value);
}
public Future<List<V>> lrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(LRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<Long> lrem(K key, long count, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(count).addValue(value);
return dispatch(LREM, new IntegerOutput<K, V>(codec), args);
}
public Future<String> lset(K key, long index, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(index).addValue(value);
return dispatch(LSET, new StatusOutput<K, V>(codec), args);
}
public Future<String> ltrim(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(LTRIM, new StatusOutput<K, V>(codec), args);
}
public Future<String> migrate(String host, int port, K key, int db, long timeout) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.add(host).add(port).addKey(key).add(db).add(timeout);
return dispatch(MIGRATE, new StatusOutput<K, V>(codec), args);
}
public Future<List<V>> mget(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(MGET, new ValueListOutput<K, V>(codec), args);
}
public Future<Boolean> move(K key, int db) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(db);
return dispatch(MOVE, new BooleanOutput<K, V>(codec), args);
}
public Future<String> multi() {
Command<K, V, String> cmd = dispatch(MULTI, new StatusOutput<K, V>(codec));
multi = (multi == null ? new MultiOutput<K, V>(codec) : multi);
return cmd;
}
public Future<String> mset(Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(map);
return dispatch(MSET, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> msetnx(Map<K, V> map) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(map);
return dispatch(MSETNX, new BooleanOutput<K, V>(codec), args);
}
public Future<String> objectEncoding(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(ENCODING).addKey(key);
return dispatch(OBJECT, new StatusOutput<K, V>(codec), args);
}
public Future<Long> objectIdletime(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(IDLETIME).addKey(key);
return dispatch(OBJECT, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> objectRefcount(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(REFCOUNT).addKey(key);
return dispatch(OBJECT, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> persist(K key) {
return dispatch(PERSIST, new BooleanOutput<K, V>(codec), key);
}
public Future<Boolean> pexpire(K key, long milliseconds) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(milliseconds);
return dispatch(PEXPIRE, new BooleanOutput<K, V>(codec), args);
}
public Future<Boolean> pexpireat(K key, Date timestamp) {
return pexpireat(key, timestamp.getTime());
}
public Future<Boolean> pexpireat(K key, long timestamp) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(timestamp);
return dispatch(PEXPIREAT, new BooleanOutput<K, V>(codec), args);
}
public Future<String> ping() {
return dispatch(PING, new StatusOutput<K, V>(codec));
}
public Future<Long> pttl(K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(PTTL, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> publish(K channel, V message) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(channel).addValue(message);
return dispatch(PUBLISH, new IntegerOutput<K, V>(codec), args);
}
public Future<String> quit() {
return dispatch(QUIT, new StatusOutput<K, V>(codec));
}
public Future<V> randomkey() {
return dispatch(RANDOMKEY, new ValueOutput<K, V>(codec));
}
public Future<String> rename(K key, K newKey) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(newKey);
return dispatch(RENAME, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> renamenx(K key, K newKey) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addKey(newKey);
return dispatch(RENAMENX, new BooleanOutput<K, V>(codec), args);
}
public Future<String> restore(K key, long ttl, byte[] value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(ttl).add(value);
return dispatch(RESTORE, new StatusOutput<K, V>(codec), args);
}
public Future<V> rpop(K key) {
return dispatch(RPOP, new ValueOutput<K, V>(codec), key);
}
public Future<V> rpoplpush(K source, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(source).addKey(destination);
return dispatch(RPOPLPUSH, new ValueOutput<K, V>(codec), args);
}
public Future<Long> rpush(K key, V... values) {
return dispatch(RPUSH, new IntegerOutput<K, V>(codec), key, values);
}
public Future<Long> rpushx(K key, V value) {
return dispatch(RPUSHX, new IntegerOutput<K, V>(codec), key, value);
}
public Future<Long> sadd(K key, V... members) {
return dispatch(SADD, new IntegerOutput<K, V>(codec), key, members);
}
public Future<String> save() {
return dispatch(SAVE, new StatusOutput<K, V>(codec));
}
public Future<Long> scard(K key) {
return dispatch(SCARD, new IntegerOutput<K, V>(codec), key);
}
public Future<List<Boolean>> scriptExists(String... digests) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(EXISTS);
for (String sha : digests) args.add(sha);
return dispatch(SCRIPT, new BooleanListOutput<K, V>(codec), args);
}
public Future<String> scriptFlush() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(FLUSH);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<String> scriptKill() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(KILL);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<String> scriptLoad(V script) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LOAD).addValue(script);
return dispatch(SCRIPT, new StatusOutput<K, V>(codec), args);
}
public Future<Set<V>> sdiff(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SDIFF, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sdiffstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SDIFFSTORE, new IntegerOutput<K, V>(codec), args);
}
public String select(int db) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(db);
Command<K, V, String> cmd = dispatch(SELECT, new StatusOutput<K, V>(codec), args);
String status = await(cmd, timeout, unit);
if ("OK".equals(status)) this.db = db;
return status;
}
public Future<String> set(K key, V value) {
return dispatch(SET, new StatusOutput<K, V>(codec), key, value);
}
public Future<Long> setbit(K key, long offset, int value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset).add(value);
return dispatch(SETBIT, new IntegerOutput<K, V>(codec), args);
}
public Future<String> setex(K key, long seconds, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(seconds).addValue(value);
return dispatch(SETEX, new StatusOutput<K, V>(codec), args);
}
public Future<Boolean> setnx(K key, V value) {
return dispatch(SETNX, new BooleanOutput<K, V>(codec), key, value);
}
public Future<Long> setrange(K key, long offset, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(offset).addValue(value);
return dispatch(SETRANGE, new IntegerOutput<K, V>(codec), args);
}
@Deprecated
public void shutdown() {
dispatch(SHUTDOWN, new StatusOutput<K, V>(codec));
}
public void shutdown(boolean save) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
dispatch(SHUTDOWN, new StatusOutput<K, V>(codec), save ? args.add(SAVE) : args.add(NOSAVE));
}
public Future<Set<V>> sinter(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SINTER, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sinterstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SINTERSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<Boolean> sismember(K key, V member) {
return dispatch(SISMEMBER, new BooleanOutput<K, V>(codec), key, member);
}
public Future<Boolean> smove(K source, K destination, V member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(source).addKey(destination).addValue(member);
return dispatch(SMOVE, new BooleanOutput<K, V>(codec), args);
}
public Future<String> slaveof(String host, int port) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(host).add(port);
return dispatch(SLAVEOF, new StatusOutput<K, V>(codec), args);
}
public Future<String> slaveofNoOne() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(NO).add(ONE);
return dispatch(SLAVEOF, new StatusOutput<K, V>(codec), args);
}
public Future<List<Object>> slowlogGet() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET);
return dispatch(SLOWLOG, new NestedMultiOutput<K, V>(codec), args);
}
public Future<List<Object>> slowlogGet(int count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(GET).add(count);
return dispatch(SLOWLOG, new NestedMultiOutput<K, V>(codec), args);
}
public Future<Long> slowlogLen() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(LEN);
return dispatch(SLOWLOG, new IntegerOutput<K, V>(codec), args);
}
public Future<String> slowlogReset() {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(RESET);
return dispatch(SLOWLOG, new StatusOutput<K, V>(codec), args);
}
public Future<Set<V>> smembers(K key) {
return dispatch(SMEMBERS, new ValueSetOutput<K, V>(codec), key);
}
public Future<List<V>> sort(K key) {
return dispatch(SORT, new ValueListOutput<K, V>(codec), key);
}
public Future<List<V>> sort(K key, SortArgs sortArgs) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
sortArgs.build(args, null);
return dispatch(SORT, new ValueListOutput<K, V>(codec), args);
}
public Future<Long> sortStore(K key, SortArgs sortArgs, K destination) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
sortArgs.build(args, destination);
return dispatch(SORT, new IntegerOutput<K, V>(codec), args);
}
public Future<V> spop(K key) {
return dispatch(SPOP, new ValueOutput<K, V>(codec), key);
}
public Future<V> srandmember(K key) {
return dispatch(SRANDMEMBER, new ValueOutput<K, V>(codec), key);
}
public Future<Set<V>> srandmember(K key, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(count);
return dispatch(SRANDMEMBER, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> srem(K key, V... members) {
return dispatch(SREM, new IntegerOutput<K, V>(codec), key, members);
}
public Future<Set<V>> sunion(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(SUNION, new ValueSetOutput<K, V>(codec), args);
}
public Future<Long> sunionstore(K destination, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).addKeys(keys);
return dispatch(SUNIONSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<String> sync() {
return dispatch(SYNC, new StatusOutput<K, V>(codec));
}
public Future<Long> strlen(K key) {
return dispatch(STRLEN, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> ttl(K key) {
return dispatch(TTL, new IntegerOutput<K, V>(codec), key);
}
public Future<String> type(K key) {
return dispatch(TYPE, new StatusOutput<K, V>(codec), key);
}
public Future<String> watch(K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKeys(keys);
return dispatch(WATCH, new StatusOutput<K, V>(codec), args);
}
public Future<String> unwatch() {
return dispatch(UNWATCH, new StatusOutput<K, V>(codec));
}
public Future<Long> zadd(K key, double score, V member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(score).addValue(member);
return dispatch(ZADD, new IntegerOutput<K, V>(codec), args);
}
@SuppressWarnings("unchecked")
public Future<Long> zadd(K key, Object... scoresAndValues) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
for (int i = 0; i < scoresAndValues.length; i += 2) {
args.add((Double) scoresAndValues[i]);
args.addValue((V) scoresAndValues[i + 1]);
}
return dispatch(ZADD, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> zcard(K key) {
return dispatch(ZCARD, new IntegerOutput<K, V>(codec), key);
}
public Future<Long> zcount(K key, double min, double max) {
return zcount(key, string(min), string(max));
}
public Future<Long> zcount(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZCOUNT, new IntegerOutput<K, V>(codec), args);
}
public Future<Double> zincrby(K key, double amount, K member) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(amount).addKey(member);
return dispatch(ZINCRBY, new DoubleOutput<K, V>(codec), args);
}
public Future<Long> zinterstore(K destination, K... keys) {
return zinterstore(destination, new ZStoreArgs(), keys);
}
public Future<Long> zinterstore(K destination, ZStoreArgs storeArgs, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(destination).add(keys.length).addKeys(keys);
storeArgs.build(args);
return dispatch(ZINTERSTORE, new IntegerOutput<K, V>(codec), args);
}
public Future<List<V>> zrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangeWithScores(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(stop).add(WITHSCORES);
return dispatch(ZRANGE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrangebyscore(K key, double min, double max) {
return zrangebyscore(key, string(min), string(max));
}
public Future<List<V>> zrangebyscore(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrangebyscore(K key, double min, double max, long offset, long count) {
return zrangebyscore(key, string(min), string(max), offset, count);
}
public Future<List<V>> zrangebyscore(K key, String min, String max, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(LIMIT).add(offset).add(count);
return dispatch(ZRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, double min, double max) {
return zrangebyscoreWithScores(key, string(min), string(max));
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(WITHSCORES);
return dispatch(ZRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, double min, double max, long offset, long count) {
return zrangebyscoreWithScores(key, string(min), string(max), offset, count);
}
public Future<List<ScoredValue<V>>> zrangebyscoreWithScores(K key, String min, String max, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(min).add(max).add(WITHSCORES).add(LIMIT).add(offset).add(count);
return dispatch(ZRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<Long> zrank(K key, V member) {
return dispatch(ZRANK, new IntegerOutput<K, V>(codec), key, member);
}
public Future<Long> zrem(K key, V... members) {
return dispatch(ZREM, new IntegerOutput<K, V>(codec), key, members);
}
public Future<Long> zremrangebyrank(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZREMRANGEBYRANK, new IntegerOutput<K, V>(codec), args);
}
public Future<Long> zremrangebyscore(K key, double min, double max) {
return zremrangebyscore(key, string(min), string(max));
}
public Future<Long> zremrangebyscore(K key, String min, String max) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(min).add(max);
return dispatch(ZREMRANGEBYSCORE, new IntegerOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrange(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(start).add(stop);
return dispatch(ZREVRANGE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangeWithScores(K key, long start, long stop) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(start).add(stop).add(WITHSCORES);
return dispatch(ZREVRANGE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrangebyscore(K key, double max, double min) {
return zrevrangebyscore(key, string(max), string(min));
}
public Future<List<V>> zrevrangebyscore(K key, String max, String min) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).add(max).add(min);
return dispatch(ZREVRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<V>> zrevrangebyscore(K key, double max, double min, long offset, long count) {
return zrevrangebyscore(key, string(max), string(min), offset, count);
}
public Future<List<V>> zrevrangebyscore(K key, String max, String min, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(LIMIT).add(offset).add(count);
return dispatch(ZREVRANGEBYSCORE, new ValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, double max, double min) {
return zrevrangebyscoreWithScores(key, string(max), string(min));
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, String max, String min) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(WITHSCORES);
return dispatch(ZREVRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, double max, double min, long offset, long count) {
return zrevrangebyscoreWithScores(key, string(max), string(min), offset, count);
}
public Future<List<ScoredValue<V>>> zrevrangebyscoreWithScores(K key, String max, String min, long offset, long count) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(key).add(max).add(min).add(WITHSCORES).add(LIMIT).add(offset).add(count);
return dispatch(ZREVRANGEBYSCORE, new ScoredValueListOutput<K, V>(codec), args);
}
public Future<Long> zrevrank(K key, V member) {
return dispatch(ZREVRANK, new IntegerOutput<K, V>(codec), key, member);
}
public Future<Double> zscore(K key, V member) {
return dispatch(ZSCORE, new DoubleOutput<K, V>(codec), key, member);
}
public Future<Long> zunionstore(K destination, K... keys) {
return zunionstore(destination, new ZStoreArgs(), keys);
}
public Future<Long> zunionstore(K destination, ZStoreArgs storeArgs, K... keys) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec);
args.addKey(destination).add(keys.length).addKeys(keys);
storeArgs.build(args);
return dispatch(ZUNIONSTORE, new IntegerOutput<K, V>(codec), args);
}
/**
* Wait until commands are complete or the connection timeout is reached.
*
* @param futures Futures to wait for.
*
* @return True if all futures complete in time.
*/
public boolean awaitAll(Future<?>... futures) {
return awaitAll(timeout, unit, futures);
}
/**
* Wait until futures are complete or the supplied timeout is reached.
*
* @param timeout Maximum time to wait for futures to complete.
* @param unit Unit of time for the timeout.
* @param futures Futures to wait for.
*
* @return True if all futures complete in time.
*/
public boolean awaitAll(long timeout, TimeUnit unit, Future<?>... futures) {
boolean complete;
try {
long nanos = unit.toNanos(timeout);
long time = System.nanoTime();
for (Future<?> f : futures) {
if (nanos < 0) return false;
f.get(nanos, TimeUnit.NANOSECONDS);
long now = System.nanoTime();
nanos -= now - time;
time = now;
}
complete = true;
} catch (TimeoutException e) {
complete = false;
} catch (Exception e) {
throw new RedisCommandInterruptedException(e);
}
return complete;
}
/**
* Close the connection.
*/
public synchronized void close() {
if (!closed && channel != null) {
ConnectionWatchdog watchdog = channel.getPipeline().get(ConnectionWatchdog.class);
watchdog.setReconnect(false);
closed = true;
channel.close();
}
}
public String digest(V script) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.update(codec.encodeValue(script));
return new String(Base16.encode(md.digest(), false));
} catch (NoSuchAlgorithmException e) {
throw new RedisException("JVM does not support SHA1");
}
}
@Override
public synchronized void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
channel = ctx.getChannel();
List<Command<K, V, ?>> tmp = new ArrayList<Command<K, V, ?>>(queue.size() + 2);
if (password != null) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(password);
tmp.add(new Command<K, V, String>(AUTH, new StatusOutput<K, V>(codec), args, false));
}
if (db != 0) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).add(db);
tmp.add(new Command<K, V, String>(SELECT, new StatusOutput<K, V>(codec), args, false));
}
tmp.addAll(queue);
queue.clear();
for (Command<K, V, ?> cmd : tmp) {
if (!cmd.isCancelled()) {
queue.add(cmd);
channel.write(cmd);
}
}
tmp.clear();
}
@Override
public synchronized void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
if (closed) {
for (Command<K, V, ?> cmd : queue) {
cmd.getOutput().setError("Connection closed");
cmd.complete();
}
queue.clear();
queue = null;
channel = null;
}
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output) {
return dispatch(type, output, (CommandArgs<K, V>) null);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key);
return dispatch(type, output, args);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key, V value) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addValue(value);
return dispatch(type, output, args);
}
public <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, K key, V[] values) {
CommandArgs<K, V> args = new CommandArgs<K, V>(codec).addKey(key).addValues(values);
return dispatch(type, output, args);
}
public synchronized <T> Command<K, V, T> dispatch(CommandType type, CommandOutput<K, V, T> output, CommandArgs<K, V> args) {
Command<K, V, T> cmd = new Command<K, V, T>(type, output, args, multi != null);
try {
if (multi != null) {
multi.add(cmd);
}
queue.put(cmd);
if (channel != null) {
channel.write(cmd);
}
} catch (NullPointerException e) {
throw new RedisException("Connection is closed");
} catch (InterruptedException e) {
throw new RedisCommandInterruptedException(e);
}
return cmd;
}
public <T> T await(Command<K, V, T> cmd, long timeout, TimeUnit unit) {
if (!cmd.await(timeout, unit)) {
cmd.cancel(true);
throw new RedisException("Command timed out");
}
CommandOutput<K, V, T> output = cmd.getOutput();
if (output.hasError()) throw new RedisException(output.getError());
return output.get();
}
@SuppressWarnings("unchecked")
protected <K, V, T> CommandOutput<K, V, T> newScriptOutput(RedisCodec<K, V> codec, ScriptOutputType type) {
switch (type) {
case BOOLEAN: return (CommandOutput<K, V, T>) new BooleanOutput<K, V>(codec);
case INTEGER: return (CommandOutput<K, V, T>) new IntegerOutput<K, V>(codec);
case STATUS: return (CommandOutput<K, V, T>) new StatusOutput<K, V>(codec);
case MULTI: return (CommandOutput<K, V, T>) new NestedMultiOutput<K, V>(codec);
case VALUE: return (CommandOutput<K, V, T>) new ValueOutput<K, V>(codec);
default: throw new RedisException("Unsupported script output type");
}
}
public String string(double n) {
if (Double.isInfinite(n)) {
return (n > 0) ? "+inf" : "-inf";
}
return Double.toString(n);
}
}
| [
"[email protected]"
] | |
2341c86015e168ff3ec2de38e81513a7c0b4c3a0 | 6252c165657baa6aa605337ebc38dd44b3f694e2 | /org.eclipse.epsilon.egl.sync/Scalability-Tests/boiler-To-Generate-1000-Files/boiler-To-Generate-1000-Files/syncregions-1000Files/BoilerActuator4284.java | a2ef21b51a9f676e085f5ff4506c5e9ab7054a5c | [] | no_license | soha500/EglSync | 00fc49bcc73f7f7f7fb7641d0561ca2b9a8ea638 | 55101bc781349bb14fefc178bf3486e2b778aed6 | refs/heads/master | 2021-06-23T02:55:13.464889 | 2020-12-11T19:10:01 | 2020-12-11T19:10:01 | 139,832,721 | 0 | 1 | null | 2019-05-31T11:34:02 | 2018-07-05T10:20:00 | Java | UTF-8 | Java | false | false | 267 | java | package syncregions;
public class BoilerActuator4284 {
public int execute(int temperatureDifference4284, boolean boilerStatus4284) {
//sync _bfpnGUbFEeqXnfGWlV4284, behaviour
Half Change - return temperature - targetTemperature;
//endSync
}
}
| [
"[email protected]"
] | |
6590548770e6895cf1037e1e61c5ede23de604da | 682929767740301d4ab3e020a5996f2e43ef8f56 | /MessageQueue/src/assignment/Responder.java | a564b93675931ed396c0468a27114a548dd450c1 | [] | no_license | JosephMalandruccolo/CSPP51050-HW2 | 44c71c65adcafc82eaead22140a35d239d3a6cbd | 56e0f2ed9775b1ee6faba218f4d00ab867967dfa | refs/heads/master | 2021-01-10T19:05:46.002684 | 2013-05-06T00:37:32 | 2013-05-06T00:37:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,217 | java | package assignment;
import java.util.HashMap;
/**
* Responds to Query Messages
* @author Joseph Malandruccolo
*
*/
public class Responder {
//=====================================================================
// => CLASS
//=====================================================================
public static int nextId = 1;
private static HashMap<Integer, String> presidentialData;
static {
presidentialData = new HashMap<Integer, String>();
presidentialData.put(1, "George Washington");
presidentialData.put(2, "John Adams");
presidentialData.put(3, "Thomas Jefferson");
presidentialData.put(4, "James Madison");
presidentialData.put(5, "James Monroe");
presidentialData.put(6, "John Qunicy Adams");
presidentialData.put(7, "Andrew Jackson");
presidentialData.put(8, "Martin Van Buren");
presidentialData.put(9, "William Henry Harrison");
presidentialData.put(10, "John Tyler");
}
//=====================================================================
// => PROPERTIES
//=====================================================================
private int id;
//=====================================================================
// => CONSTRUCTOR
//=====================================================================
public Responder() {
this.id = Responder.nextId++;
}
//=====================================================================
// => PUBLIC API
//=====================================================================
public int getId() { return this.id; }
//=====================================================================
// => QUEUE INTERACTION
//=====================================================================
public void readQueue(MessageQueue q) {
Message msg = q.popMessageIfForRecipient(this.id);
if (msg != null) {
if (msg instanceof QueryMsg) {
int request = (Integer) msg.getContents();
ReplyMsg reply = new ReplyMsg(this.id, msg.getSenderId(), Responder.presidentialData.get(request), ((QueryMsg) msg).getQueryId());
q.pushMessage(reply);
}
else {
q.pushMessage(new ReplyMsg(this.id, msg.getSenderId(), new String("Invalid message type"), -1));
}
}
}
}
| [
"[email protected]"
] | |
f06fafa3abe4d238ce38d317bf95e325a6f35f9c | c71831709c5c56f99d32b4c5369b3bc51d415d55 | /app/src/main/java/com/hasan/mathsukrevision/AqaJun18Paper3.java | 01fd5db5d93ee3664f0148d28603db4c3c23f6a2 | [] | no_license | hasanalfaruk/unifinalproject | 869c2a9e8e289fa23b37ec4bd70b325e2e95163c | bec65418ebe92eb17d176e655c8b243468592751 | refs/heads/main | 2023-06-28T22:18:27.972472 | 2021-08-02T11:32:07 | 2021-08-02T11:32:07 | 386,979,054 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 553 | java | package com.hasan.mathsukrevision;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.github.barteksc.pdfviewer.PDFView;
public class AqaJun18Paper3 extends AppCompatActivity {
private PDFView paper3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aqa_jun18_paper3);
paper3 = (PDFView) findViewById(R.id.pdfAqa_Jun18_3);
paper3.fromAsset("AQA-83003H-QPMS-jun18.pdf").load();
}
} | [
"[email protected]"
] | |
4f423d892dfdd916c0114a222acb727e1a598da1 | 911d71da9155b022631a071c631ce1b2cb14b92c | /basic-arch-ruoyivue/ruoyi-system/src/main/java/com/ruoyi/system/service/ISysDeptService.java | c69f24bfb1a60c91ad7c49e70d39ca64a48ac118 | [
"MIT"
] | permissive | devsong/basic_arch | 09cc86f0f2b7a1b836195316426c2a72b78271dd | 7e48c3e52878939f6b191741d338e24fc7eea90e | refs/heads/master | 2023-03-08T09:34:24.906231 | 2021-05-20T07:18:28 | 2021-05-20T07:18:28 | 203,941,641 | 0 | 1 | null | 2023-02-22T07:51:07 | 2019-08-23T06:53:47 | Java | UTF-8 | Java | false | false | 2,478 | java | package com.ruoyi.system.service;
import java.util.List;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
/**
* 部门管理 服务层
*
* @author guanzhisong
*/
public interface ISysDeptService {
/**
* 查询部门管理数据
*
* @param dept 部门信息
* @return 部门信息集合
*/
public List<SysDept> selectDeptList(SysDept dept);
/**
* 构建前端所需要树结构
*
* @param depts 部门列表
* @return 树结构列表
*/
public List<SysDept> buildDeptTree(List<SysDept> depts);
/**
* 构建前端所需要下拉树结构
*
* @param depts 部门列表
* @return 下拉树结构列表
*/
public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts);
/**
* 根据角色ID查询部门树信息
*
* @param roleId 角色ID
* @return 选中部门列表
*/
public List<Integer> selectDeptListByRoleId(Long roleId);
/**
* 根据部门ID查询信息
*
* @param deptId 部门ID
* @return 部门信息
*/
public SysDept selectDeptById(Long deptId);
/**
* 根据ID查询所有子部门(正常状态)
*
* @param deptId 部门ID
* @return 子部门数
*/
public int selectNormalChildrenDeptById(Long deptId);
/**
* 是否存在部门子节点
*
* @param deptId 部门ID
* @return 结果
*/
public boolean hasChildByDeptId(Long deptId);
/**
* 查询部门是否存在用户
*
* @param deptId 部门ID
* @return 结果 true 存在 false 不存在
*/
public boolean checkDeptExistUser(Long deptId);
/**
* 校验部门名称是否唯一
*
* @param dept 部门信息
* @return 结果
*/
public String checkDeptNameUnique(SysDept dept);
/**
* 新增保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
public int insertDept(SysDept dept);
/**
* 修改保存部门信息
*
* @param dept 部门信息
* @return 结果
*/
public int updateDept(SysDept dept);
/**
* 删除部门管理信息
*
* @param deptId 部门ID
* @return 结果
*/
public int deleteDeptById(Long deptId);
}
| [
"[email protected]"
] | |
9c7e0e1828c97eb800b31db753c1368bc8f10980 | 8de7d24a3b26954b46fabfd6190452da37e6fe5a | /src/main/java/com/hrtx/global/EgtPage.java | be72b9100d95c53077a8b98f5e9d0e8700a5f08f | [] | no_license | funtalkTelecom/saleBUBackend | 7ed31d8cf2849f4ffc382b334dbf0de48d1f0ee3 | d2b53e7a9888226928a276b7a68a9ce85a590ea0 | refs/heads/master | 2022-05-22T18:27:26.046073 | 2019-06-24T10:06:14 | 2019-06-24T10:06:14 | 192,842,892 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 409 | java | package com.hrtx.global;
public class EgtPage extends com.github.pagehelper.Page {
private long total;
public EgtPage(int pageNum, int pageSzie, long totalHits) {
super(pageNum, pageSzie);
this.total = totalHits;
}
@Override
public long getTotal() {
return total;
}
@Override
public void setTotal(long total) {
this.total = total;
}
}
| [
"[email protected]"
] | |
66437172f4238b86a30e70f731d3ff5368c59112 | 82487900d0d4e9a0a2d9f24e605c64db3585a40f | /app/src/main/java/com/example/corstan__cc__managment/Model/Day.java | e911f28b7a44eb7651a3dd92aaaa378699e0dd1d | [] | no_license | ryangd/Corstan--CC--Managment | 2a18cc3e9c4f7b35740e7503ac45de15f0a6c657 | 224e508bb48d77925e19d3af011c5053f7a18007 | refs/heads/master | 2022-12-04T02:23:36.851940 | 2020-08-22T03:15:07 | 2020-08-22T03:15:07 | 288,278,259 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 865 | java | /*
* Property of: GreenDot Management Systems Inc.
* A Division Of
* Corstan Systems Inc.
*
* Written By: Ryan Stander
* [email protected]
* June 17, 2020
*
* Copyright (c) TradeMark Reserved (tm)
*
*/
package com.example.corstan__cc__managment.Model;
public class Day {
private String dayDate, dayDay;
public Day (){
}
public Day(String dayDate, String dayDay) {
this.dayDate = dayDate;
this.dayDay = dayDay;
}
public String getDayDay() {
return dayDay;
}
public void setDayDay(String dayDay) {
this.dayDay = dayDay;
}
public String getDayDate() {
return dayDate;
}
public void setDayDate(String dayDate) {
this.dayDate = dayDate;
}
}
| [
"[email protected]"
] | |
621a94254b9dae1293a9d03b4f1a5e61212a38c3 | 3bcaebf7d69eaab5e4086568440b2ca56219b50d | /src/main/java/com/tinyolo/cxml/parsing/demo/jaxb/cxml/RequiredMaximumQuantity.java | c6583d21312b479e569982db941a4a8d4108b1fc | [] | no_license | augustine-d-nguyen/cxml-parsing-demo | 2a419263b091b32e70fa84312b55d8217e691ac6 | 3cc169ee0392d88bbf0e03f0791a15287a8eba97 | refs/heads/master | 2023-01-18T19:07:27.094598 | 2020-11-20T14:52:52 | 2020-11-20T14:52:52 | 314,490,660 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,164 | java | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.2
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2020.11.20 at 08:07:34 PM ICT
//
package com.tinyolo.cxml.parsing.demo.jaxb.cxml;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"unitOfMeasure"
})
@XmlRootElement(name = "RequiredMaximumQuantity")
public class RequiredMaximumQuantity {
@XmlAttribute(name = "quantity")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String quantity;
@XmlElement(name = "UnitOfMeasure")
protected String unitOfMeasure;
/**
* Gets the value of the quantity property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getQuantity() {
return quantity;
}
/**
* Sets the value of the quantity property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setQuantity(String value) {
this.quantity = value;
}
/**
* Gets the value of the unitOfMeasure property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUnitOfMeasure() {
return unitOfMeasure;
}
/**
* Sets the value of the unitOfMeasure property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUnitOfMeasure(String value) {
this.unitOfMeasure = value;
}
}
| [
"[email protected]"
] | |
7b0f5b072e879fd4fdacdf31d9ca6611b989de48 | 25cbbac28845e08d9f353879f2a36c561d973a0d | /BehavioralDesignPatten/src/TemplateMethod/Meal.java | be5e2f3e78313b2b580d1f95b69502e4c8ae4543 | [] | no_license | huynhtanhoa3011/Module2-java | 6471144be3ad2e23c5deb91122621cae1a564f60 | 1ba89358887219caa0f70f2eee3a97a76ffe5878 | refs/heads/main | 2023-07-16T02:51:25.757425 | 2021-09-02T05:57:13 | 2021-09-02T05:57:13 | 389,837,906 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 388 | java | package TemplateMethod;
public abstract class Meal {
public final void doMeal() {
prepareIngredients();
cook();
eat();
cleanUp();
}
public abstract void prepareIngredients();
public abstract void cook();
public void eat(){
System.out.println("Mmm, that's good");
}
public abstract void cleanUp();
}
| [
"[email protected]"
] | |
774406206caa47107860142cebc07fcc44d2ebad | b160bd1d344d3d9af67f7d9e7b7e9f48d3c6db8c | /src/cn/book/ui/UserFrame.java | 68e42ee4af791b2c0249f1e860f54da3699d5e6f | [] | no_license | clooney0/bookmanagement | 4a3632633a30baee981d53a7b17ca28c6d4eb596 | bbeed21ec77676e8aa65beaeb14944e4cd500da9 | refs/heads/master | 2022-02-19T07:44:01.426856 | 2017-11-20T11:24:02 | 2017-11-20T11:24:02 | 111,398,383 | 6 | 1 | null | null | null | null | UTF-8 | Java | false | false | 16,864 | java | package cn.book.ui;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableModel;
import org.jvnet.substance.SubstanceLookAndFeel;
import org.jvnet.substance.button.StandardButtonShaper;
import org.jvnet.substance.skin.CremeSkin;
import org.jvnet.substance.theme.SubstanceCremeTheme;
import org.jvnet.substance.watermark.SubstanceBinaryWatermark;
import cn.book.dao.UserDao;
import cn.book.entity.User;
import cn.book.util.StringUtil;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
public class UserFrame {
public JFrame frame;
private JTable table;
private JTextField nameField;
private JButton btnQueryname;
private JLabel nameLabel;
private JLabel phoneLabel;
private JTextField phoneField;
private JButton btnQueryphone;
private JPopupMenu popupMenu;
private JMenuItem reflushItem;
private JMenuItem getvalueItem;
private JLabel genderLabel;
private final ButtonGroup buttonGroup = new ButtonGroup();
private JTextField idField;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(new SubstanceLookAndFeel());
JFrame.setDefaultLookAndFeelDecorated(true); // frame
JDialog.setDefaultLookAndFeelDecorated(true); // dialog
SubstanceLookAndFeel.setCurrentTheme(new SubstanceCremeTheme()); // theme
SubstanceLookAndFeel.setSkin(new CremeSkin()); // skin
SubstanceLookAndFeel
.setCurrentWatermark(new SubstanceBinaryWatermark()); // watermark
SubstanceLookAndFeel
.setCurrentButtonShaper(new StandardButtonShaper()); // button
// SubstanceLookAndFeel.setCurrentBorderPainter(new
// StandardBorderPainter());
// SubstanceLookAndFeel.setCurrentGradientPainter(new
// StandardGradientPainter());
// SubstanceLookAndFeel.setCurrentTitlePainter(new
// FlatTitePainter());
} catch (Exception e) {
System.err.println("Something went wrong!");
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserFrame window = new UserFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*
* @throws Exception
*/
public UserFrame() throws Exception {
initialize();
}
/**
* Initialize the contents of the frame.
*
* @throws Exception
*/
private void initialize() throws Exception {
frame = new JFrame();
frame.setTitle("书籍管理系统");
frame.setResizable(false);
frame.setBounds(100, 100, 850, 600);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image image = toolkit.getImage("img/sys.png");
frame.setIconImage(image);
frame.setLocationRelativeTo(null);
JLabel userLabel = new JLabel("读者信息管理");
userLabel.setForeground(Color.RED);
userLabel.setFont(new Font("SimSun", Font.PLAIN, 25));
userLabel.setHorizontalAlignment(SwingConstants.CENTER);
userLabel.setBounds(310, 27, 190, 30);
frame.getContentPane().add(userLabel);
// table
table = new JTable();
UserDao dao = new UserDao();
Object[][] data = null; // 声明date
List<User> user = dao.queryUser();
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data, new String[] { "编号", "名字",
"性别", "手机号" }));
// scorll
final JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(72, 74, 695, 210);
frame.getContentPane().add(scroll);
nameLabel = new JLabel("读者姓名");
nameLabel.setFont(new Font("SimSun", Font.PLAIN, 18));
nameLabel.setBounds(139, 315, 95, 25);
frame.getContentPane().add(nameLabel);
nameField = new JTextField();
nameField.setFont(new Font("SimSun", Font.PLAIN, 18));
nameField.setBounds(282, 313, 190, 30);
frame.getContentPane().add(nameField);
nameField.setColumns(10);
// button queryByname 姓名查询按钮
btnQueryname = new JButton("姓名查询");
btnQueryname.setFont(new Font("SimSun", Font.PLAIN, 18));
btnQueryname.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = nameField.getText();
// 创建 Dao
UserDao dao = new UserDao();
String name = "%" + text + "%";
Object[][] data = null; // 声明date
List<User> user = dao.queryUserByname(name);
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data, new String[] { "编号",
"名字", "性别", "手机号" }));
scroll.setViewportView(table);
}
});
btnQueryname.setBounds(529, 312, 122, 30);
frame.getContentPane().add(btnQueryname);
phoneLabel = new JLabel("手机号");
phoneLabel.setFont(new Font("SimSun", Font.PLAIN, 18));
phoneLabel.setBounds(139, 368, 95, 25);
frame.getContentPane().add(phoneLabel);
phoneField = new JTextField();
phoneField.setFont(new Font("SimSun", Font.PLAIN, 18));
phoneField.setBounds(282, 366, 190, 30);
frame.getContentPane().add(phoneField);
phoneField.setColumns(10);
// button queryByphone 手机查询 按钮
btnQueryphone = new JButton("手机查询");
btnQueryphone.setFont(new Font("SimSun", Font.PLAIN, 18));
btnQueryphone.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String text = phoneField.getText();
// 创建 Dao
UserDao dao = new UserDao();
String phone = "%" + text + "%";
Object[][] data = null; // 声明date
List<User> user = dao.queryUserByphone(phone);
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data, new String[] { "编号",
"名字", "性别", "手机号" }));
scroll.setViewportView(table);
}
});
btnQueryphone.setBounds(529, 365, 122, 30);
frame.getContentPane().add(btnQueryphone);
genderLabel = new JLabel("性别");
genderLabel.setFont(new Font("SimSun", Font.PLAIN, 18));
genderLabel.setBounds(139, 421, 95, 25);
frame.getContentPane().add(genderLabel);
final JRadioButton maleRadio = new JRadioButton("男");
maleRadio.setSelected(true);
buttonGroup.add(maleRadio);
maleRadio.setFont(new Font("SimSun", Font.PLAIN, 18));
maleRadio.setBounds(282, 421, 56, 25);
frame.getContentPane().add(maleRadio);
final JRadioButton femaleRadio = new JRadioButton("女");
femaleRadio.setFont(new Font("SimSun", Font.PLAIN, 18));
buttonGroup.add(femaleRadio);
femaleRadio.setBounds(344, 421, 56, 25);
frame.getContentPane().add(femaleRadio);
JLabel idLabel = new JLabel("读者编号");
idLabel.setFont(new Font("SimSun", Font.PLAIN, 18));
idLabel.setBounds(139, 473, 95, 25);
frame.getContentPane().add(idLabel);
idField = new JTextField();
idField.setEnabled(false);
idField.setFont(new Font("SimSun", Font.PLAIN, 18));
idField.setColumns(10);
idField.setBounds(282, 471, 190, 30);
frame.getContentPane().add(idField);
// button modifyUser 修改按钮
JButton btnUsermodify = new JButton("修改");
btnUsermodify.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
// 取值
String strid = idField.getText();
long id = Long.valueOf(strid); // String-->id
String name = nameField.getText();
String phone = phoneField.getText();
String regex = "^1[3|4|5|7|8]\\d{9}$";
boolean isNum = phone.matches(regex);
if (isNum == false) {
JOptionPane.showMessageDialog(null, "手机格式不正确!");
} else {
// 获取男女信息
String gender = "男";
if (femaleRadio.isSelected()) {
gender = "女";
}
UserDao dao = new UserDao();
User obj = new User(id, name, gender, phone);
boolean isupdate = dao.updateUser(obj);
if (isupdate) {
// 判断是否为空
if (StringUtil.hasLength(name)
&& StringUtil.hasLength(phone)
&& StringUtil.hasLength(gender)) {
JOptionPane.showMessageDialog(null, "修改成功");
// 刷新table
Object[][] data = null;
dao = new UserDao();
List<User> user = dao.queryUser();
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(
data,
new String[] { "编号", "名字", "性别", "手机号" }));
scroll.setViewportView(table);
} else {
JOptionPane.showMessageDialog(null, "输入不能为空");
}
}
/*
* else { // 异常在UserDao处理
* JOptionPane.showMessageDialog(null, "修改失败!");
* //手机号已存在
*
* }
*/
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "数据不能为空!");
}
}
});
btnUsermodify.setFont(new Font("SimSun", Font.PLAIN, 18));
btnUsermodify.setBounds(539, 416, 105, 30);
frame.getContentPane().add(btnUsermodify);
// button addUser 添加按钮
JButton btnUseradd = new JButton("添加");
btnUseradd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 取值
String name = nameField.getText();
String phone = phoneField.getText();
String regex = "^1[3|4|5|7|8]\\d{9}$";
boolean isNum = phone.matches(regex);
if (isNum == false) {
JOptionPane.showMessageDialog(null, "手机格式不正确!");
} else {
// 获取男女信息
String gender = "男";
if (femaleRadio.isSelected()) {
gender = "女";
}
UserDao dao = new UserDao();
User obj = new User(0, name, gender, phone);
boolean isadd = dao.addUser(obj);
if (isadd) {
// 判断是否为空
if (StringUtil.hasLength(name)
&& StringUtil.hasLength(phone)
&& StringUtil.hasLength(gender)) {
JOptionPane.showMessageDialog(null, "添加成功");
// 刷新table
Object[][] data = null;
dao = new UserDao();
List<User> user = dao.queryUser();
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data,
new String[] { "编号", "名字", "性别", "手机号" }));
scroll.setViewportView(table);
} else {
JOptionPane.showMessageDialog(null, "输入不能为空");
}
}
/*
* else { //UserDao处理异常 JOptionPane.showMessageDialog(null,
* "添加失败"); }
*/
}
}
});
btnUseradd.setFont(new Font("SimSun", Font.PLAIN, 18));
btnUseradd.setBounds(539, 470, 105, 30);
frame.getContentPane().add(btnUseradd);
// 右键菜单
popupMenu = new JPopupMenu();
popupMenu.addAncestorListener(new AncestorListener() {
public void ancestorAdded(AncestorEvent event) {
}
public void ancestorMoved(AncestorEvent event) {
}
public void ancestorRemoved(AncestorEvent event) {
}
});
addPopup(table, popupMenu);
// 右键删除
JMenuItem deleteItem = new JMenuItem("删除");
deleteItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("删除");
int isdel = JOptionPane.showConfirmDialog(null, "是否删除", "提示",
JOptionPane.YES_NO_OPTION);
System.out.println("isdel==" + isdel);
if (isdel == 0) {
try {
// 确认删除
Object object = table.getValueAt(
table.getSelectedRow(), 0);
UserDao dao = new UserDao();
boolean b = dao.deleteUser((Long) object); // UserDao
// 处理异常
if (b) {
JOptionPane.showMessageDialog(null, "删除成功");
Object[][] data = null; // 声明date
List<User> user = dao.queryUser();
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data,
new String[] { "编号", "名字", "性别", "手机号" }));
scroll.setViewportView(table);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "请在表格中选中一行,右键删除!");
}
}
}
});
// 右键获取数值
getvalueItem = new JMenuItem("获取该行数据");
getvalueItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long id = (Long) table.getValueAt(table.getSelectedRow(), 0);// get
// id
idField.setText(String.valueOf(id));// set id long--->String
String name = (String) table.getValueAt(
table.getSelectedRow(), 1);
nameField.setText(name); // name赋值到文本框
String gender = (String) table.getValueAt(
table.getSelectedRow(), 2);
if (gender.equals("男")) { // gender 设置被选中
maleRadio.setSelected(true);
} else {
femaleRadio.setSelected(true);
}
String phone = (String) table.getValueAt(
table.getSelectedRow(), 3);
phoneField.setText(phone); // phone
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "请在表格中选中一行,右键取值!");
}
}
});
popupMenu.add(getvalueItem);
// 右键刷新
reflushItem = new JMenuItem("刷新");
reflushItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[][] data = null;
UserDao dao = new UserDao();
List<User> user = dao.queryUser();
data = new Object[user.size()][4];
for (int i = 0; i < user.size(); i++) {
User u = user.get(i);
data[i][0] = u.getUser_id();
data[i][1] = u.getUser_name();
data[i][2] = u.getUser_gender();
data[i][3] = u.getUser_phone();
}
table.setModel(new DefaultTableModel(data, new String[] { "编号",
"名字", "性别", "手机号" }));
scroll.setViewportView(table);
}
});
popupMenu.add(reflushItem);
popupMenu.add(deleteItem);
}
// addPopup
private static void addPopup(Component component, final JPopupMenu popup) {
component.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
showMenu(e);
}
}
private void showMenu(MouseEvent e) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
| [
"[email protected]"
] | |
bdcaa2d5b666a1a49a4ce2fb310c6fdd8aaddafa | 5a124224b497605306b4efdb3be2da013461ea22 | /Case1.java | c8b60033343440a67d5cfa2b4f275dbf7e1ec4e2 | [] | no_license | rdwornik/ecote-project | f5f6f93e6a4a81278ec3621290ac3583fbfd6b30 | b407728bae3eeb78abd3e76a1c2ccb9cda38d6a8 | refs/heads/master | 2022-01-18T18:05:46.425617 | 2019-05-22T10:19:24 | 2019-05-22T10:19:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,314 | java | /*
Successful case:
We test 5 cases;
-Already declared "Runnable" interface in library with no arguemnts
-Decalred Interface with 3 paramaters and using this parametrs in lambda body
-Interface with one parameter not used in lambda body
-Interface with six parameters used in lambda body
-Interface with one parameter used in lambda body
*/
interface Interface{
public void foo(Object n, Object l, Object p);
}
interface Interface2{
public void foo2(Object n);
}
interface Interface3{
public void foo3(Object x, Object y, Object z,Object a, Object b, Object c);
}
interface Interface4{
public void foo4(Object n);
}
public class Case1 {
public static void main(String[] args) {
Runnable run = () -> {
System.out.println("Hello");
};
Interface foo = (x,y,z) -> {
System.out.println(x);
Integer v = (Integer) x;
v++;
};
Interface2 foo2 = (x) -> {
System.out.println("hello");
};
Interface3 foo3 = (x,y,z,a,b,c) -> {
System.out.println("hello");
Integer v = (Integer) a;
v++;
Integer o = (Integer) b;
o++;
};
Interface4 foo4 = (x) -> {
System.out.println(x);
};
}
}
| [
"[email protected]"
] | |
2536464853bde66fd5221698d94e400437b2e97b | 7639cb47863dc8ee41a420f4e838d61e9857bbf4 | /NTurk_BACKEND_1/src/main/java/foursomeSE/entity/statistics/UserDistribution.java | f61a5e77793263ddbc9338e0fc4cc5195bc3b03d | [] | no_license | PatrickLai7528/NTurk_Phase_III | 3e0288a337ca562662d41ed8477b0df3f2ca42ed | 4a23be2ac0d6ec79a69c9564d9bb883efc14e3c8 | refs/heads/master | 2020-04-26T17:42:17.704743 | 2018-09-05T01:13:58 | 2018-09-05T01:13:58 | 173,721,636 | 0 | 0 | null | 2020-04-12T03:51:17 | 2019-03-04T10:14:09 | Java | UTF-8 | Java | false | false | 1,240 | java | package foursomeSE.entity.statistics;
public class UserDistribution {
private String name; // 就是province
private int value;
public UserDistribution() {
}
public UserDistribution(String name, int value) {
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public String toString() {
return "UserDistribution{" +
"name='" + name + '\'' +
", value=" + value +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof UserDistribution)) return false;
UserDistribution that = (UserDistribution) o;
if (value != that.value) return false;
return name != null ? name.equals(that.name) : that.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + value;
return result;
}
}
| [
"[email protected]"
] | |
de8aa0f97ebccc7e63138b3f00f3b10984974c4f | ed1344487a6f2711a946fdfe92cbfa92f5d8f921 | /src/com/abd/services/CustServicesImpl.java | 82c936506c746736049d34dae8f11aed455f7415 | [] | no_license | showagon/SpringMVC_manaul_library | 9d589ac2d1f306a9f1b5aea869e90d6f564b8e0d | 553d03380d784aa43e5fe6aeee16d98f3cf2e959 | refs/heads/master | 2020-07-29T11:04:03.504913 | 2019-09-20T11:32:51 | 2019-09-20T11:32:51 | 209,773,580 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 925 | java | package com.abd.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.abd.dao.CustDao;
import com.abd.entity.Customer;
@Service
public class CustServicesImpl implements CustServices {
@Autowired
private CustDao custdao;
@Override
@Transactional
public List<Customer> getCustomer() {
return custdao.getcustlist();
}
@Override
@Transactional
public void saveCustomer(Customer thecustomer) {
custdao.saveCustomer(thecustomer);
}
@Override
@Transactional
public Customer getcustomer(int theid) {
return custdao.getcustomer(theid);
}
@Override
@Transactional
public void deleteCustomer(int theid) {
custdao.deleteCustomer(theid);
}
}
| [
"[email protected]"
] | |
9a335ccc6a938e8cc64382cb0ba04e6741f14966 | e79a12f7d2538dce830d8abc858d49c247f14248 | /src/main/java/com/firstjhipster/sample/security/jwt/TokenProvider.java | f62ec50192fab66521974ad56cc88f9a155d6fb5 | [] | no_license | shindedeepali1994/Sample | 17f778dfd66f3213ecf7b42efe2ab0d212ebfeb0 | 345b501547f2fefa7eb9c98b808b62d93f036704 | refs/heads/master | 2021-06-23T20:22:06.407545 | 2019-11-15T06:03:11 | 2019-11-15T06:03:11 | 221,855,121 | 0 | 0 | null | 2021-04-29T21:53:11 | 2019-11-15T06:03:03 | Java | UTF-8 | Java | false | false | 4,256 | java | package com.firstjhipster.sample.security.jwt;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
@Component
public class TokenProvider implements InitializingBean {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
private static final String AUTHORITIES_KEY = "auth";
private Key key;
private long tokenValidityInMilliseconds;
private long tokenValidityInMillisecondsForRememberMe;
private final JHipsterProperties jHipsterProperties;
public TokenProvider(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void afterPropertiesSet() throws Exception {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(key, SignatureAlgorithm.HS512)
.setExpiration(validity)
.compact();
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (JwtException | IllegalArgumentException e) {
log.info("Invalid JWT token.");
log.trace("Invalid JWT token trace.", e);
}
return false;
}
}
| [
"[email protected]"
] | |
3c225d8ab71086e71ec4c958d99ab32a6bf7cb64 | 5f4bfcdf9c1b8f3d7ac31785201edb59a7e35273 | /src/com/javarush/test/level13/lesson02/task07/Solution.java | 14769082afab417f97d9d1acda6e3aaf3a207255 | [] | no_license | sergAleshchenko/JavaRushHomeWork | f6c9d23e881245c80d42f72cf06a5d860191b0a4 | ff67c727cbe9f27468d83d625594b3f682a58320 | refs/heads/master | 2021-01-18T11:50:31.130020 | 2016-01-13T03:52:50 | 2016-01-13T03:52:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 625 | java | package com.javarush.test.level13.lesson02.task07;
/* Параметризованый интерфейс
В классе StringObject реализуй интерфейс SimpleObject с параметром типа String.
*/
public class Solution
{
public static void main(String[] args) throws Exception
{
}
interface SimpleObject<T>
{
SimpleObject<T> getInstance();
}
class StringObject implements SimpleObject<String> //допишите здесь ваш код
{
public SimpleObject<String> getInstance() {
return new StringObject();
}
}
}
| [
"[email protected]"
] | |
38727fe6187be6a40c70cf00cf2148d4e065d1cf | d69ab48c3a3e2f2ebce488c0627c536c81421685 | /MovingCard.java | 0d8d90931a7398797019aba927042eaa17fef9c0 | [] | no_license | sdr04055/maplestone | 63490d1d262faa221451003117b310b6d6e882d7 | 4face29c416cea92c20c07112a75ecc5079b2d0d | refs/heads/master | 2016-09-06T05:56:41.585999 | 2015-05-12T11:59:42 | 2015-05-12T11:59:42 | 35,484,627 | 1 | 2 | null | null | null | null | UTF-8 | Java | false | false | 1,021 | java |
public class MovingCard {
static Card data, goal;
static Champion goalChamp;
static int goalx, goaly;
static int movingTime = 1500;
static double speedx, speedy;
static double nowx, nowy;
static int retx, rety;
static boolean isMoving;
static void update(){
nowx += speedx;
nowy += speedy;
if(goalx == retx && goaly == rety){
//returning
if(Math.abs(nowx-goalx)<=Math.abs(speedx) || Math.abs(nowy-goaly)<=Math.abs(speedy)){
isMoving = false;
nowx = retx;
nowy = rety;
}
}
else if(Math.abs(goalx-nowx)<60 && Math.abs(goaly-nowy)<90){
//isMoving = false;isMoving = true;
if(goal.name!=""){
data.hp -= goal.atk;
goal.hp -= data.atk;
if(data.hpmax<data.hp)data.hp = data.hpmax;
if(goal.hpmax<goal.hp)goal.hp = goal.hpmax;
}
else{
goalChamp.hp -= data.atk;
if(goalChamp.hpmax<goalChamp.hp)goalChamp.hp = goalChamp.hpmax;
}
goalx = retx;
goaly = rety;
speedx *= -1;
speedy *= -1;
}
data.x = (int)nowx;
data.y = (int)nowy;
}
}
| [
"[email protected]"
] | |
1bd1bb3493dc542bc2b6be6bde1e9ed5308c3fc0 | 3ee6d6a1ca3f19b56eab7936a1e2839fc4b29e78 | /jungsuk/src/ch12/ThreadEx2.java | efb264aaa9d7b16c5a6f70838889137b2e6689db | [] | no_license | daegi/study-dg | 2764592b0f0914ec64b0a418a0417a1d6091651f | ad9862ecb60aca7265481daf7735d9dfd826e5f6 | refs/heads/master | 2021-01-19T13:52:59.044839 | 2014-07-25T03:27:26 | 2014-07-25T03:27:26 | 32,976,520 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 364 | java | package ch12;
public class ThreadEx2 {
public static void main(String[] args) {
MyThreadEx2_1 t1 = new MyThreadEx2_1();
t1.start();
}
}
class MyThreadEx2_1 extends Thread{
public void run(){
throwException();
}
public void throwException(){
try{
throw new Exception();
}catch(Exception e){
e.printStackTrace();
}
}
} | [
"choyc82@cf0b24a7-709c-1eb7-a6c0-50069b54bc80"
] | choyc82@cf0b24a7-709c-1eb7-a6c0-50069b54bc80 |
635092a6e40079bfd7bb4e55d77af55a900dbf74 | 6324ba3857e09e1ff891dc547f05bb7c9ed6f449 | /apps/maintenance/web/src/main/java/net/aicoder/maintenance/business/product/product/package-info.java | eb9f5cdd9a811cac3ada9a125a619067f0d75f2a | [] | no_license | ai-coders/devp | 68a0431007ebd5796dbf48a321ee08ff2dd87708 | 9dfe34374048cea2e613fa01fd9f584c5090361d | refs/heads/master | 2023-01-09T12:16:06.197363 | 2018-11-24T09:16:25 | 2018-11-24T09:16:25 | 134,250,514 | 0 | 2 | null | 2022-12-26T05:54:12 | 2018-05-21T09:53:00 | Java | UTF-8 | Java | false | false | 57 | java | package net.aicoder.maintenance.business.product.product; | [
"[email protected]"
] | |
6c0d068baa47d7b92ed9d9b1d89121831e967517 | 74c2241ffd858933efd645b25618b608c2e1b6b0 | /Comicser/app/src/main/java/com/sedsoftware/comicser/features/widget/ComicWidgetService.java | 9b1c2aeb0a4877898c2d6b2c3727f45e4921c2d1 | [] | no_license | cpt-r3tr0/Android | 3559b9ea039e87f1222e42cb69ec4a8566db2885 | 47b987bfeabe4f9dd0b1683b5aa7d0655b9d8b4e | refs/heads/master | 2020-04-06T10:26:49.751079 | 2018-11-13T15:09:33 | 2018-11-13T15:09:33 | 157,380,576 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 327 | java | package com.sedsoftware.comicser.features.widget;
import android.content.Intent;
import android.widget.RemoteViewsService;
public class ComicWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new ComicWidgetFactory(getApplicationContext());
}
}
| [
"[email protected]"
] | |
e7f3660db75a98f7ccaa9e9b4712415ddc2b29d3 | e62c3b93b38d2d7781d38ba1cdbabfea2c1cf7af | /BocBankMobile/src/main/java/com/boc/bocsoft/mobile/bocmobile/buss/wealthmanagement/mypositions/financialposition/ui/FinancialTypeProgressQueryFragment.java | 1c3e650e4cf18cc44bde9d84b4e452732650ad0a | [] | no_license | soghao/zgyh | df34779708a8d6088b869d0efc6fe1c84e53b7b1 | 09994dda29f44b6c1f7f5c7c0b12f956fc9a42c1 | refs/heads/master | 2021-06-19T07:36:53.910760 | 2017-06-23T14:23:10 | 2017-06-23T14:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 14,243 | java | package com.boc.bocsoft.mobile.bocmobile.buss.wealthmanagement.mypositions.financialposition.ui;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.boc.bocsoft.mobile.bii.bus.wealthmanagement.model.PsnXpadProgressQuery.PsnXpadProgressQueryParams;
import com.boc.bocsoft.mobile.bii.bus.wealthmanagement.model.PsnXpadProgressQueryOutlay.PsnXpadProgressQueryOutlayParams;
import com.boc.bocsoft.mobile.bocmobile.R;
import com.boc.bocsoft.mobile.bocmobile.base.activity.MvpBussFragment;
import com.boc.bocsoft.mobile.bocmobile.base.utils.LogUtils;
import com.boc.bocsoft.mobile.bocmobile.base.widget.SpringPressageView.SpringRateDetailContent;
import com.boc.bocsoft.mobile.bocmobile.base.widget.emptyview.CommonEmptyView;
import com.boc.bocsoft.mobile.bocmobile.buss.wealthmanagement.mypositions.financialposition.model.PsnXpadProgressQueryOutlay.PsnXpadProgressQueryOutlayResModel;
import com.boc.bocsoft.mobile.bocmobile.buss.wealthmanagement.mypositions.financialposition.model.psnxpadprogressquery.PsnXpadProgressQueryResModel;
import com.boc.bocsoft.mobile.bocmobile.buss.wealthmanagement.mypositions.financialposition.presenter.FinancialPositionContract;
import com.boc.bocsoft.mobile.bocmobile.buss.wealthmanagement.mypositions.financialposition.presenter.FinancialTypeProgressQueryPresenter;
import com.boc.bocsoft.mobile.common.utils.PublicUtils;
import com.boc.bocsoft.mobile.common.utils.StringUtils;
import com.boc.bocsoft.mobile.framework.ui.BasePresenter;
import com.boc.bocsoft.mobile.framework.widget.TitleBarView;
import java.util.ArrayList;
import java.util.List;
/**
* 收益累进产品 -- 累计产品收益查询 - 预计年化收益率
* Created by cff on 2016/10/19.
*/
public class FinancialTypeProgressQueryFragment extends MvpBussFragment<FinancialTypeProgressQueryPresenter>
implements FinancialPositionContract.FinancialTypeProgressQueryView {
private static final String TAG = "FinancialTypeProgressQueryFragment";
private View rootView;
//产品头部介绍
private TextView progress_product;
//=============================变量======================================
//回话ID
// private String mConversationID;
//接收传送数据
// private PsnXpadProductBalanceQueryResModel banlanceDeta;
//当前请求页数
private int page = 0;
//数据总共条目数
private int queryNum_total;
//展示数据
private List<PsnXpadProgressQueryResModel.ListBean> progressList = new ArrayList<PsnXpadProgressQueryResModel.ListBean>();
//展示数据
private List<PsnXpadProgressQueryOutlayResModel.ListBean> progressOutlayList = new ArrayList<PsnXpadProgressQueryOutlayResModel.ListBean>();
//请求参数
private PsnXpadProgressQueryParams mParams = new PsnXpadProgressQueryParams();
//请求参数
private PsnXpadProgressQueryOutlayParams mParamsOutlay = new PsnXpadProgressQueryOutlayParams();
private SpringRateDetailContent spring_date;
private ScrollView scroll_no_emptyview;
/**
* 产品名称和code---默认为隐藏
*/
private LinearLayout title_product_name;
//空数据页面
private RelativeLayout rl_content_view_nodata;
//空数据页面
private CommonEmptyView view_no_data;
/**
* 产品名称
*/
private String ProdName;
/**
* 产品代码
*/
private String ProdCod;
/**
* 资金账号缓存标识
*/
private String BancAccountKey;
//是否登录 默认为未登录
private boolean isLogin = false;
float max;
@Override
protected View onCreateView(LayoutInflater mInflater) {
rootView = mInflater.inflate(R.layout.view_financialtype_progress_view, null);
return rootView;
}
@Override
protected String getTitleValue() {
return getString(R.string.boc_position_expected_annual_return_rate);
}
@Override
protected boolean getTitleBarRed() {
return false;
}
@Override
protected View getTitleBarView() {
TitleBarView titleBarView = (TitleBarView) super.getTitleBarView();
titleBarView.setRightButton(null, null);
return titleBarView;
}
@Override
public void initView() {
progress_product = (TextView) rootView.findViewById(R.id.progress_product);
scroll_no_emptyview = (ScrollView) rootView.findViewById(R.id.scroll_no_emptyview);
spring_date = (SpringRateDetailContent) rootView.findViewById(R.id.spring_date);
title_product_name = (LinearLayout) rootView.findViewById(R.id.title_productnameandcode);
rl_content_view_nodata = (RelativeLayout) rootView.findViewById(R.id.rl_content_view_nodata);
view_no_data = (CommonEmptyView) rootView.findViewById(R.id.view_no_data);
scroll_no_emptyview.setVisibility(View.GONE);
}
@Override
public void initData() {
progress_product.setText(ProdName + " (" + ProdCod + ")");
// for(int i = 1;i<=10;i++){
// spring_date.addTextContent("100",i*10+"",i+"-"+i*10+"天");
// }
//
if (isLogin) {
//已登录 获取年华收益率详情
showLoadingDialog();
getPresenter().getPSNCreatConversation();
} else {
//未登录 获取年华收益率详情
getPsnXpadProgressQueryOutlay(page);
// getPresenter().getPsnXpadProgressQueryOutlay();
}
}
@Override
public void setListener() {
}
/**
* 为预计年化收益率设置数据
*
* @param ProdName
* @param ProdCod
* @param BancAccountKey
* @param isLogin
*/
public void setReferDetail(String ProdName,
String ProdCod, String BancAccountKey, boolean isLogin) {
this.ProdName = ProdName;
this.ProdCod = ProdCod;
this.BancAccountKey = BancAccountKey;
this.isLogin = isLogin;
}
/**
* 获取会话ID--成功
*
* @param conversationId
*/
@Override
public void obtainConversationSuccess(String conversationId) {
LogUtils.i(TAG, "-------->获取会话ID--成功!");
getPsnXpadProgressQuery(page, conversationId);
}
/**
* 获取会话ID--失败
*/
@Override
public void obtainConversationFail() {
LogUtils.i(TAG, "-------->获取会话ID--失败!");
closeProgressDialog();
}
/**
* 请求收益率查询成功
*
* @param resModel
*/
@Override
public void obtainPsnXpadProgressQuerySuccess(PsnXpadProgressQueryResModel resModel) {
LogUtils.i(TAG, "----------请求收益率查询成功----------");
closeProgressDialog();
handlerPsnXpadProgressQuerySuccess(resModel);
}
/**
* 请求收益率查询失败
*/
@Override
public void obtainPsnXpadProgressQueryFault() {
LogUtils.i(TAG, "----------请求收益率查询失败----------");
closeProgressDialog();
rl_content_view_nodata.setVisibility(View.VISIBLE);
view_no_data.setEmptyTips("暂无预期年化收益率", R.drawable.no_result);
scroll_no_emptyview.setVisibility(View.GONE);
}
/**
* 4.53 053 PsnXpadProgressQueryOutlay 登录前累进产品收益率查询
* 成功
*
* @param resModel
*/
@Override
public void obtainPsnXpadProgressQueryOutlaySuccess(PsnXpadProgressQueryOutlayResModel resModel) {
LogUtils.i(TAG, "----------登录前累进产品收益率查询成功----------");
closeProgressDialog();
handlerPsnXpadProgressQueryOutlaySuccess(resModel);
}
/**
* 4.53 053 PsnXpadProgressQueryOutlay 登录前累进产品收益率查询
* 失败
*/
@Override
public void obtainPsnXpadProgressQueryOutlayFault() {
LogUtils.i(TAG, "----------登录前累进产品收益率查询失败----------");
closeProgressDialog();
rl_content_view_nodata.setVisibility(View.VISIBLE);
view_no_data.setEmptyTips("暂无预期年化收益率", R.drawable.no_result);
scroll_no_emptyview.setVisibility(View.GONE);
}
@Override
public void setPresenter(BasePresenter presenter) {
}
@Override
protected FinancialTypeProgressQueryPresenter initPresenter() {
return new FinancialTypeProgressQueryPresenter(this);
}
//===========================自定义方法===========================
/**
* 网络数据回调处理
*
* @param resModel
*/
private void handlerPsnXpadProgressQuerySuccess(PsnXpadProgressQueryResModel resModel) {
queryNum_total = Integer.parseInt(resModel.getRecordNumber());
if (0 == page) {
progressList = resModel.getList();
} else {
progressList.addAll(resModel.getList());
}
if (PublicUtils.isEmpty(progressList)) {
rl_content_view_nodata.setVisibility(View.VISIBLE);
view_no_data.setEmptyTips("暂无预期年化收益率", R.drawable.no_result);
scroll_no_emptyview.setVisibility(View.GONE);
} else {
scroll_no_emptyview.setVisibility(View.VISIBLE);
rl_content_view_nodata.setVisibility(View.GONE);
for (int i = 0; i < progressList.size(); i++) {
max = Float.valueOf(progressList.get(0).getYearlyRR());
if (max <= Float.valueOf(progressList.get(i).getYearlyRR())) {
max = Float.valueOf(progressList.get(i).getYearlyRR());
}
}
for (int i = 0; i < progressList.size(); i++) {
PsnXpadProgressQueryResModel.ListBean model = progressList.get(i);
if (!StringUtils.isEmptyOrNull(model.getMaxDays())&&!"-1".equalsIgnoreCase(model.getMaxDays())) {
spring_date.addTextContent(String.valueOf(max),
model.getYearlyRR(), model.getMinDays() + "-" + model.getMaxDays() + "天");
} else {
spring_date.addTextContent(String.valueOf(max),
model.getYearlyRR(), model.getMinDays() + "天及以上");
}
}
// for(int i = 0; i < 5; i++){
// spring_date.addTextContent( "15.0" ,String.valueOf(i+6.0),"1-7tian");
//
// }
}
}
/**
* 4.53 053 PsnXpadProgressQueryOutlay 登录前累进产品收益率查询
*
* @param resModel
*/
private void handlerPsnXpadProgressQueryOutlaySuccess(PsnXpadProgressQueryOutlayResModel resModel) {
queryNum_total = Integer.parseInt(resModel.getRecordNumber());
if (0 == page) {
progressOutlayList = resModel.getList();
} else {
progressOutlayList.addAll(resModel.getList());
}
if (PublicUtils.isEmpty(progressOutlayList)) {
rl_content_view_nodata.setVisibility(View.VISIBLE);
view_no_data.setEmptyTips("暂无预期年化收益率", R.drawable.no_result);
scroll_no_emptyview.setVisibility(View.GONE);
} else {
scroll_no_emptyview.setVisibility(View.VISIBLE);
rl_content_view_nodata.setVisibility(View.GONE);
for (int i = 0; i < progressOutlayList.size(); i++) {
max = Float.valueOf(progressOutlayList.get(0).getYearlyRR());
if (max <= Float.valueOf(progressOutlayList.get(i).getYearlyRR())) {
max = Float.valueOf(progressOutlayList.get(i).getYearlyRR());
}
}
for (int i = 0; i < progressOutlayList.size(); i++) {
PsnXpadProgressQueryOutlayResModel.ListBean model = progressOutlayList.get(i);
// if (null != model.getMinDays()) {
// spring_date.addTextContent(progressOutlayList.get(progressOutlayList.size() - 1).getYearlyRR(),
// model.getYearlyRR(), model.getMinDays() + "-" + model.getMaxDays() + "天");
// } else {
// spring_date.addTextContent(progressOutlayList.get(progressOutlayList.size() - 1).getYearlyRR(),
// model.getYearlyRR(), model.getMaxDays() + "天及以上");
// }
if (!StringUtils.isEmptyOrNull(model.getMaxDays())&&!"-1".equalsIgnoreCase(model.getMaxDays())) {
spring_date.addTextContent(String.valueOf(max),
model.getYearlyRR(), model.getMinDays() + "-" + model.getMaxDays() + "天");
} else {
spring_date.addTextContent(String.valueOf(max),
model.getYearlyRR(), model.getMinDays() + "天及以上");
}
}
}
}
/**
* 登陆后
*
* @param page
* @param conversationId
*/
private void getPsnXpadProgressQuery(int page, String conversationId) {
mParams.setConversationId(conversationId);
mParams.setAccountKey(BancAccountKey);
mParams.setPageSize("50");
mParams.set_refresh("true");
mParams.setCurrentIndex(page * 50 + "");
mParams.setProductCode(ProdCod);
getPresenter().getPsnXpadProgressQuery(mParams);
}
/**
* 登陆前
*/
private void getPsnXpadProgressQueryOutlay(int page) {
mParamsOutlay.setProductCode(ProdCod);
mParamsOutlay.setPageSize("50");
mParamsOutlay.set_refresh("true");
mParamsOutlay.setCurrentIndex(page * 50 + "");
getPresenter().getPsnXpadProgressQueryOutlay(mParamsOutlay);
}
/**
* 判断是否已加载所有数据
*
* @return true 已经全部加载;false 没有全部加载
*/
private boolean isLoadAllRecord() {
int loadnum = progressList == null ? 0 : progressList.size();
int totalnum = queryNum_total;
if (loadnum >= totalnum) {
return true;
} else {
return false;
}
}
}
| [
"[email protected]"
] | |
a4d9ebc269cd48d078ac5cb21c938d88b40d3963 | 6c967830481b8a71655059efa8596e7a2aa2f8dc | /menu/src/com/example/menu/notice/NoticeAdapter.java | 7d5d3314d9fb2c92de23f31e768f7a835dc7067e | [] | no_license | fordream/Link_Android | f243216e62eef4acf80e1fac862fbe29008f4c74 | 12d2492f8f700906ccf55fd89eb7d392c4d67434 | refs/heads/master | 2021-01-18T05:07:53.928962 | 2015-11-28T07:57:24 | 2015-11-28T07:57:24 | 47,870,658 | 1 | 0 | null | 2015-12-12T08:34:47 | 2015-12-12T08:34:47 | null | UTF-8 | Java | false | false | 2,675 | java | package com.example.menu.notice;
import java.util.ArrayList;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
public class NoticeAdapter extends BaseExpandableListAdapter {
ArrayList<DataNoticeTitle> items = new ArrayList<DataNoticeTitle>();
Context mContext;
public void add(String groupKey, String content)
{
DataNoticeTitle newTitle = null;
if(newTitle == null)
{
newTitle = new DataNoticeTitle();
newTitle.title = groupKey;
items.add(newTitle);
}
if(newTitle != null)
{
DataNoticeContent newContent = new DataNoticeContent();
newContent.content = content;
newTitle.content.add(newContent);
}
notifyDataSetChanged();
}
public NoticeAdapter(Context context) {
mContext = context;
}
@Override
public int getGroupCount() {
// TODO Auto-generated method stub
return items.size();
}
@Override
public int getChildrenCount(int groupPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition).content.size();
}
@Override
public Object getGroup(int groupPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return items.get(groupPosition).content.get(childPosition);
}
@Override
public long getGroupId(int groupPosition) {
// TODO Auto-generated method stub
return ((long)groupPosition) << 32|0xffffffff;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return ((long)groupPosition) << 32|(long)childPosition;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
ViewNoticeTitle view;
if(convertView == null)
{ view = new ViewNoticeTitle(mContext); }
else
{ view = (ViewNoticeTitle)convertView; }
view.setNoticTitle(items.get(groupPosition));
return view;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
ViewNoticeContent view;
if(convertView == null)
{ view = new ViewNoticeContent(mContext); }
else
{ view = (ViewNoticeContent)convertView; }
view.setNoticeContent(items.get(groupPosition).content.get(childPosition));
return view;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
// TODO Auto-generated method stub
return true;
}
}
| [
"[email protected]"
] | |
79757c4c1351732e8a7625b148ec790794885abe | 7af846ccf54082cd1832c282ccd3c98eae7ad69a | /ftmap/src/main/java/taxi/nicecode/com/ftmap/generated/package_31/Foo10.java | 756fd22f9e78dd447135edbd38ec058e168cd1b4 | [] | no_license | Kadanza/TestModules | 821f216be53897d7255b8997b426b359ef53971f | 342b7b8930e9491251de972e45b16f85dcf91bd4 | refs/heads/master | 2020-03-25T08:13:09.316581 | 2018-08-08T10:47:25 | 2018-08-08T10:47:25 | 143,602,647 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 267 | java | package taxi.nicecode.com.ftmap.generated.package_31;
public class Foo10 {
public void foo0(){
new Foo9().foo5();
}
public void foo1(){
foo0();
}
public void foo2(){
foo1();
}
public void foo3(){
foo2();
}
public void foo4(){
foo3();
}
public void foo5(){
foo4();
}
} | [
"1"
] | 1 |
f5a1fe2d8bb6aec67ebf05178f3514ac399bf28d | 8306789663a11368acc6e51803aec1fa8ccde900 | /CommonListeners/src/main/java/me/elvis/common/listeners/ServletContextAttributeListener.java | bceb26f8b40b2cc909761dad87cfcac3529b8c62 | [] | no_license | zjs1224522500/JavaWebUtils | b436c87a58b1fff88aea339062c2baf5da23f0ff | ae0240397367a9e9211e979e1045971101862869 | refs/heads/master | 2022-12-24T21:52:03.151355 | 2021-04-04T09:48:06 | 2021-04-04T09:48:06 | 108,950,592 | 2 | 0 | null | 2022-12-10T06:22:03 | 2017-10-31T05:42:36 | Java | UTF-8 | Java | false | false | 605 | java | package me.elvis.common.listeners;
import javax.servlet.ServletContextAttributeEvent;
/**
* Version:v1.0 (description: 用于监听context中属性的变化,对应的被监听对象执行add/update/remove ) Date:2017/11/22 0022 Time:12:31
*/
public class ServletContextAttributeListener implements
javax.servlet.ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent scae) {
}
@Override
public void attributeRemoved(ServletContextAttributeEvent scae) {
}
@Override
public void attributeReplaced(ServletContextAttributeEvent scae) {
}
}
| [
"[email protected]"
] | |
268fe1e777120ed5480336d5309b91d1ca086e96 | 179f41638aa9e3ba18d64a4ed01bb4d88fa79c5b | /src/Client/ClientSender.java | 30e8123b713917e8ef4048ea8efe164ef7438c06 | [] | no_license | AnnMir/Rest_chat | 352f36d7fc2e3a07eea81ff87b51294a7a8ef4b0 | 443452567831ae8bc73a5777798e904f7b608266 | refs/heads/master | 2020-04-08T01:34:51.671338 | 2018-11-30T13:46:38 | 2018-11-30T13:46:38 | 158,900,828 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,459 | java | package Client;
import Common.Data;
import org.json.simple.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.concurrent.LinkedBlockingQueue;
import static Common.Commons.*;
public class ClientSender implements Runnable {
private BufferedWriter bufferedWriter;
private String method;
private LinkedBlockingQueue<Data> toSendQueue;
void setToken(String token) {
this.token = token;
}
private String token;
ClientSender(final Socket socket) {
try {
method = "default";
toSendQueue = new LinkedBlockingQueue<>();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
void work(final String methodName, final String message) {
try {
toSendQueue.put(new Data(methodName, message));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
Data data;
try {
data = toSendQueue.take();
executeMethod(data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void executeMethod(Data data) {
method = data.getNameOfMethod();
String nameOrMessage = data.getMessage();
switch (method) {
case KEY_POST_LOGIN: {
sendPostLogin(nameOrMessage);
method = "default";
break;
}
case KEY_POST_LOGOUT: {
sendPostLogout();
method = "default";
break;
}
case KEY_POST_MESSAGE: {
sendPostMessage(nameOrMessage);
method = "default";
break;
}
case KEY_GET_ONE_USER: {
sendGetOneUser(nameOrMessage);
method = "default";
break;
}
case KEY_GET_ALL_USERS: {
sendGetAllUsers();
method = "default";
break;
}
case KEY_GET_MESSAGES: {
sendGetAllMessages(nameOrMessage);
method = "default";
break;
}
default: {
break;
}
}
}
private void sendPostMessage(final String msg) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", msg);
String message = "POST /"+KEY_POST_MESSAGE+ " HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "Content-Type: application/json " + "\r\n"
+ "\r\n"
+ jsonObject.toJSONString() + "\r\n";
System.out.println("post message: "+message);
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPostLogin(final String name) {
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("username", name);
String message = "POST /"+KEY_POST_LOGIN+" HTTP/1.1" + "\r\n"
+ "Content-Type: application/json" + "\r\n"
+ "\r\n"
+ jsonObject.toJSONString() + "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendPostLogout() {
try {
String message = "POST /"+KEY_POST_LOGOUT +" HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
System.out.println(message);
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetOneUser(final String nameOrMessage) {
try {
String message = "GET /"+KEY_GET_ONE_USER+nameOrMessage + " HTTP/1.1\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetAllUsers() {
try {
String message = "GET /"+ KEY_GET_ALL_USERS+" HTTP/1.1" + "\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendGetAllMessages(String numberOfMessage) {
try {
String message = "GET /"+KEY_GET_MESSAGES+"?offset=" + numberOfMessage + "&count=10" + " HTTP/1.1\r\n"
+ "Authorization: Token " + token + "\r\n"
+ "\r\n";
bufferedWriter.write(message);
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| [
"[email protected]"
] | |
9efd2d467de140d1a85282c04a42c327948c7b11 | eb5f5353f49ee558e497e5caded1f60f32f536b5 | /javax/management/NotificationEmitter.java | 6764d4e25ec436944797df7b806242ac3d27178e | [] | no_license | mohitrajvardhan17/java1.8.0_151 | 6fc53e15354d88b53bd248c260c954807d612118 | 6eeab0c0fd20be34db653f4778f8828068c50c92 | refs/heads/master | 2020-03-18T09:44:14.769133 | 2018-05-23T14:28:24 | 2018-05-23T14:28:24 | 134,578,186 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 505 | java | package javax.management;
public abstract interface NotificationEmitter
extends NotificationBroadcaster
{
public abstract void removeNotificationListener(NotificationListener paramNotificationListener, NotificationFilter paramNotificationFilter, Object paramObject)
throws ListenerNotFoundException;
}
/* Location: C:\Program Files (x86)\Java\jre1.8.0_151\lib\rt.jar!\javax\management\NotificationEmitter.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 0.7.1
*/ | [
"[email protected]"
] | |
080b1ad6b12e10d8c1daf12d6672240948b11f50 | 7744e94b372687a1467df23acc7e498db6c7d4cd | /src/main/java/com/linwu/yuanqi/threadtest/TheradTest.java | abf7543453d0dc673cd202549d55d6e647a7dbe1 | [] | no_license | Mrwuyi00/yuanqi | e42f99eb9a6ed4169d0acc5f04b693500356a3dc | 23c2df72899e3f9b8c48e17bd89e0d35ce90c634 | refs/heads/master | 2021-01-02T08:48:55.425277 | 2017-12-29T09:32:19 | 2017-12-29T09:32:19 | 99,068,988 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 133 | java | package com.linwu.yuanqi.threadtest;
/**
* Created by linwu on 11/8/2017.
*/
public abstract class TheradTest extends Thread{
}
| [
"[email protected]"
] | |
a5e7675b782340ddb993d880442c459610bf7f7a | 59b6d97d8a053697becba4418a83ed4ffc855d6b | /src/main/java/JDBC/PsRolePermissionDao.java | 76923d8ec47729958722a491e7455d450affe11d | [] | no_license | HanaSakuI/shixun | ff0ead2904f22b342cbb6a1926c13deae2854b55 | 7533538468a1c47fbee337e4f4ab65409ef03ff4 | refs/heads/master | 2023-06-20T09:28:52.083889 | 2021-07-22T07:29:32 | 2021-07-22T07:29:32 | 385,191,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,199 | java | package JDBC;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @author yt
* 实体类PsRolePermission的Dao
*/
public class PsRolePermissionDao extends BaseDao {
/**
* 根据roleId获取functionCode
*
* @param roleId 角色ID
* @return functionCode
*/
public String getFunctionCodeByRoleId(String roleId) throws SQLException {
String sql = "SELECT * FROM ps_role_permission where roleId = '" + roleId + "'";
String functionCode = "";
ResultSet rs = executeQuery(sql);
while (rs.next()) {
functionCode = rs.getString("functionCode");
}
closeAll();
return functionCode;
}
/**
* 根据roleId修改functionCode
*
* @param roleId 角色ID
* @param functionCode 权限编号
* @return row
*/
public int updateFunctionCodeByRoleId(String roleId, String functionCode) {
String sql = "update ps_role_permission set functionCode = ? where roleId = '" + roleId + "'";
Object[] param = {
functionCode
};
int row = executeUpdate(sql, param);
closeAll();
return row;
}
}
| [
"[email protected]"
] | |
73dcdb9c209f349557d136b0e1c8a1d4be08092a | 6974e49496049f3cd8033c2c7712bb9c95172263 | /src/main/java/presentation/Bootstrap.java | 9d70dac98152173035dc2b3dfdfbb7bf2316a547 | [] | no_license | alot210/praktikum.webeng | 17ea11159711e9ef4b7fe6a321d5fc962c1b07df | 2faede28bd934ea5487ae67667cb7c2be8c04bfc | refs/heads/master | 2020-03-18T17:47:50.664675 | 2018-05-27T13:58:19 | 2018-05-27T13:58:19 | 135,051,277 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,248 | java | package presentation;
import businesslogic.ArticleManager;
import transferobject.Article;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
@WebServlet(urlPatterns ={ "/Bootstrap" })
public class Bootstrap extends HttpServlet {
public Bootstrap() {
super();
}
public void init() throws ServletException {
super.init();
ArticleManager manager = new ArticleManager();
manager.createArticleTable();
manager.createArticle(1, "Kaffee", 2, 10);
manager.createArticle(2, "Tee", 2, 20);
manager.createArticle(3, "Mate", 3, 8);
manager.createArticle(4, "Matcha", 5, 12);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
ArticleManager manager = new ArticleManager();
ArrayList<Article> a = manager.getArticle();
writer.println("<!doctype html>");
writer.println("<html>");
writer.println("<head><title>2. Praktikum WebEng</title></head>");
writer.println("<body>");
writer.println("<h3>Artikel im Shop</h3><br>");
writer.println("<table width = \"50%\" border = \"1 solid\" align = \"center\">");
writer.println("<tr>");
writer.println("<th>ID </th>");
writer.println("<th>Name </th>");
writer.println("<th>Price </th>");
writer.println("<th>Amount </th>");
writer.println("</tr>");
for(Article article : a ) {
writer.println("<tr>");
writer.println("<td>"+article.id+"</td>");
writer.println("<td>"+article.name+"</td>");
writer.println("<td>"+article.price+"</td>");
writer.println("<td>"+article.amount+"</td>");
writer.println("</tr>");
}
writer.println("</table>");
writer.println("<body>");
writer.println("</html>");
writer.close();
}
}
| [
"[email protected]"
] | |
1f19de836f6588354b89be1dfb430dbc9c7942cf | 0b0dbdc0d12c8eb60fdfbd48c4afc37147d0082e | /itests/standalone/basic/src/test/java/org/wildfly/camel/test/mail/MailIntegrationCDITest.java | f7b3fba086d038d30b76b4dda27e82a0f9ae6a4a | [
"Apache-2.0"
] | permissive | ppalaga/wildfly-camel | f99a35e36f9c80b8251d44ee1330c912a2916cb6 | 7376bb102149939da99063215c3f186424681fbc | refs/heads/master | 2021-07-09T01:44:01.018465 | 2019-06-21T08:46:17 | 2019-06-21T08:47:04 | 101,184,017 | 0 | 1 | Apache-2.0 | 2018-05-25T13:17:42 | 2017-08-23T13:36:21 | Java | UTF-8 | Java | false | false | 5,606 | java | /*
* #%L
* Wildfly Camel :: Testsuite
* %%
* Copyright (C) 2013 - 2014 RedHat
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.wildfly.camel.test.mail;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.as.arquillian.api.ServerSetup;
import org.jboss.as.arquillian.api.ServerSetupTask;
import org.jboss.as.arquillian.container.ManagementClient;
import org.jboss.dmr.ModelNode;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.common.utils.DMRUtils;
import org.wildfly.camel.test.mail.subA.MailSessionProducer;
import org.wildfly.extension.camel.CamelAware;
import org.wildfly.extension.camel.CamelContextRegistry;
@CamelAware
@ServerSetup({MailIntegrationCDITest.MailSessionSetupTask.class})
@RunWith(Arquillian.class)
public class MailIntegrationCDITest {
private static final String GREENMAIL_WAR = "greenmail.war";
@ArquillianResource
CamelContextRegistry contextRegistry;
static class MailSessionSetupTask implements ServerSetupTask {
@Override
public void setup(ManagementClient managementClient, String s) throws Exception {
ModelNode batchNode = DMRUtils.batchNode()
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-smtp", "add(host=localhost, port=10025)")
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-pop3", "add(host=localhost, port=10110)")
.addStep("subsystem=mail/mail-session=greenmail", "add(jndi-name=java:jboss/mail/greenmail)")
.addStep("subsystem=mail/mail-session=greenmail/server=smtp", "add(outbound-socket-binding-ref=mail-greenmail-smtp, username=user1, password=password)")
.addStep("subsystem=mail/mail-session=greenmail/server=pop3", "add(outbound-socket-binding-ref=mail-greenmail-pop3, username=user2, password=password2)")
.build();
managementClient.getControllerClient().execute(batchNode);
}
@Override
public void tearDown(ManagementClient managementClient, String s) throws Exception {
ModelNode batchNode = DMRUtils.batchNode()
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-smtp", "remove")
.addStep("socket-binding-group=standard-sockets/remote-destination-outbound-socket-binding=mail-greenmail-pop3", "remove")
.addStep("subsystem=mail/mail-session=greenmail", "remove")
.addStep("subsystem=mail/mail-session=greenmail/server=smtp", "remove")
.addStep("subsystem=mail/mail-session=greenmail/server=pop3", "remove")
.build();
managementClient.getControllerClient().execute(batchNode);
}
}
@Deployment(order = 1, testable = false, name = GREENMAIL_WAR)
public static WebArchive createGreenmailDeployment() {
File mailDependencies = Maven.configureResolverViaPlugin().
resolve("com.icegreen:greenmail-webapp:war:1.4.0").
withoutTransitivity().
asSingleFile();
return ShrinkWrap.createFromZipFile(WebArchive.class, mailDependencies);
}
@Deployment(order = 2)
public static JavaArchive createDeployment() throws IOException {
final JavaArchive archive = ShrinkWrap.create(JavaArchive.class, "camel-mail-cdi-tests.jar");
archive.addPackage(MailSessionProducer.class.getPackage());
archive.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
return archive;
}
@Test
public void testMailEndpointWithCDIContext() throws Exception {
CamelContext camelctx = contextRegistry.getCamelContext("camel-mail-cdi-context");
Assert.assertNotNull("Camel context not null", camelctx);
MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
mockEndpoint.setExpectedMessageCount(1);
Map<String, Object> mailHeaders = new HashMap<>();
mailHeaders.put("from", "user1@localhost");
mailHeaders.put("to", "user2@localhost");
mailHeaders.put("message", "Hello Kermit");
ProducerTemplate template = camelctx.createProducerTemplate();
template.requestBodyAndHeaders("direct:start", null, mailHeaders);
mockEndpoint.assertIsSatisfied(5000);
}
}
| [
"[email protected]"
] | |
8ec2124c77ec9107886b46873a2677e13f019ffa | 8140b0a57296a0c6c784de2d64fc71574e00dcb8 | /Evaluator/src/main/java/org/kakaobank/kafka/ConsumerCreator.java | 86f2b78f86771bb6abf8f5ec29849b39383da1ec | [] | no_license | deviscreen/FDS01 | c0468179d08b28ab84ede339c73450e86102be15 | 8d02383c570930fb6ec5248cee87cfb439cfc176 | refs/heads/master | 2022-12-05T11:38:42.563712 | 2020-08-25T15:00:44 | 2020-08-25T15:00:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,333 | java | package org.kakaobank.kafka;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.LongDeserializer;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.Collections;
import java.util.Properties;
public class ConsumerCreator {
public static Consumer<String, String> createConsumer() {
Properties props = new Properties();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, IKafkaConfig.KAFKA_BROKERS);
props.put(ConsumerConfig.GROUP_ID_CONFIG, IKafkaConfig.GROUP_ID_CONFIG);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, IKafkaConfig.MAX_POLL_RECORDS);
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, IKafkaConfig.OFFSET_RESET_EALIER);
Consumer<String, String> consumer = new KafkaConsumer<>(props);
consumer.subscribe(Collections.singletonList(IKafkaConfig.TOPIC_NAME));
return consumer;
}
}
| [
"[email protected]"
] | |
4160200eadc60afd8c253a97ea10fdcb57164700 | a4a51084cfb715c7076c810520542af38a854868 | /src/main/java/com/shopee/protocol/shop/CoinGlobalExtInfo.java | 349c2c567689560d88af98acc6cbcaf3bb5cbe06 | [] | no_license | BharathPalanivelu/repotest | ddaf56a94eb52867408e0e769f35bef2d815da72 | f78ae38738d2ba6c9b9b4049f3092188fabb5b59 | refs/heads/master | 2020-09-30T18:55:04.802341 | 2019-12-02T10:52:08 | 2019-12-02T10:52:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,963 | java | package com.shopee.protocol.shop;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoField;
import java.util.Collections;
import java.util.List;
public final class CoinGlobalExtInfo extends Message {
public static final List<Integer> DEFAULT_RULE_RANK_IDS = Collections.emptyList();
private static final long serialVersionUID = 0;
@ProtoField(label = Message.Label.REPEATED, tag = 1, type = Message.Datatype.INT32)
public final List<Integer> rule_rank_ids;
public CoinGlobalExtInfo(List<Integer> list) {
this.rule_rank_ids = immutableCopyOf(list);
}
private CoinGlobalExtInfo(Builder builder) {
this(builder.rule_rank_ids);
setBuilder(builder);
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CoinGlobalExtInfo)) {
return false;
}
return equals((List<?>) this.rule_rank_ids, (List<?>) ((CoinGlobalExtInfo) obj).rule_rank_ids);
}
public int hashCode() {
int i = this.hashCode;
if (i == 0) {
List<Integer> list = this.rule_rank_ids;
i = list != null ? list.hashCode() : 1;
this.hashCode = i;
}
return i;
}
public static final class Builder extends Message.Builder<CoinGlobalExtInfo> {
public List<Integer> rule_rank_ids;
public Builder() {
}
public Builder(CoinGlobalExtInfo coinGlobalExtInfo) {
super(coinGlobalExtInfo);
if (coinGlobalExtInfo != null) {
this.rule_rank_ids = CoinGlobalExtInfo.copyOf(coinGlobalExtInfo.rule_rank_ids);
}
}
public Builder rule_rank_ids(List<Integer> list) {
this.rule_rank_ids = checkForNulls(list);
return this;
}
public CoinGlobalExtInfo build() {
return new CoinGlobalExtInfo(this);
}
}
}
| [
"[email protected]"
] | |
f2a449245fb64dcfd246ac28d043b8a0a8f584ef | 0168ec3bec7e8475fb64df897d11be3fde1e2e6e | /src/main/java/com/example/demo/HomeController.java | d2628e6dbf8fbbeee25e998252c287fa40e6664f | [] | no_license | DerekLorimer/SpringCourse | 3c3236a1edacbd0feb261308832b8c24f61d7798 | c0eea131bba1f6a6a3367a4027959027b25d3411 | refs/heads/master | 2023-07-26T03:21:18.169690 | 2021-09-04T06:32:03 | 2021-09-04T06:32:03 | 402,982,591 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 886 | java | package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class HomeController {
@Autowired
PersonRepo repo;
@RequestMapping("home")
public ModelAndView home(@RequestParam("name") String name) {
ModelAndView mv = new ModelAndView();
System.out.println("hello ModelAndView " + name);
mv.addObject("name", name);
mv.setViewName("home");
return mv;
}
@RequestMapping("addPerson")
public ModelAndView addPerson(Person person) {
ModelAndView mv = new ModelAndView();
mv.setViewName("home");
repo.save(person);
return mv;
}
}
| [
"[email protected]"
] | |
af308caf6397e710a513753f2d38193fef68692d | 4537423a5e50edf77bf48b2e52b1b73c3fc5d696 | /tokamak-core/src/main/java/com/wrmsr/tokamak/core/tree/node/TAliasableRelation.java | d039248d497616de193a0110851a387bfb061cb7 | [
"Apache-2.0"
] | permissive | wrmsr/tokamak | 5a662ec6ee2b34321f772a881d3bfe4f413da82a | 3ebf3395c5bb78b80e0445199958cb81f4cf9be8 | refs/heads/master | 2022-12-22T13:27:58.158522 | 2021-03-29T21:03:00 | 2021-03-29T21:03:00 | 191,827,182 | 3 | 0 | Apache-2.0 | 2022-12-12T21:43:15 | 2019-06-13T20:14:55 | Java | UTF-8 | Java | false | false | 676 | java | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wrmsr.tokamak.core.tree.node;
public abstract class TAliasableRelation
extends TRelation
{
}
| [
"[email protected]"
] | |
3eeaf7eca9adf37e3b36d3dc930b463bde8c1250 | ced2a6643a41e167bdacec5d9d9533c269476fa0 | /java/sortings/bubblesort/BubbleSort.java | 0bbb5c110da3494dd49079c701ec1da7bf505910 | [] | no_license | atsuya/algorithms | 7c157996d949e8da37f3475aede74adb2fa58ded | 1e3e708dd39cc8f55445ae59818435a5c2028f7d | refs/heads/master | 2021-06-06T18:28:55.377542 | 2021-06-06T06:13:43 | 2021-06-06T06:13:43 | 17,336,318 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,218 | java | import java.util.Vector;
public class BubbleSort {
public BubbleSort() {
}
public void sort(Vector<Integer> list) {
boolean swapped;
do {
swapped = false;
for (int index = 0; index < list.size(); index++) {
if (index + 1 < list.size()) {
if (list.get(index) > list.get(index + 1)) {
Integer temp = list.get(index);
list.set(index, list.get(index + 1));
list.set(index + 1, temp);
swapped = true;
}
}
}
} while (swapped);
}
public void print(Vector<Integer> list) {
for (Integer value : list) {
System.out.printf("%d ", value.intValue());
}
System.out.println();
}
public static void main(String[] args) {
Vector<Integer> list = new Vector<Integer>();
list.add(new Integer(8));
list.add(new Integer(22));
list.add(new Integer(2));
list.add(new Integer(40));
list.add(new Integer(9));
list.add(new Integer(11));
list.add(new Integer(2));
list.add(new Integer(15));
list.add(new Integer(4));
BubbleSort bubbleSort = new BubbleSort();
bubbleSort.print(list);
bubbleSort.sort(list);
bubbleSort.print(list);
}
}
| [
"[email protected]"
] | |
142df89b778a9e8d87e1a3f2d0ab6d067b072572 | 55cda70a591be9e15d972aac5b12203433105386 | /4. Microservices/Microservices_O8ITO8_Movies/src/main/java/movies/MovieDirectorComparator.java | 0b0ade377b7b3094e4b1e4986f27e12d48f16534 | [] | no_license | wkrea/soi | 4c881eaacd1a20b8f329cbdc77c710ee8a0c4477 | 4c9b785ab6074bcd388f0ecd27ad450c6598ea7b | refs/heads/master | 2021-12-14T22:55:13.701574 | 2017-06-18T18:59:36 | 2017-06-18T18:59:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 245 | java | package movies;
import java.util.Comparator;
public class MovieDirectorComparator implements Comparator<Movie> {
@Override
public int compare(Movie a, Movie b) {
return (a.getDirector().compareTo(b.getDirector()) >= 0) ? 1 : -1;
}
}
| [
"[email protected]"
] | |
6e254a41ed3446b5a19247bd1a7dc79ffa247428 | 78897cc7463a2b79d60d2c087a34693b37be9b60 | /Proyecto_A_CreditoEJB/ejbModule/proyecto/model/entities/Transaccion.java | 63789b99569f17b82c16569ebedd9c35a0db4127 | [] | no_license | QuilismalM/AhorroyCredito | 0583274a2e44c5d92017e45c30fc91a138e38697 | 3926f720888e1f68c5a965cf41f5747ae7df1d37 | refs/heads/master | 2020-06-14T04:26:06.652652 | 2019-07-16T00:10:33 | 2019-07-16T00:10:33 | 194,898,812 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,734 | java | package proyecto.model.entities;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigDecimal;
import java.util.Date;
/**
* The persistent class for the transaccion database table.
*
*/
@Entity
@Table(name="transaccion")
@NamedQuery(name="Transaccion.findAll", query="SELECT t FROM Transaccion t")
public class Transaccion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@SequenceGenerator(name="TRANSACCION_IDTRANSACCION_GENERATOR", sequenceName="SEQ_TRANSACCION",allocationSize = 1)
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TRANSACCION_IDTRANSACCION_GENERATOR")
@Column(name="id_transaccion", unique=true, nullable=false)
private Integer idTransaccion;
@Column(name="cuenta_destino")
private Integer cuentaDestino;
@Temporal(TemporalType.DATE)
@Column(name="fecha_transaccion", nullable=false)
private Date fechaTransaccion;
@Column(name="monto_transaccion", precision=10, scale=2)
private BigDecimal montoTransaccion;
@Column(name="saldo_transaccion", nullable=false)
private Integer saldoTransaccion;
//bi-directional many-to-one association to CuentaCliente
@ManyToOne
@JoinColumn(name="nro_cuenta_cl", nullable=false)
private CuentaCliente cuentaCliente;
//bi-directional many-to-one association to TipoTransaccion
@ManyToOne
@JoinColumn(name="id_tipo_transaccion", nullable=false)
private TipoTransaccion tipoTransaccion;
public Transaccion() {
}
public Integer getIdTransaccion() {
return this.idTransaccion;
}
public void setIdTransaccion(Integer idTransaccion) {
this.idTransaccion = idTransaccion;
}
public Integer getCuentaDestino() {
return this.cuentaDestino;
}
public void setCuentaDestino(Integer cuentaDestino) {
this.cuentaDestino = cuentaDestino;
}
public Date getFechaTransaccion() {
return this.fechaTransaccion;
}
public void setFechaTransaccion(Date fechaTransaccion) {
this.fechaTransaccion = fechaTransaccion;
}
public BigDecimal getMontoTransaccion() {
return this.montoTransaccion;
}
public void setMontoTransaccion(BigDecimal montoTransaccion) {
this.montoTransaccion = montoTransaccion;
}
public Integer getSaldoTransaccion() {
return this.saldoTransaccion;
}
public void setSaldoTransaccion(Integer saldoTransaccion) {
this.saldoTransaccion = saldoTransaccion;
}
public CuentaCliente getCuentaCliente() {
return this.cuentaCliente;
}
public void setCuentaCliente(CuentaCliente cuentaCliente) {
this.cuentaCliente = cuentaCliente;
}
public TipoTransaccion getTipoTransaccion() {
return this.tipoTransaccion;
}
public void setTipoTransaccion(TipoTransaccion tipoTransaccion) {
this.tipoTransaccion = tipoTransaccion;
}
} | [
"quilismalm@localhost"
] | quilismalm@localhost |
126b0d7b220cfefa837fe40baf806634d03e9723 | 87c16c410b8ba1d66376f22ebc5c494b4b8b6294 | /study/study/datastructnew/main/java/bitalgo/CountSetBits.java | 711119995219263bbd3eb1dbaa2d5714a263cd57 | [] | no_license | DRahul89/ds-algo-practise | 47bb6f887b9aaca73df69dba98da834abdb4a4d6 | 93c164a3e0de07aba50c1508983e7f28d7ce5552 | refs/heads/master | 2021-08-28T04:45:12.460967 | 2017-12-11T07:26:29 | 2017-12-11T07:26:29 | 110,454,062 | 0 | 0 | null | null | null | null | WINDOWS-1250 | Java | false | false | 951 | java | package main.java.bitalgo;
/**
* By using Kernighan’s Algorithm
*
* @author rahul2065
*
*/
public class CountSetBits {
public static int countSetBits(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1);
count++;
}
return count;
}
public static int addOne(int x) {
return (-(~x));
}
public static int decreaseOne(int x) {
int one = 1;
for (int i = 1; i <= 32; i++) {
if ((x & one) != 0) {
x = x ^ one;
break;
} else {
x = x | one;
}
one = 1 << i;
}
return x;
}
public static int addOneByPattern(int x) {
int one = 1;
for (int i = 1; i <= 32; i++) {
if ((x & one) != 0) {
x = x ^ one;
} else {
x = x | one;
break;
}
one = 1 << i;
}
return x;
}
public static void main(String[] args) {
System.out.println(countSetBits(10));
System.out.println(addOne(10));
System.out.println(decreaseOne(10));
System.out.println(addOneByPattern(-200));
}
}
| [
"[email protected]"
] | |
e17e9a77c3fe45a9e4eea0a1936d735ac4b22731 | 887d067c15066ea7f1df98eeefe2c12ceeeec435 | /SpringNybatis/src/main/java/com/imooc/thrift/ThriftService.java | 35aa6bdb8589b617aca70172a19d158e118a8c38 | [] | no_license | liubo0501/myspring | d1734e33e391e10e0899006023c9e1f927816bbc | bb179171715fe137d3e92e04db57b40f358a0629 | refs/heads/master | 2020-03-21T19:57:58.031250 | 2018-06-28T07:08:01 | 2018-06-28T07:08:01 | 138,980,247 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | true | 41,834 | java | /**
* Autogenerated by Thrift Compiler (0.10.0)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package com.imooc.thrift;
/********************************************************************************
** Copyright(c) 2014-2017 湖南万为智能机器人技术有限公司 All Rights Reserved.
** @author [email protected]
** 日期: 2017/11/10
** 描述:Thrift
** 版本:v1.0
*********************************************************************************/
@SuppressWarnings({ "cast", "rawtypes", "serial", "unchecked", "unused" })
@javax.annotation.Generated(value = "Autogenerated by Thrift Compiler (0.10.0)", date = "2017-04-13")
public class ThriftService {
public interface Iface {
public java.lang.String httpRequest(java.lang.String data) throws org.apache.thrift.TException;
}
public interface AsyncIface {
public void httpRequest(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException;
}
public static class Client extends org.apache.thrift.TServiceClient implements Iface {
public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {
public Factory() {
}
public Client getClient(org.apache.thrift.protocol.TProtocol prot) {
return new Client(prot);
}
public Client getClient(org.apache.thrift.protocol.TProtocol iprot,
org.apache.thrift.protocol.TProtocol oprot) {
return new Client(iprot, oprot);
}
}
public Client(org.apache.thrift.protocol.TProtocol prot) {
super(prot, prot);
}
public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {
super(iprot, oprot);
}
public java.lang.String httpRequest(java.lang.String data) throws org.apache.thrift.TException {
send_httpRequest(data);
return recv_httpRequest();
}
public void send_httpRequest(java.lang.String data) throws org.apache.thrift.TException {
httpRequest_args args = new httpRequest_args();
args.setData(data);
sendBase("httpRequest", args);
}
public java.lang.String recv_httpRequest() throws org.apache.thrift.TException {
httpRequest_result result = new httpRequest_result();
receiveBase(result, "httpRequest");
if (result.isSetSuccess()) {
return result.success;
}
throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT,
"httpRequest failed: unknown result");
}
}
public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {
public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {
private org.apache.thrift.async.TAsyncClientManager clientManager;
private org.apache.thrift.protocol.TProtocolFactory protocolFactory;
public Factory(org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.protocol.TProtocolFactory protocolFactory) {
this.clientManager = clientManager;
this.protocolFactory = protocolFactory;
}
public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {
return new AsyncClient(protocolFactory, clientManager, transport);
}
}
public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.async.TAsyncClientManager clientManager,
org.apache.thrift.transport.TNonblockingTransport transport) {
super(protocolFactory, clientManager, transport);
}
public void httpRequest(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException {
checkReady();
httpRequest_call method_call = new httpRequest_call(data, resultHandler, this, ___protocolFactory,
___transport);
this.___currentMethod = method_call;
___manager.call(method_call);
}
public static class httpRequest_call extends org.apache.thrift.async.TAsyncMethodCall<java.lang.String> {
private java.lang.String data;
public httpRequest_call(java.lang.String data,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler,
org.apache.thrift.async.TAsyncClient client,
org.apache.thrift.protocol.TProtocolFactory protocolFactory,
org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {
super(client, protocolFactory, transport, resultHandler, false);
this.data = data;
}
public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {
prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage("httpRequest",
org.apache.thrift.protocol.TMessageType.CALL, 0));
httpRequest_args args = new httpRequest_args();
args.setData(data);
args.write(prot);
prot.writeMessageEnd();
}
public java.lang.String getResult() throws org.apache.thrift.TException {
if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {
throw new java.lang.IllegalStateException("Method call not finished!");
}
org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(
getFrameBuffer().array());
org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);
return (new Client(prot)).recv_httpRequest();
}
}
}
public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I>
implements org.apache.thrift.TProcessor {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory.getLogger(Processor.class.getName());
public Processor(I iface) {
super(iface, getProcessMap(
new java.util.HashMap<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));
}
protected Processor(I iface,
java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends Iface> java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(
java.util.Map<java.lang.String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {
processMap.put("httpRequest", new httpRequest());
return processMap;
}
public static class httpRequest<I extends Iface>
extends org.apache.thrift.ProcessFunction<I, httpRequest_args> {
public httpRequest() {
super("httpRequest");
}
public httpRequest_args getEmptyArgsInstance() {
return new httpRequest_args();
}
protected boolean isOneway() {
return false;
}
public httpRequest_result getResult(I iface, httpRequest_args args) throws org.apache.thrift.TException {
httpRequest_result result = new httpRequest_result();
result.success = iface.httpRequest(args.data);
return result;
}
}
}
public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {
private static final org.slf4j.Logger _LOGGER = org.slf4j.LoggerFactory
.getLogger(AsyncProcessor.class.getName());
public AsyncProcessor(I iface) {
super(iface, getProcessMap(
new java.util.HashMap<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));
}
protected AsyncProcessor(I iface,
java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
super(iface, getProcessMap(processMap));
}
private static <I extends AsyncIface> java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> getProcessMap(
java.util.Map<java.lang.String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {
processMap.put("httpRequest", new httpRequest());
return processMap;
}
public static class httpRequest<I extends AsyncIface>
extends org.apache.thrift.AsyncProcessFunction<I, httpRequest_args, java.lang.String> {
public httpRequest() {
super("httpRequest");
}
public httpRequest_args getEmptyArgsInstance() {
return new httpRequest_args();
}
public org.apache.thrift.async.AsyncMethodCallback<java.lang.String> getResultHandler(
final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.String>() {
public void onComplete(java.lang.String o) {
httpRequest_result result = new httpRequest_result();
result.success = o;
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY, seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException) e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb, msg, msgType, seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
protected boolean isOneway() {
return false;
}
public void start(I iface, httpRequest_args args,
org.apache.thrift.async.AsyncMethodCallback<java.lang.String> resultHandler)
throws org.apache.thrift.TException {
iface.httpRequest(args.data, resultHandler);
}
}
}
public static class httpRequest_args implements org.apache.thrift.TBase<httpRequest_args, httpRequest_args._Fields>,
java.io.Serializable, Cloneable, Comparable<httpRequest_args> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"httpRequest_args");
private static final org.apache.thrift.protocol.TField DATA_FIELD_DESC = new org.apache.thrift.protocol.TField(
"data", org.apache.thrift.protocol.TType.STRING, (short) 1);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new httpRequest_argsStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new httpRequest_argsTupleSchemeFactory();
public java.lang.String data; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
DATA((short) 1, "data");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 1: // DATA
return DATA;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(_Fields.DATA, new org.apache.thrift.meta_data.FieldMetaData("data",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(httpRequest_args.class, metaDataMap);
}
public httpRequest_args() {
}
public httpRequest_args(java.lang.String data) {
this();
this.data = data;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public httpRequest_args(httpRequest_args other) {
if (other.isSetData()) {
this.data = other.data;
}
}
public httpRequest_args deepCopy() {
return new httpRequest_args(this);
}
@Override
public void clear() {
this.data = null;
}
public java.lang.String getData() {
return this.data;
}
public httpRequest_args setData(java.lang.String data) {
this.data = data;
return this;
}
public void unsetData() {
this.data = null;
}
/**
* Returns true if field data is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetData() {
return this.data != null;
}
public void setDataIsSet(boolean value) {
if (!value) {
this.data = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case DATA:
if (value == null) {
unsetData();
} else {
setData((java.lang.String) value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case DATA:
return getData();
}
throw new java.lang.IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case DATA:
return isSetData();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof httpRequest_args)
return this.equals((httpRequest_args) that);
return false;
}
public boolean equals(httpRequest_args that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_data = true && this.isSetData();
boolean that_present_data = true && that.isSetData();
if (this_present_data || that_present_data) {
if (!(this_present_data && that_present_data))
return false;
if (!this.data.equals(that.data))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetData()) ? 131071 : 524287);
if (isSetData())
hashCode = hashCode * 8191 + data.hashCode();
return hashCode;
}
@Override
public int compareTo(httpRequest_args other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetData()).compareTo(other.isSetData());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetData()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.data, other.data);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("httpRequest_args(");
boolean first = true;
sb.append("data:");
if (this.data == null) {
sb.append("null");
} else {
sb.append(this.data);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class httpRequest_argsStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_argsStandardScheme getScheme() {
return new httpRequest_argsStandardScheme();
}
}
private static class httpRequest_argsStandardScheme
extends org.apache.thrift.scheme.StandardScheme<httpRequest_args> {
public void read(org.apache.thrift.protocol.TProtocol iprot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // DATA
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.data = iprot.readString();
struct.setDataIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, httpRequest_args struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.data != null) {
oprot.writeFieldBegin(DATA_FIELD_DESC);
oprot.writeString(struct.data);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class httpRequest_argsTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_argsTupleScheme getScheme() {
return new httpRequest_argsTupleScheme();
}
}
private static class httpRequest_argsTupleScheme
extends org.apache.thrift.scheme.TupleScheme<httpRequest_args> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetData()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetData()) {
oprot.writeString(struct.data);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, httpRequest_args struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.data = iprot.readString();
struct.setDataIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(
org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY
: TUPLE_SCHEME_FACTORY).getScheme();
}
}
public static class httpRequest_result
implements org.apache.thrift.TBase<httpRequest_result, httpRequest_result._Fields>, java.io.Serializable,
Cloneable, Comparable<httpRequest_result> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(
"httpRequest_result");
private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(
"success", org.apache.thrift.protocol.TType.STRING, (short) 0);
private static final org.apache.thrift.scheme.SchemeFactory STANDARD_SCHEME_FACTORY = new httpRequest_resultStandardSchemeFactory();
private static final org.apache.thrift.scheme.SchemeFactory TUPLE_SCHEME_FACTORY = new httpRequest_resultTupleSchemeFactory();
public java.lang.String success; // required
/**
* The set of fields this struct contains, along with convenience
* methods for finding and manipulating them.
*/
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
SUCCESS((short) 0, "success");
private static final java.util.Map<java.lang.String, _Fields> byName = new java.util.HashMap<java.lang.String, _Fields>();
static {
for (_Fields field : java.util.EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its
* not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch (fieldId) {
case 0: // SUCCESS
return SUCCESS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an
* exception if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null)
throw new java.lang.IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not
* found.
*/
public static _Fields findByName(java.lang.String name) {
return byName.get(name);
}
private final short _thriftId;
private final java.lang.String _fieldName;
_Fields(short thriftId, java.lang.String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public java.lang.String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
java.util.Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new java.util.EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(
_Fields.class);
tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData("success",
org.apache.thrift.TFieldRequirementType.DEFAULT,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
metaDataMap = java.util.Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(httpRequest_result.class, metaDataMap);
}
public httpRequest_result() {
}
public httpRequest_result(java.lang.String success) {
this();
this.success = success;
}
/**
* Performs a deep copy on <i>other</i>.
*/
public httpRequest_result(httpRequest_result other) {
if (other.isSetSuccess()) {
this.success = other.success;
}
}
public httpRequest_result deepCopy() {
return new httpRequest_result(this);
}
@Override
public void clear() {
this.success = null;
}
public java.lang.String getSuccess() {
return this.success;
}
public httpRequest_result setSuccess(java.lang.String success) {
this.success = success;
return this;
}
public void unsetSuccess() {
this.success = null;
}
/**
* Returns true if field success is set (has been assigned a value) and
* false otherwise
*/
public boolean isSetSuccess() {
return this.success != null;
}
public void setSuccessIsSet(boolean value) {
if (!value) {
this.success = null;
}
}
public void setFieldValue(_Fields field, java.lang.Object value) {
switch (field) {
case SUCCESS:
if (value == null) {
unsetSuccess();
} else {
setSuccess((java.lang.String) value);
}
break;
}
}
public java.lang.Object getFieldValue(_Fields field) {
switch (field) {
case SUCCESS:
return getSuccess();
}
throw new java.lang.IllegalStateException();
}
/**
* Returns true if field corresponding to fieldID is set (has been
* assigned a value) and false otherwise
*/
public boolean isSet(_Fields field) {
if (field == null) {
throw new java.lang.IllegalArgumentException();
}
switch (field) {
case SUCCESS:
return isSetSuccess();
}
throw new java.lang.IllegalStateException();
}
@Override
public boolean equals(java.lang.Object that) {
if (that == null)
return false;
if (that instanceof httpRequest_result)
return this.equals((httpRequest_result) that);
return false;
}
public boolean equals(httpRequest_result that) {
if (that == null)
return false;
if (this == that)
return true;
boolean this_present_success = true && this.isSetSuccess();
boolean that_present_success = true && that.isSetSuccess();
if (this_present_success || that_present_success) {
if (!(this_present_success && that_present_success))
return false;
if (!this.success.equals(that.success))
return false;
}
return true;
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 8191 + ((isSetSuccess()) ? 131071 : 524287);
if (isSetSuccess())
hashCode = hashCode * 8191 + success.hashCode();
return hashCode;
}
@Override
public int compareTo(httpRequest_result other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = java.lang.Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetSuccess()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
scheme(iprot).read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
scheme(oprot).write(oprot, this);
}
@Override
public java.lang.String toString() {
java.lang.StringBuilder sb = new java.lang.StringBuilder("httpRequest_result(");
boolean first = true;
sb.append("success:");
if (this.success == null) {
sb.append("null");
} else {
sb.append(this.success);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in)
throws java.io.IOException, java.lang.ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(
new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class httpRequest_resultStandardSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_resultStandardScheme getScheme() {
return new httpRequest_resultStandardScheme();
}
}
private static class httpRequest_resultStandardScheme
extends org.apache.thrift.scheme.StandardScheme<httpRequest_result> {
public void read(org.apache.thrift.protocol.TProtocol iprot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true) {
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 0: // SUCCESS
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.success = iprot.readString();
struct.setSuccessIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be
// checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, httpRequest_result struct)
throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.success != null) {
oprot.writeFieldBegin(SUCCESS_FIELD_DESC);
oprot.writeString(struct.success);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class httpRequest_resultTupleSchemeFactory implements org.apache.thrift.scheme.SchemeFactory {
public httpRequest_resultTupleScheme getScheme() {
return new httpRequest_resultTupleScheme();
}
}
private static class httpRequest_resultTupleScheme
extends org.apache.thrift.scheme.TupleScheme<httpRequest_result> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol oprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet optionals = new java.util.BitSet();
if (struct.isSetSuccess()) {
optionals.set(0);
}
oprot.writeBitSet(optionals, 1);
if (struct.isSetSuccess()) {
oprot.writeString(struct.success);
}
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, httpRequest_result struct)
throws org.apache.thrift.TException {
org.apache.thrift.protocol.TTupleProtocol iprot = (org.apache.thrift.protocol.TTupleProtocol) prot;
java.util.BitSet incoming = iprot.readBitSet(1);
if (incoming.get(0)) {
struct.success = iprot.readString();
struct.setSuccessIsSet(true);
}
}
}
private static <S extends org.apache.thrift.scheme.IScheme> S scheme(
org.apache.thrift.protocol.TProtocol proto) {
return (org.apache.thrift.scheme.StandardScheme.class.equals(proto.getScheme()) ? STANDARD_SCHEME_FACTORY
: TUPLE_SCHEME_FACTORY).getScheme();
}
}
}
| [
"[email protected]"
] | |
b7bb1971897db4b4879d1357a83a9160ff7ccc54 | f95165ad67734b791cd902e310cbc9be405f9a0d | /Game Engine/src/LevelMaker/LevelMakerData.java | ef60922b0ea7d66c7bf926cdc5cfce5634aa64ee | [] | no_license | kevino5233/GameEngine | 29bd51f71ba80431b76d996b990b4d5ddd9d66f6 | d2bfafdbba649611beb0ef7e77b3de8b75d4f581 | refs/heads/master | 2021-01-25T12:24:16.585224 | 2014-05-31T09:13:19 | 2014-05-31T09:13:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,655 | java | package LevelMaker;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import Event.TextEvent;
public class LevelMakerData {
private BufferedImage tileMap;
private int[][] tileTypes;
private String[][] enemyData;
private ArrayList<String> events;
private LevelMakerData(BufferedImage tm, int[][] tt, String[][] ed, ArrayList<String> ev){
tileMap = tm;
tileTypes = tt;
enemyData = ed;
events = ev;
}
public BufferedImage getTileMap(){ return tileMap; }
public int[][] getTileTypes(){ return tileTypes; }
public String[][] getEnemyData(){ return enemyData; }
public ArrayList<String> getEvents(){ return events; }
public static String getSaveableData(BufferedImage tileMap, int[][] tileTypes, String[][] enemyData, TextEvent[][] textEvents){
String contents = "";
contents += String.format("%d %d\n", tileMap.getHeight(), tileMap.getWidth());
for (int j = 0; j < tileMap.getHeight(); j++){
for (int i = 0; i < tileMap.getWidth(); i++){
contents += tileMap.getRGB(i, j) + " ";
}
contents += '\n';
}
contents += String.format("%d %d\n", tileTypes.length, tileTypes[0].length);
for (int j = 0; j < tileTypes.length; j++){
for (int i = 0; i < tileTypes[0].length; i++){
contents += tileTypes[j][i] + " ";
}
contents += '\n';
}
for (int j = 0; j < enemyData.length; j++){
for (int i = 0; i < enemyData[0].length; i++){
if (enemyData[j][i] == null){
contents += "None ";
} else {
contents += enemyData[j][i] + " ";
}
}
contents += '\n';
}
for (int j = 0; j < textEvents.length; j++){
for (int i = 0; i < textEvents[0].length; i++){
if (textEvents[j][i] != null){
contents += i + "|" + j + "|" + textEvents[j][i] + "\n";
}
}
}
return contents;
}
public static LevelMakerData getLevelMakerData(BufferedImage tileMap, int cols, int rows){
return new LevelMakerData(tileMap, new int[rows][cols], new String[rows][cols], new ArrayList<String>());
}
public static LevelMakerData parse(String levelName)throws IOException{
/*
* Switch to InputStreamReader
* parse until a space, then parse that String
*/
InputStream in = Main.class.getResourceAsStream("/Resources/Levels/" + levelName + ".lvmk");
BufferedReader level =
new BufferedReader(
new InputStreamReader(in)
);
String[] dat = level.readLine().split(" ");
int rows = Integer.parseInt(dat[0]);
int cols = Integer.parseInt(dat[1]);
BufferedImage tm = new BufferedImage(cols, rows, BufferedImage.TYPE_INT_RGB);
for (int j = 0; j < rows; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < cols; i++){
tm.setRGB(i, j, Integer.parseInt(dat[i]));
}
}
dat = level.readLine().split(" ");
rows = Integer.parseInt(dat[0]);
cols = Integer.parseInt(dat[1]);
int[][] tt = new int[rows][cols];
for (int j = 0; j < tt.length; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < tt[0].length; i++){
tt[j][i] = Integer.parseInt(dat[i]);
}
}
String[][] ed = new String[tt.length][tt[0].length];
for (int j = 0; j < tt.length; j++){
dat = level.readLine().split(" ");
for (int i = 0; i < tt[0].length; i++){
ed[j][i] = dat[i];
}
}
int num = 0;
try{
num = Integer.parseInt(level.readLine());
} catch (Exception e){}
ArrayList<String> ev = new ArrayList<String>();
while(num-- > 0){
ev.add(level.readLine());
}
level.close();
return new LevelMakerData(tm, tt, ed, ev);
}
}
| [
"[email protected]"
] | |
41e45adbdd0e30a0f746260d36519e43fa132d99 | e5915db1aef7162ef4a9c28b022937070a92a2a7 | /src/main/java/qlhvt/dao/impl/DriverDaoImpl.java | 988e3f70df728116b94ed8bd0979b7fa9de32be6 | [] | no_license | ductq1999/QLHVT | 04409daf44dc45fb2c650bc10539ce71f4045263 | 98f6e2e63c02d056e405fda6473d5fa824a272f8 | refs/heads/master | 2023-02-11T05:47:58.050294 | 2021-01-11T11:07:58 | 2021-01-11T11:07:58 | 314,599,002 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 5,272 | java | package qlhvt.dao.impl;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import qlhvt.dao.DriverDao;
import qlhvt.entities.Driver;
@Transactional
@Repository(value = "driverDao")
public class DriverDaoImpl implements DriverDao {
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
@Override
public List<Driver> getAllDriver() {
// TODO Auto-generated method stub
String hql = "FROM Driver as d WHERE d.status = 1";
return (List<Driver>) entityManager.createQuery(hql).getResultList();
}
@Override
public Driver getDriverById(Integer id) {
// TODO Auto-generated method stub
return entityManager.find(Driver.class, id);
}
@Override
public void addDriver(Driver driver) {
// TODO Auto-generated method stub
entityManager.persist(driver);
}
@Override
public void updateDriver(Driver driver) {
// TODO Auto-generated method stub
Driver mDriver = entityManager.find(Driver.class, driver.getId());
driver.setId(mDriver.getId());
entityManager.merge(driver);
}
@Override
public void deleteDriverById(Integer id) {
// TODO Auto-generated method stub
Driver driver = entityManager.find(Driver.class, id);
driver.setStatus(0);
entityManager.merge(driver);
}
@SuppressWarnings("unlikely-arg-type")
@Override
public List<Driver> searchDriverByCondition(int page, int pageSize, String columnSortName, Boolean asc, String name,
String idNumber, String licenseType, String address, Integer status) {
// TODO Auto-generated method stub
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Driver> from = criteriaQuery.from(Driver.class);
CriteriaQuery<Object> select = criteriaQuery.select(from);
List<Predicate> predicates = new ArrayList<Predicate>();
if (name != null && !name.equals("")) {
predicates.add(criteriaBuilder.like(from.get("name"), "%" + name + "%"));
}
if (idNumber != null && !idNumber.equals("")) {
predicates.add(criteriaBuilder.like(from.get("idNumber"), "%" + idNumber + "%"));
}
if (licenseType != null && !licenseType.equals("")) {
predicates.add(criteriaBuilder.like(from.get("licenseType"), "%" + licenseType + "%"));
}
if (address != null && !address.equals("")) {
predicates.add(criteriaBuilder.like(from.get("address"), "%" + address + "%"));
}
if (status != null && !status.equals("")) {
predicates.add(criteriaBuilder.equal(from.get("status"), status));
}
select.select(from).where(predicates.toArray(new Predicate[] {}));
if (columnSortName != null && !columnSortName.equals("")) {
if (asc == null || asc) {
select.orderBy(criteriaBuilder.asc(from.get(columnSortName)));
} else {
select.orderBy(criteriaBuilder.desc(from.get(columnSortName)));
}
}
Query query = entityManager.createQuery(criteriaQuery);
if (page >= 0 && pageSize >= 0) {
query.setFirstResult((page - 1) * pageSize);
query.setMaxResults(pageSize);
}
@SuppressWarnings("unchecked")
List<Driver> lstResult = query.getResultList();
return lstResult;
}
@SuppressWarnings("unlikely-arg-type")
@Override
public int getRowCount(String name, String idNumber, String licenseType, String address, Integer status) {
// TODO Auto-generated method stub
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery();
Root<Driver> from = criteriaQuery.from(Driver.class);
CriteriaQuery<Object> select = criteriaQuery.select(from);
List<Predicate> predicates = new ArrayList<Predicate>();
if (name != null && !name.equals("")) {
predicates.add(criteriaBuilder.like(from.get("name"), "%" + name + "%"));
}
if (idNumber != null && !idNumber.equals("")) {
predicates.add(criteriaBuilder.like(from.get("idNumber"), "%" + idNumber + "%"));
}
if (licenseType != null && !licenseType.equals("")) {
predicates.add(criteriaBuilder.like(from.get("licenseType"), "%" + licenseType + "%"));
}
if (address != null && !address.equals("")) {
predicates.add(criteriaBuilder.like(from.get("address"), "%" + address + "%"));
}
;
if (status != null && !status.equals("")) {
predicates.add(criteriaBuilder.equal(from.get("status"), status));
}
select.select(from).where(predicates.toArray(new Predicate[] {}));
Query query = entityManager.createQuery(criteriaQuery);
@SuppressWarnings("unchecked")
List<Driver> lstResult = query.getResultList();
return lstResult.size();
}
@Override
public Boolean isExist(Driver driver) {
// TODO Auto-generated method stub
String hql = "FROM Driver as d WHERE d.status = 1 AND d.idNumber = :idNumber";
return entityManager.createQuery(hql).setParameter("idNumber", driver.getIdNumber()).getResultList().size() > 0 ? true : false;
}
}
| [
"[email protected]"
] | |
fd5250f99b9ceb8a948958e0dcca7553002a496e | 6b7159ff2a4e40e5ca0240018ac67433c26ced6c | /src/com/example/articlesManagement/ArticleDetailActivity.java | 70f7cf71fabb0b5c77d610c5f8ff031ef2bd29ca | [] | no_license | chenxiaobin001/maple.fm | 401c4419b53b427dd2ae887d4eaa54d70ef06b71 | 713e99a20596c16feaadc4f4311c5dbc7ec45d0f | refs/heads/master | 2021-07-05T06:26:26.370841 | 2015-07-02T16:15:05 | 2015-07-02T16:15:05 | 104,799,593 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 7,460 | java | package com.example.articlesManagement;
import java.util.ArrayList;
import com.code.freeMarket.R;
import com.example.acountManagement.AccessAcountSettings;
import com.example.asyncTasks.HandleCommentsTask;
import com.example.asyncTasks.RetriveJSONAPITask;
import com.example.infoClasses.Article;
import com.github.curioustechizen.ago.RelativeTimeTextView;
import com.nhaarman.listviewanimations.appearance.simple.ScaleInAnimationAdapter;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.example.infoClasses.Comment;
import com.example.interfaces.MyAsyncTaskListener;
public class ArticleDetailActivity extends ActionBarActivity implements MyAsyncTaskListener{
private ListView listView;
private CommentArrayAdapter adapter;
private ProgressBar progressBar;
static final int REQUEST = 1; // The request code
private ViewHolder viewHolder;
private Article article;
static class ViewHolder {
public TextView articleTitleTextView;
public RelativeTimeTextView articleTimeTextView;
public TextView articleContentTextView;
public TextView articleAuthorTextView;
public TextView articleLikeTextView;
public TextView articleDislikeTextView;
public TextView articleCommentTextView;
public TextView articleEditTextView;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = getIntent();
article = ((Article) i.getParcelableExtra("article"));
setContentView(R.layout.article_detail_activity);
listView = (ListView) findViewById(R.id.commentListView);
adapter = new CommentArrayAdapter(this, new ArrayList<Comment>());
ScaleInAnimationAdapter animationAdapter = new ScaleInAnimationAdapter(adapter);
animationAdapter.setAbsListView(listView);
listView.setAdapter(animationAdapter);
progressBar = (ProgressBar) findViewById(R.id.commentsProgress);
progressBar.setVisibility(View.GONE);
listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position,
long id) {
replyDialog((Comment) adapter.getItemAtPosition(position));
}
});
setArticleInfo();
listView.postDelayed(new Runnable() {
public void run() {
loadComments();
}
}, 1000); //Every 120000 ms (2 minutes)
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.article_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_refresh:
try {
loadComments();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case R.id.action_edit:
replyDialog(new Comment());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
Article article = data.getParcelableExtra("article");
viewHolder.articleTitleTextView.setText(article.getTitle());
viewHolder.articleContentTextView.setText(article.getContent());
this.article.setContent(article.getContent());
this.article.setTitle(article.getTitle());
}
}
}
private void loadComments() {
AsyncTask<String, Void, String> asyncTask = new HandleCommentsTask(this, findViewById(android.R.id.content), adapter);
new RetriveJSONAPITask(this, asyncTask, 3).execute(String.valueOf(article.getId()));
progressBar.setVisibility(View.VISIBLE);
}
private void setArticleInfo() {
viewHolder = new ViewHolder();
viewHolder.articleAuthorTextView = (TextView) findViewById(R.id.articleAuthorTextView);
viewHolder.articleTitleTextView = (TextView) findViewById(R.id.articleTitleTextView);
viewHolder.articleTimeTextView = (RelativeTimeTextView) findViewById(R.id.articleTimeTextView);
viewHolder.articleContentTextView = (TextView) findViewById(R.id.articleContentTextView);
viewHolder.articleLikeTextView = (TextView) findViewById(R.id.articleLikeTextView);
viewHolder.articleDislikeTextView = (TextView) findViewById(R.id.articleDislikeTextView);
viewHolder.articleCommentTextView = (TextView) findViewById(R.id.articleCommentTextView);
viewHolder.articleEditTextView = (TextView) findViewById(R.id.articleEditTextView);
viewHolder.articleContentTextView.setMovementMethod(new ScrollingMovementMethod());
AccessAcountSettings account = AccessAcountSettings.getInstance();
String user = account.getAccountName();
if (user != null && user.equals(article.getAuthor())) {
viewHolder.articleEditTextView.setVisibility(View.VISIBLE);
viewHolder.articleEditTextView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent myIntent = new Intent(ArticleDetailActivity.this, NewPostActivity.class);
myIntent.putExtra("type", 1); //1-edit mode, 0-new mode
myIntent.putExtra("article", article);
startActivityForResult(myIntent, REQUEST);
}
});
}
// date = sdf.parse(dateString);
// long startDate = date.getTime();
viewHolder.articleTimeTextView.setReferenceTime(article.getLastEditTimeL());
viewHolder.articleTitleTextView.setText(article.getTitle());
viewHolder.articleAuthorTextView.setText(article.getAuthor());
viewHolder.articleContentTextView.setText(article.getContent());
viewHolder.articleLikeTextView.setText("O " + String.valueOf(article.getLike()));
viewHolder.articleDislikeTextView.setText("X " + String.valueOf(article.getDislike()));
viewHolder.articleCommentTextView.setText("Reply " + String.valueOf(article.getComment()));
}
private void replyDialog(Comment comment) {
String[] args = new String[4];
AccessAcountSettings account = AccessAcountSettings.getInstance();
args[0] = account.getAccountName();
args[1] = String.valueOf(comment.getId());
args[2] = comment.getCommenter1();
args[3] = String.valueOf(article.getId());
ReplyArticleDialog dialog = ReplyArticleDialog.newInstance(args);
dialog.show(getFragmentManager(), "reply");
}
@Override
public void onAsyncTaskFinished(String foo) {
HandleCommentsTask task = new HandleCommentsTask(this, findViewById(android.R.id.content), adapter);
task.execute(foo);
}
}
| [
"[email protected]"
] | |
eb5fdc31d768709a82e5c674cf453f1c7c6fee6f | f9fcde801577e7b9d66b0df1334f718364fd7b45 | /icepdf-6.0.2_P01/icepdf/core/src/org/icepdf/core/pobjects/annotations/Annotation.java | a67c154d521b99c21fb8550c74310819c7a80469 | [
"Apache-2.0"
] | permissive | numbnet/icepdf_FULL-versii | 86d74147dc107e4f2239cd4ac312f15ebbeec473 | b67e1ecb60aca88cacdca995d24263651cf8296b | refs/heads/master | 2021-01-12T11:13:57.107091 | 2016-11-04T16:43:45 | 2016-11-04T16:43:45 | 72,880,329 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 76,371 | java | /*
* Copyright 2006-2016 ICEsoft Technologies Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.icepdf.core.pobjects.annotations;
import org.icepdf.core.pobjects.Dictionary;
import org.icepdf.core.pobjects.*;
import org.icepdf.core.pobjects.acroform.FieldDictionary;
import org.icepdf.core.pobjects.acroform.FieldDictionaryFactory;
import org.icepdf.core.pobjects.actions.Action;
import org.icepdf.core.pobjects.graphics.Shapes;
import org.icepdf.core.pobjects.security.SecurityManager;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.icepdf.core.util.Library;
import java.awt.*;
import java.awt.geom.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.*;
import java.util.List;
import java.util.logging.Logger;
/**
* <p>An <code>Annotation</code> class associates an object such as a note, sound, or movie with
* a location on a page of a PDF document, or provides a way to interact with
* the user by means of the mouse and keyboard.</p>
* <p/>
* <p>This class allows direct access to the a Annotations dictionary.
* Developers can take advantage of this information as they see fit. It is
* important to note that an annotations' rectangle coordinates are defined
* in the PDF document space. In order to map the rectangle coordinates to
* a view, they must be converted from the Cartesian plain to the the Java2D
* plain. The PageView method getPageBounds() can be used to locate the position
* of a page within its parent component.</p>
* <p/>
* Base class of all the specific Annotation types
* <p/>
* Taken from the PDF 1.6 spec, here is some relevant documentation,
* along with some additional commentary
* <p/>
* <h2>8.4.1 Annotation Dictionaries</h2>
* <table border=1>
* <tr>
* <td>Key</td>
* <td>Type</td>
* <td>Value</td>
* </tr>
* <tr>
* <td><b>Type</b></td>
* <td>name</td>
* <td>(<i>Optional</i>) The type of PDF object that this dictionary describes;
* if present, must be <b>Annot</b> for an annotation dictionary.</td>
* </tr>
* <tr>
* <td><b>Subtype</b></td>
* <td>name</td>
* <td>(<i>Required</i>) The type of annotation that this dictionary describes.</td>
* </tr>
* <tr>
* <td><b>Rect</b></td>
* <td>rectangle</td>
* <td>(<i>Required</i>) The <i>annotation rectangle</i>, defining the location of the
* annotation on the page in default user space units.</td>
* <td>getUserspaceLocation()</td>
* </tr>
* <tr>
* <td><b>Contents</b></td>
* <td>text string</td>
* <td>(<i>Optional</i>) Text to be displayed for the annotation or, if this type of annotation
* does not display text, an alternate description of the annotation's contents
* in human-readable form.'s contents in support of accessibility to users with
* disabilities or for other purposes (see Section 10.8.2, "Alternate Descriptions").
* See Section 8.4.5, "Annotation Types" for more details on the meaning
* of this entry for each annotation type.</td>
* </tr>
* <tr>
* <td><b>P</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.3; not used in FDF files</i>) An indirect reference to the page
* object with which this annotation is associated.</td>
* </tr>
* <tr>
* <td><b>NM</b></td>
* <td>text string</td>
* <td>(<i>Optional; PDF 1.4</i>) The <i>annotation name</i>, a text string uniquely identifying it
* among all the annotations on its page.</td>
* </tr>
* <tr>
* <td><b>M</b></td>
* <td>date or string</td>
* <td>(<i>Optional; PDF 1.1</i>) The date and time when the annotation was most
* recently modified. The preferred format is a date string as described in Section
* 3.8.3, "Dates," but viewer applications should be prepared to accept and
* display a string in any format. (See implementation note 78 in Appendix H.)</td>
* </tr>
* <tr>
* <td><b>F</b></td>
* <td>integer</td>
* <td>(<i>Optional; PDF 1.1</i>) A set of flags specifying various characteristics of the annotation
* (see Section 8.4.2, "Annotation Flags"). Default value: 0.</td>
* </tr>
* <tr>
* <td><b>BS</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) A border style dictionary specifying the characteristics of
* the annotation's border (see Section 8.4.3, "Border Styles"; see also implementation
* notes 79 and 86 in Appendix H).<br>
* <br>
* <i><b>Note:</b> This entry also specifies the width and dash pattern for the lines drawn by
* line, square, circle, and ink annotations. See the note under <b>Border</b> (below) for
* additional information.</i><br>
* <br>
* Table 8.13 summarizes the contents of the border style dictionary. If neither
* the <b>Border</b> nor the <b>BS</b> entry is present, the border is drawn as a solid line with a
* width of 1 point.</td>
* </tr>
* <tr>
* <td><b>AP</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) An <i>appearance dictionary</i> specifying how the annotation
* is presented visually on the page (see Section 8.4.4, "Appearance Streams" and
* also implementation notes 79 and 80 in Appendix H). Individual annotation
* handlers may ignore this entry and provide their own appearances.<br>
* <br>
* For convenience in managing appearance streams that are used repeatedly, the AP
* entry in a PDF document's name dictionary (see Section 3.6.3, "Name Dictionary")
* can contain a name tree mapping name strings to appearance streams. The
* name strings have no standard meanings; no PDF objects refer to appearance
* streams by name.</td>
* </tr>
* <tr>
* <td><b>AS</b></td>
* <td>name</td>
* <td>(<i>Required if the appearance dictionary <b>AP</b> contains one or more subdictionaries;
* PDF 1.2</i>) The annotation's <i>appearance state</i>, which selects the applicable
* appearance stream from an appearance subdictionary (see Section 8.4.4, "Appearance
* Streams" and also implementation note 79 in Appendix H).</td>
* </tr>
* <tr>
* <td><b>Border</b></td>
* <td>array</td>
* <td>(<i>Optional</i>) An array specifying the characteristics of the annotation's border.
* The border is specified as a rounded rectangle.<br>
* <br>
* In PDF 1.0, the array consists of three numbers defining the horizontal corner
* radius, vertical corner radius, and border width, all in default user space
* units. If the corner radii are 0, the border has square (not rounded) corners; if
* the border width is 0, no border is drawn. (See implementation note 81 in
* Appendix H.) <br>
* <br>
* In PDF 1.1, the array may have a fourth element, an optional <i>dash array</i>
* defining a pattern of dashes and gaps to be used in drawing the border. The
* dash array is specified in the same format as in the line dash pattern parameter
* of the graphics state (see "Line Dash Pattern" on page 187). For example, a
* <b>Border</b> value of [0 0 1 [3 2]] specifies a border 1 unit wide, with square corners,
* drawn with 3-unit dashes alternating with 2-unit gaps. Note that no
* dash phase is specified; the phase is assumed to be 0. (See implementation
* note 82 in Appendix H.)<br>
* <br>
* <i><b>Note:</b> In PDF 1.2 or later, this entry may be ignored in favor of the <b>BS</b>
* entry (see above); see implementation note 86 in Appendix H.</i><br>
* <br>
* Default value: [0 0 1].</td>
* </tr>
* <tr>
* <td><b>BE</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.5</i>) Some annotations (square, circle, and polygon) may
* have a <b>BE</b> entry, which is a <i>border effect</i> dictionary that specifies an effect
* to be applied to the border of the annotations. Its entries are listed in Table 8.14.</td>
* </tr>
* <tr>
* <td><b>C</b></td>
* <td>array</td>
* <td>(<i>Optional; PDF 1.1</i>) An array of three numbers in the range 0.0 to 1.0, representing
* the components of a color in the <b>DeviceRGB</b> color space. This color is
* used for the following purposes:
* <ul>
* <li>The background of the annotation's icon when closed
* <li>The title bar of the annotation's pop-up window
* <li>The border of a link annotation
* </ul></td>
* </tr>
* <tr>
* <td><b>A</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.1</i>) An action to be performed when the annotation is activated
* (see Section 8.5, "Actions").<br>
* <br>
* <i><b>Note:</b> This entry is not permitted in link annotations if a Dest entry is present
* (see "Link Annotations" on page 587). Also note that the A entry in movie annotations
* has a different meaning (see "Movie Annotations" on page 601).</i></td>
* </tr>
* <tr>
* <td><b>AA</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.2</i>) An additional-actions dictionary defining the annotation's
* behavior in response to various trigger events (see Section 8.5.2,
* "Trigger Events"). At the time of publication, this entry is used only by widget
* annotations.</td>
* </tr>
* <tr>
* <td><b>StructParent</b></td>
* <td>integer</td>
* <td>(<i>(Required if the annotation is a structural content item; PDF 1.3</i>) The integer
* key of the annotation's entry in the structural parent tree (see "Finding Structure
* Elements from Content Items" on page 797).</td>
* </tr>
* <tr>
* <td><b>OC</b></td>
* <td>dictionary</td>
* <td>(<i>Optional; PDF 1.5</i>) An optional content group or optional content membership
* dictionary (see Section 4.10, "Optional Content") specifying the optional
* content properties for the annotation. Before the annotation is drawn, its visibility
* is determined based on this entry as well as the annotation flags specified
* in the <b>F</b> entry (see Section 8.4.2, "Annotation Flags"). If it is determined
* to be invisible, the annotation is skipped, as if it were not in the document.</td>
* </tr>
* </table>
* <p/>
* <p/>
* <h2>8.4.2 Annotation Flags</h2>
* The value of the annotation dictionary's <b>F</b> entry is an unsigned 32-bit integer containing
* flags specifying various characteristics of the annotation. Bit positions
* within the flag word are numbered from 1 (low-order) to 32 (high-order). Table
* 8.12 shows the meanings of the flags; all undefined flag bits are reserved and must
* be set to 0.
* <table border=1>
* <tr>
* <td>Bit position</td>
* <td>Name</td>
* <td>Meaning</td>
* </tr>
* <tr>
* <td>1</td>
* <td>Invisible</td>
* <td>If set, do not display the annotation if it does not belong to one of the standard
* annotation types and no annotation handler is available. If clear, display such an
* unknown annotation using an appearance stream specified by its appearance
* dictionary, if any (see Section 8.4.4, "Appearance Streams").</td>
* </tr>
* <tr>
* <td>2</td>
* <td>Hidden</td>
* <td>If set, do not display or print the annotation or allow it to interact
* with the user, regardless of its annotation type or whether an annotation
* handler is available. In cases where screen space is limited, the ability to hide
* and show annotations selectively can be used in combination with appearance
* streams (see Section 8.4.4, "Appearance Streams") to display auxiliary pop-up
* information similar in function to online help systems. (See implementation
* note 83 in Appendix H.)</td>
* </tr>
* <tr>
* <td>3</td>
* <td>Print</td>
* <td>If set, print the annotation when the page is printed. If clear, never
* print the annotation, regardless of whether it is displayed on the screen. This
* can be useful, for example, for annotations representing interactive pushbuttons,
* which would serve no meaningful purpose on the printed page. (See
* implementation note 83 in Appendix H.)</td>
* </tr>
* <tr>
* <td>4</td>
* <td>NoZoom</td>
* <td>If set, do not scale the annotation's appearance to match the magnification
* of the page. The location of the annotation on the page (defined by the
* upper-left corner of its annotation rectangle) remains fixed, regardless of the
* page magnification. See below for further discussion.</td>
* </tr>
* <tr>
* <td>5</td>
* <td>NoRotate</td>
* <td>If set, do not rotate the annotation's appearance to match the rotation
* of the page. The upper-left corner of the annotation rectangle remains in a fixed
* location on the page, regardless of the page rotation. See below for further discussion.</td>
* </tr>
* <tr>
* <td>6</td>
* <td>NoView</td>
* <td>If set, do not display the annotation on the screen or allow it to
* interact with the user. The annotation may be printed (depending on the setting
* of the Print flag) but should be considered hidden for purposes of on-screen
* display and user interaction.</td>
* </tr>
* <tr>
* <td>7</td>
* <td>ReadOnly</td>
* <td>If set, do not allow the annotation to interact with the user. The
* annotation may be displayed or printed (depending on the settings of the
* NoView and Print flags) but should not respond to mouse clicks or change its
* appearance in response to mouse motions.<br>
* <br>
* <i><b>Note:</b> This flag is ignored for widget annotations; its function is subsumed by the
* ReadOnly flag of the associated form field (see Table 8.66 on page 638).</i></td>
* </tr>
* <tr>
* <td>8</td>
* <td>Locked</td>
* <td>If set, do not allow the annotation to be deleted or its properties (including
* position and size) to be modified by the user. However, this flag does
* not restrict changes to the annotation's contents, such as the value of a form
* field. (See implementation note 84 in Appendix H.)</td>
* </tr>
* <tr>
* <td>9</td>
* <td>ToggleNoView</td>
* <td>If set, invert the interpretation of the NoView flag for certain events. A
* typical use is to have an annotation that appears only when a mouse cursor is
* held over it; see implementation note 85 in Appendix H.</td>
* </tr>
* </table>
*
* @author Mark Collette
* @since 2.5
*/
public abstract class Annotation extends Dictionary {
private static final Logger logger =
Logger.getLogger(Annotation.class.toString());
public static final Name TYPE = new Name("Annot");
public static final Name RESOURCES_VALUE = new Name("Resources");
public static final Name BBOX_VALUE = new Name("BBox");
public static final Name PARENT_KEY = new Name("Parent");
/**
* Dictionary constants for Annotations.
*/
public static final Name TYPE_VALUE = new Name("Annot");
/**
* Annotation subtype and types.
*/
public static final Name SUBTYPE_LINK = new Name("Link");
public static final Name SUBTYPE_LINE = new Name("Line");
public static final Name SUBTYPE_SQUARE = new Name("Square");
public static final Name SUBTYPE_CIRCLE = new Name("Circle");
public static final Name SUBTYPE_POLYGON = new Name("Polygon");
public static final Name SUBTYPE_POLYLINE = new Name("PolyLine");
public static final Name SUBTYPE_HIGHLIGHT = new Name("Highlight");
public static final Name SUBTYPE_POPUP = new Name("Popup");
public static final Name SUBTYPE_WIDGET = new Name("Widget");
public static final Name SUBTYPE_INK = new Name("Ink");
public static final Name SUBTYPE_FREE_TEXT = new Name("FreeText");
public static final Name SUBTYPE_TEXT = new Name("Text");
/**
* If set, do not display the annotation if it does not belong to one of the
* standard annotation types and no annotation handler is available. If clear,
* display such an unknown annotation using an appearance stream specified
* by its appearance dictionary, if any
*/
public static final int FLAG_INVISIBLE = 0x0001;
/**
* If set, do not display or print the annotation or allow it to interact
* with the user, regardless of its annotation type or whether an annotation
* handler is available.
*/
public static final int FLAG_HIDDEN = 0x0002;
/**
* If set, print the annotation when the page is printed. If clear, never
* print the annotation, regardless of whether it is displayed on the screen.
*/
public static final int FLAG_PRINT = 0x0004;
/**
* If set, do not scale the annotation’s appearance to match the magnification
* of the page. The location of the annotation on the page (defined by the
* upper-left corner of its annotation rectangle) shall remain fixed,
* regardless of the page magnification. See further discussion following
* this Table.
*/
public static final int FLAG_NO_ZOOM = 0x0008;
/**
* If set, do not rotate the annotation’s appearance to match the rotation
* of the page. The upper-left corner of the annotation rectangle shall
* remain in a fixed location on the page, regardless of the page rotation.
* See further discussion following this Table.
*/
public static final int FLAG_NO_ROTATE = 0x0010;
/**
* If set, do not display the annotation on the screen or allow it to interact
* with the user. The annotation may be printed (depending on the setting of
* the Print flag) but should be considered hidden for purposes of on-screen
* display and user interaction.
*/
public static final int FLAG_NO_VIEW = 0x0020;
/**
* If set, do not allow the annotation to interact with the user. The
* annotation may be displayed or printed (depending on the settings of the
* NoView and Print flags) but should not respond to mouse clicks or change
* its appearance in response to mouse motions.
* <p/>
* This flag shall be ignored for widget annotations; its function is
* subsumed by the ReadOnly flag of the associated form field.
*/
public static final int FLAG_READ_ONLY = 0x0040;
/**
* If set, do not allow the annotation to be deleted or its properties
* (including position and size) to be modified by the user. However, this
* flag does not restrict changes to the annotation’s contents, such as the
* value of a form field.
*/
public static final int FLAG_LOCKED = 0x0080;
/**
* If set, invert the interpretation of the NoView flag for certain events.
*/
public static final int FLAG_TOGGLE_NO_VIEW = 0x0100;
/**
* If set, do not allow the contents of the annotation to be modified by the
* user. This flag does not restrict deletion of the annotation or changes
* to other annotation properties, such as position and size.
*/
public static final int FLAG_LOCKED_CONTENTS = 0x0200;
/**
* Border style
*/
public static final Name BORDER_STYLE_KEY = new Name("BS");
/**
* The annotation location on the page in user space units.
*/
public static final Name RECTANGLE_KEY = new Name("Rect");
/**
* The action to be performed whenteh annotation is activated.
*/
public static final Name ACTION_KEY = new Name("A");
/**
* Page that this annotation is associated with.
*/
public static final Name PARENT_PAGE_KEY = new Name("P");
/**
* Annotation border characteristics.
*/
public static final Name BORDER_KEY = new Name("Border");
/**
* Annotation border characteristics.
*/
public static final Name FLAG_KEY = new Name("F");
/**
* RGB colour value for background, titlebars and link annotation borders
*/
public static final Name COLOR_KEY = new Name("C");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page.
*/
public static final Name APPEARANCE_STREAM_KEY = new Name("AP");
/**
* Appearance state selecting default from multiple AP's.
*/
public static final Name APPEARANCE_STATE_KEY = new Name("AS");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for normal display.
*/
public static final Name APPEARANCE_STREAM_NORMAL_KEY = new Name("N");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for rollover display.
*/
public static final Name APPEARANCE_STREAM_ROLLOVER_KEY = new Name("R");
/**
* Appearance dictionary specifying how the annotation is presented
* visually on the page for down display.
*/
public static final Name APPEARANCE_STREAM_DOWN_KEY = new Name("D");
/**
* (Optional) Text that shall be displayed for the annotation or, if this
* type of annotation does not display text, an alternate description of the
* annotation’s contents in human-readable form. In either case, this text
* is useful when extracting the document’s contents in support of accessibility
* to users with disabilities or for other purposes (see 14.9.3,
* “Alternate Descriptions”). See 12.5.6, “Annotation Types” for more details
* on the meaning of this entry for each annotation type.
*/
public static final Name CONTENTS_KEY = new Name("Contents");
/**
* The date and time when the annotation was most recently modified. The
* format should be a date string as described in 7.9.4, “Dates,” but
* conforming readers shall accept and display a string in any format.
*/
public static final Name M_KEY = new Name("M");
/**
* (Optional; PDF 1.4) The annotation name, a text string uniquely
* identifying it among all the annotations on its page.
*/
public static final Name NM_KEY = new Name("NM");
/**
* Border property indexes for the border vector, only applicable
* if the border style has not been set.
*/
public static final int BORDER_HORIZONTAL_CORNER_RADIUS = 0;
public static final int BORDER_VERTICAL_CORNER_RADIUS = 1;
public static final int BORDER_WIDTH = 2;
public static final int BORDER_DASH = 3;
/**
* Annotion may or may not have a visible rectangle border
*/
public static final int VISIBLE_RECTANGLE = 1;
public static final int INVISIBLE_RECTANGLE = 0;
protected PropertyChangeSupport changeSupport;
/**
* Debug flag to turn off appearance stream compression for easier
* human file reading.
*/
protected static boolean compressAppearanceStream = true;
protected HashMap<Name, Appearance> appearances = new HashMap<Name, Appearance>(3);
protected Name currentAppearance;
// modified date.
protected PDate modifiedDate;
protected boolean hasBlendingMode;
// security manager need for decrypting strings.
protected SecurityManager securityManager;
// type of annotation
protected Name subtype;
// content flag
protected String content;
// borders style of the annotation, can be null
protected BorderStyle borderStyle;
// border defined by vector
protected List border;
// border color of annotation.
protected Color color;
// annotation bounding rectangle in user space.
protected Rectangle2D.Float userSpaceRectangle;
// test for borderless annotation types
protected boolean canDrawBorder;
/**
* Creates a new instance of an Annotation.
*
* @param l document library.
* @param h dictionary entries.
*/
public Annotation(Library l, HashMap h) {
super(l, h);
}
/**
* Should only be called from Parser, Use AnnotationFactory if you
* creating a new annotation.
*
* @param library document library
* @param hashMap annotation properties.
* @return annotation instance.
*/
@SuppressWarnings("unchecked")
public static Annotation buildAnnotation(Library library, HashMap hashMap) {
Annotation annot = null;
Name subType = (Name) hashMap.get(SUBTYPE_KEY);
if (subType != null) {
if (subType.equals(Annotation.SUBTYPE_LINK)) {
annot = new LinkAnnotation(library, hashMap);
}
// highlight version of a TextMarkup annotation.
else if (subType.equals(TextMarkupAnnotation.SUBTYPE_HIGHLIGHT) ||
subType.equals(TextMarkupAnnotation.SUBTYPE_STRIKE_OUT) ||
subType.equals(TextMarkupAnnotation.SUBTYPE_UNDERLINE)) {
annot = new TextMarkupAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_LINE)) {
annot = new LineAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_SQUARE)) {
annot = new SquareAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_CIRCLE)) {
annot = new CircleAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_INK)) {
annot = new InkAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_FREE_TEXT)) {
annot = new FreeTextAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_TEXT)) {
annot = new TextAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_POPUP)) {
annot = new PopupAnnotation(library, hashMap);
} else if (subType.equals(Annotation.SUBTYPE_WIDGET)) {
Name fieldType = library.getName(hashMap, FieldDictionary.FT_KEY);
if (fieldType == null) {
// get type from parent object if we the widget and field dictionary aren't combined.
Object tmp = library.getObject(hashMap, FieldDictionary.PARENT_KEY);
if (tmp instanceof HashMap) {
fieldType = library.getName((HashMap) tmp, FieldDictionary.FT_KEY);
}
}
if (FieldDictionaryFactory.TYPE_BUTTON.equals(fieldType)) {
annot = new ButtonWidgetAnnotation(library, hashMap);
} else if (FieldDictionaryFactory.TYPE_CHOICE.equals(fieldType)) {
annot = new ChoiceWidgetAnnotation(library, hashMap);
} else if (FieldDictionaryFactory.TYPE_TEXT.equals(fieldType)) {
annot = new TextWidgetAnnotation(library, hashMap);
}
// todo signatures widget.
else if (FieldDictionaryFactory.TYPE_SIGNATURE.equals(fieldType)) {
annot = new WidgetAnnotation(library, hashMap);
} else {
annot = new WidgetAnnotation(library, hashMap);
}
}
}
if (annot == null) {
annot = new GenericAnnotation(library, hashMap);
}
// annot.init();
return annot;
}
public static void setCompressAppearanceStream(boolean compressAppearanceStream) {
Annotation.compressAppearanceStream = compressAppearanceStream;
}
@SuppressWarnings("unchecked")
public void init() {
super.init();
// type of Annotation
subtype = (Name) getObject(SUBTYPE_KEY);
securityManager = library.getSecurityManager();
content = library.getString(entries, CONTENTS_KEY);
// no borders for the following types, not really in the
// spec for some reason, Acrobat doesn't render them.
// todo add other annotations types.
canDrawBorder = !(
SUBTYPE_LINE.equals(subtype) ||
SUBTYPE_CIRCLE.equals(subtype) ||
SUBTYPE_SQUARE.equals(subtype) ||
SUBTYPE_POLYGON.equals(subtype) ||
SUBTYPE_POLYLINE.equals(subtype));
// parse out border style if available
Object BS = getObject(BORDER_STYLE_KEY);
if (BS != null) {
if (BS instanceof HashMap) {
borderStyle = new BorderStyle(library, (HashMap) BS);
} else if (BS instanceof BorderStyle) {
borderStyle = (BorderStyle) BS;
}
}
// else build out a border style from the old B entry or create
// a default invisible border.
else {
HashMap<Name, Object> borderMap = new HashMap<Name, Object>();
// get old school border
Object borderObject = getObject(BORDER_KEY);
if (borderObject != null && borderObject instanceof List) {
border = (List) borderObject;
// copy over the properties to border style.
if (border.size() == 3) {
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_SOLID);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, border.get(2));
} else if (border.size() == 4) {
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_DASHED);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, border.get(2));
borderMap.put(BorderStyle.BORDER_DASH_KEY, Arrays.asList(3f));
}
} else {
// default to invisible border
borderMap.put(BorderStyle.BORDER_STYLE_KEY, BorderStyle.BORDER_STYLE_SOLID);
borderMap.put(BorderStyle.BORDER_WIDTH_KEY, 0f);
}
borderStyle = new BorderStyle(library, borderMap);
entries.put(BORDER_STYLE_KEY, borderStyle);
}
// parse out border colour, specific to link annotations.
color = null; // null as some borders are set as transparent via no colour
List C = (List) getObject(COLOR_KEY);
// parse thought rgb colour.
if (C != null && C.size() >= 3) {
float red = ((Number) C.get(0)).floatValue();
float green = ((Number) C.get(1)).floatValue();
float blue = ((Number) C.get(2)).floatValue();
red = Math.max(0.0f, Math.min(1.0f, red));
green = Math.max(0.0f, Math.min(1.0f, green));
blue = Math.max(0.0f, Math.min(1.0f, blue));
color = new Color(red, green, blue);
}
// if no creation date check for M or modified.
Object value = library.getObject(entries, M_KEY);
if (value != null && value instanceof StringObject) {
StringObject text = (StringObject) value;
modifiedDate = new PDate(securityManager,
text.getDecryptedLiteralString(securityManager));
}
// process the streams if available.
Object AP = getObject(APPEARANCE_STREAM_KEY);
if (AP instanceof HashMap) {
// assign the default AS key as the default appearance
currentAppearance = APPEARANCE_STREAM_NORMAL_KEY;
Name appearanceState = (Name) getObject(APPEARANCE_STATE_KEY);
if (appearanceState == null) {
appearanceState = APPEARANCE_STREAM_NORMAL_KEY;
}
// The annotations normal appearance.
Object appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_NORMAL_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_NORMAL_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_NORMAL_KEY,
appearance));
appearances.get(APPEARANCE_STREAM_NORMAL_KEY).setSelectedName(appearanceState);
}
// (Optional) The annotation’s rollover appearance.
// Default value: the value of the N entry.
appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_ROLLOVER_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_ROLLOVER_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_ROLLOVER_KEY,
appearance));
}
// (Optional) The annotation’s down appearance.
// Default value: the value of the N entry.
appearance = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_DOWN_KEY);
if (appearance != null) {
appearances.put(APPEARANCE_STREAM_DOWN_KEY,
parseAppearanceDictionary(APPEARANCE_STREAM_DOWN_KEY,
appearance));
}
} else {
// new annotation, so setup the default appearance states.
Appearance newAppearance = new Appearance();
HashMap appearanceDictionary = new HashMap();
Rectangle2D rect = getUserSpaceRectangle();
if (rect == null){
// we need a rect in order to render correctly, bail if not found. PDF-964
throw new IllegalStateException("Annotation is missing required /rect value");
}
if (rect.getWidth() <= 1) {
rect.setRect(rect.getX(), rect.getY(), 15, rect.getHeight());
}
if (rect.getHeight() <= 1) {
rect.setRect(rect.getX(), rect.getY(), rect.getWidth(), 15);
}
appearanceDictionary.put(BBOX_VALUE, rect);
newAppearance.addAppearance(APPEARANCE_STREAM_NORMAL_KEY,
new AppearanceState(library, appearanceDictionary));
appearances.put(APPEARANCE_STREAM_NORMAL_KEY, newAppearance);
currentAppearance = APPEARANCE_STREAM_NORMAL_KEY;
}
}
private Appearance parseAppearanceDictionary(Name appearanceDictionary,
Object streamOrDictionary) {
Appearance appearance = new Appearance();
// iterate over all of the keys so we can index the various annotation
// state names.
if (streamOrDictionary instanceof HashMap) {
HashMap dictionary = (HashMap) streamOrDictionary;
Set keys = dictionary.keySet();
Object value;
for (Object key : keys) {
value = dictionary.get(key);
if (value instanceof Reference) {
appearance.addAppearance((Name) key,
new AppearanceState(library, dictionary,
library.getObject((Reference) value)));
}
}
}
// single entry so assign is using the default key name
else {
appearance.addAppearance(appearanceDictionary,
new AppearanceState(library, entries, streamOrDictionary));
}
return appearance;
}
/**
* Gets the type of annotation that this dictionary describes.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getSubType()
*
* @return subtype of annotation
*/
public Name getSubType() {
return library.getName(entries, SUBTYPE_KEY);
}
public void setSubtype(Name subtype) {
entries.put(SUBTYPE_KEY, subtype);
this.subtype = subtype;
}
/**
* Gets the annotation rectangle, and defines the location of the annotation on
* the page in default user space units.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getRectangle()
*
* @return rectangle of annotation
*/
public Rectangle2D.Float getUserSpaceRectangle() {
if (userSpaceRectangle == null) {
Object tmp = getObject(RECTANGLE_KEY);
if (tmp instanceof List) {
userSpaceRectangle = library.getRectangle(entries, RECTANGLE_KEY);
}
}
return userSpaceRectangle;
}
/**
* Sets the users page rectangle for this annotation action instance
*/
public void setUserSpaceRectangle(Rectangle2D.Float rect) {
if (userSpaceRectangle != null && rect != null) {
userSpaceRectangle = new Rectangle2D.Float(rect.x, rect.y,
rect.width, rect.height);
entries.put(Annotation.RECTANGLE_KEY,
PRectangle.getPRectangleVector(userSpaceRectangle));
}
}
public void setBBox(Rectangle bbox) {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
appearanceState.setBbox(bbox);
}
public Rectangle2D getBbox() {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
return appearanceState.getBbox();
}
protected void resetNullAppearanceStream() {
// try and generate an appearance stream.
if (!hasAppearanceStream()) {
Object tmp = getObject(RECTANGLE_KEY);
Rectangle2D.Float rectangle = null;
if (tmp instanceof java.util.List) {
rectangle = library.getRectangle(entries, RECTANGLE_KEY);
}
if (rectangle != null) {
setBBox(rectangle.getBounds());
}
resetAppearanceStream(new AffineTransform());
}
}
public Name getCurrentAppearance() {
return currentAppearance;
}
public void setCurrentAppearance(Name currentAppearance) {
this.currentAppearance = currentAppearance;
}
/**
* Creates a Java2D strok from the propties tht make up the BorderStyle object.
*
* @return dashed or solid stoke.
*/
public Stroke getBorderStyleStroke() {
if (borderStyle.isStyleDashed()) {
return new BasicStroke(
borderStyle.getStrokeWidth(), BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
borderStyle.getStrokeWidth() * 2.0f, borderStyle.getDashArray(), 0.0f);
} else {
return new BasicStroke(borderStyle.getStrokeWidth());
}
}
/**
* Gets the action to be performed when the annotation is activated.
* For compatibility with the old org.icepdf.core.pobjects.Annotation.getAction()
*
* @return action to be activated, if no action, null is returned.
*/
public org.icepdf.core.pobjects.actions.Action getAction() {
Object tmp = library.getDictionary(entries, ACTION_KEY);
// initial parse will likely have the action as a dictionary, so we
// create the new action object on the fly. However it is also possible
// that we are parsing an action that has no type specification and
// thus we can't use the parser to create the new action.
if (tmp != null) {
Action action = Action.buildAction(library, (HashMap) tmp);
// assign reference if applicable
if (action != null &&
library.isReference(entries, ACTION_KEY)) {
action.setPObjectReference(
library.getReference(entries, ACTION_KEY));
}
return action;
}
// subsequent new or edit actions will put in a reference and property
// dictionary entry.
tmp = getObject(ACTION_KEY);
if (tmp != null && tmp instanceof Action) {
return (Action) tmp;
}
return null;
}
/**
* Adds the specified action to this annotation instance. If the annotation
* instance already has an action then this action replaces it.
* <p/>
* todo: future enhancement add support of next/muliple action chains.
*
* @param action action to add to this annotation. This action must
* be created using the the ActionFactory in order to correctly setup
* the Pobject reference.
* @return action that was added to Annotation, null if it was not success
* fully added.
*/
public Action addAction(Action action) {
// if no object ref we bail early.
if (action.getPObjectReference() == null) {
logger.severe("Addition of action was rejected null Object reference "
+ action);
return null;
}
// gen instance of state manager
StateManager stateManager = library.getStateManager();
// check if there is a 'dest' entry, if so we need to add this as a new
// action, flag it for later processing.
boolean isDestKey = getObject(LinkAnnotation.DESTINATION_KEY) != null;
// check the annotation dictionary for an instance of an existing action
if (getObject(ACTION_KEY) != null) {
// if found we will add the new action at the beginning of the
// next chain.
boolean isReference = library.isReference(getEntries(),
ACTION_KEY);
// we have a next action that is an object, mark it for delete.
// Because its a reference no need to flag the annotation as changed.
if (isReference) {
// mark this action for delete.
Action oldAction = (Action) action.getObject(ACTION_KEY);
oldAction.setDeleted(true);
stateManager.addChange(new PObject(oldAction,
oldAction.getPObjectReference()));
}
// not a reference, we have an inline dictionary and we'll be
// clearing it later, so we only need to add this annotation
// to the state manager.
else {
getEntries().remove(ACTION_KEY);
stateManager.addChange(new PObject(this, getPObjectReference()));
}
}
// add the new action as per usual
getEntries().put(ACTION_KEY, action.getPObjectReference());
stateManager.addChange(new PObject(this, getPObjectReference()));
// if this is a link annotation and there is a dest, we need to remove
// as it is not allowed once an action has bee added.
if (isDestKey && this instanceof LinkAnnotation) {
// remove the dest key from the dictionary
this.getEntries().remove(LinkAnnotation.DESTINATION_KEY);
// mark the annotation as changed.
stateManager.addChange(new PObject(this, getPObjectReference()));
}
// add the new action to the state manager.
action.setNew(true);
stateManager.addChange(new PObject(action, action.getPObjectReference()));
// add it to the library so we can get it again.
library.addObject(action, action.getPObjectReference());
return action;
}
/**
* Deletes the annotation action specified as a paramater. If an instance
* of the specified action can not be found, no delete is make.
*
* @param action action to remove
* @return true if the delete was successful, false otherwise.
*/
public boolean deleteAction(Action action) {
// gen instance of state manager
StateManager stateManager = library.getStateManager();
if (getObject(ACTION_KEY) != null) {
// mark this action for delete.
Action currentAction = getAction();
if (currentAction.similar(action)) {
// clear the action key for the annotation and add it as changed.
// add the new action to the annotation
getEntries().remove(ACTION_KEY);
currentAction.setDeleted(true);
// mark the action as changed.
stateManager.addChange(new PObject(currentAction,
currentAction.getPObjectReference()));
// mark the action as change.d
stateManager.addChange(new PObject(this, getPObjectReference()));
return true;
}
}
return false;
}
/**
* Update the current annotation action with this entry. This is very similar
* to add but this method will return false if there was no previous annotation.
* In such a case a call to addAction should be made.
*
* @param action action to update
* @return true if the update was successful, othere; false.
*/
public boolean updateAction(Action action) {
// get instance of state manager
StateManager stateManager = library.getStateManager();
if (getObject(ACTION_KEY) != null) {
Action currentAction = getAction();
// check if we are updating an existing instance
if (!currentAction.similar(action)) {
stateManager.addChange(new PObject(action,
action.getPObjectReference()));
currentAction.setDeleted(true);
stateManager.addChange(new PObject(currentAction,
currentAction.getPObjectReference()));
}
// add the action to the annotation
getEntries().put(ACTION_KEY, action.getPObjectReference());
stateManager.addChange(new PObject(action,
action.getPObjectReference()));
return true;
}
return false;
}
public boolean allowScreenNormalMode() {
return allowScreenOrPrintRenderingOrInteraction() && !getFlagNoView();
}
public boolean allowScreenRolloverMode() {
return allowScreenOrPrintRenderingOrInteraction() && !(getFlagNoView()
&& !getFlagToggleNoView()) && !getFlagReadOnly();
}
public boolean allowScreenDownMode() {
return allowScreenOrPrintRenderingOrInteraction() && !(getFlagNoView() &&
!getFlagToggleNoView()) && !getFlagReadOnly();
}
public boolean allowPrintNormalMode() {
return allowScreenOrPrintRenderingOrInteraction() && getFlagPrint();
}
public boolean allowAlterProperties() {
return !getFlagLocked();
}
public BorderStyle getBorderStyle() {
return borderStyle;
}
public void setBorderStyle(BorderStyle borderStyle) {
this.borderStyle = borderStyle;
entries.put(Annotation.BORDER_STYLE_KEY, this.borderStyle);
}
@SuppressWarnings("unchecked")
public List<Number> getBorder() {
return border;
}
public Object getParentAnnotation() {
Annotation parent = null;
Object ob = getObject(PARENT_KEY);
if (ob instanceof Reference)
ob = library.getObject((Reference) ob);
if (ob instanceof Annotation)
parent = (Annotation) ob;
else if (ob instanceof HashMap)
return FieldDictionaryFactory.buildField(library, (HashMap) ob);
return parent;
}
public Page getPage() {
Page page = (Page) getObject(PARENT_PAGE_KEY);
if (page == null) {
Object annot = getParentAnnotation();
if (annot instanceof Annotation)
page = ((Annotation) annot).getPage();
}
return page;
}
/**
* Gets the Link type, can be either VISIBLE_RECTANGLE or
* INVISIBLE_RECTANGLE, it all depends on the if the border or BS has
* border width > 0.
*
* @return VISIBLE_RECTANGLE if the annotation has a visible borde, otherwise
* INVISIBLE_RECTANGLE
*/
public int getBorderType() {
// border style has W value for border with
if (borderStyle != null) {
if (borderStyle.getStrokeWidth() > 0) {
return VISIBLE_RECTANGLE;
}
}
// look for a border, 0,0,1 has one, 0,0,0 doesn't
else if (border != null) {
if (border.size() >= 3 && ((Number) border.get(2)).floatValue() > 0) {
return VISIBLE_RECTANGLE;
}
}
// should never happen
return INVISIBLE_RECTANGLE;
}
/**
* Gets the Annotation border style for the given annotation. If no
* annotation line style can be found the default value of BORDER_STYLE_SOLID
* is returned. Otherwise the bordStyle and border dictionaries are used
* to deduse a line style.
*
* @return BorderSTyle line constants.
*/
public Name getLineStyle() {
// check for border style
if (borderStyle != null) {
return borderStyle.getBorderStyle();
}
// check the border entry, will be solid or dashed
else if (border != null) {
if (border.size() > 3) {
return BorderStyle.BORDER_STYLE_DASHED;
} else if (((Number) border.get(2)).floatValue() > 1) {
return BorderStyle.BORDER_STYLE_SOLID;
}
}
// default value
return BorderStyle.BORDER_STYLE_SOLID;
}
/**
* Gets the line thickness assoicated with this annotation.
*
* @return point value used when drawing line thickness.
*/
public float getLineThickness() {
// check for border style
if (borderStyle != null) {
return borderStyle.getStrokeWidth();
}
// check the border entry, will be solid or dashed
else if (border != null) {
if (border.size() >= 3) {
return ((Number) border.get(2)).floatValue();
}
}
return 0;
}
/**
* Checks to see if the annotation has defined a drawable border width.
*
* @return true if a border will be drawn; otherwise, false.
*/
public boolean isBorder() {
boolean borderWidth = false;
Object border = getObject(BORDER_KEY);
if (border != null && border instanceof List) {
List borderProps = (List) border;
if (borderProps.size() == 3) {
borderWidth = ((Number) borderProps.get(2)).floatValue() > 0;
}
}
return (getBorderStyle() != null &&
getBorderStyle().getStrokeWidth() > 0) || borderWidth;
}
public void render(Graphics2D origG, int renderHintType,
float totalRotation, float userZoom,
boolean tabSelected) {
if (!allowScreenOrPrintRenderingOrInteraction())
return;
if (renderHintType == GraphicsRenderingHints.SCREEN && !allowScreenNormalMode())
return;
if (renderHintType == GraphicsRenderingHints.PRINT && !allowPrintNormalMode())
return;
//System.out.println("render(-) " + this);
Rectangle2D.Float rect = getUserSpaceRectangle();
// Show original ractangle, without taking into consideration NoZoom and NoRotate
//System.out.println("Original rectangle: " + rect);
//origG.setColor( Color.blue );
//origG.draw( rect );
//origG.setColor( Color.red );
//Line2D.Double topLine = new Line2D.Double( rect.getMinX(), rect.getMaxY(), rect.getMaxX(), rect.getMaxY() );
//origG.draw( topLine );
//origG.setColor( Color.yellow );
//Line2D.Double bottomLine = new Line2D.Double( rect.getMinX(), rect.getMinY(), rect.getMaxX(), rect.getMinY() );
//origG.draw( bottomLine );
AffineTransform oldAT = origG.getTransform();
Shape oldClip = origG.getClip();
// Simply uncomment the //// lines to use a different Graphics object
Graphics2D g = origG;
////Graphics2D g = (Graphics2D) origG.create();
AffineTransform at = new AffineTransform(oldAT);
// move canvas to paint annotation for page rendering only.
at.translate(rect.getMinX(), rect.getMinY());
boolean noRotate = getFlagNoRotate();
if (noRotate) {
float unRotation = -totalRotation;
while (unRotation < 0.0f)
unRotation += 360.0f;
while (unRotation > 360.0f)
unRotation -= 360.0f;
if (unRotation == -0.0f)
unRotation = 0.0f;
if (unRotation != 0.0) {
double radians = Math.toRadians(unRotation); // unRotation * Math.PI / 180.0
AffineTransform rotationTransform =
AffineTransform.getRotateInstance(radians);
Point2D.Double origTopLeftCorner = new Point2D.Double(0.0, Math.abs(rect.getHeight()));
Point2D rotatedTopLeftCorner = rotationTransform.transform(origTopLeftCorner, null);
at.translate(origTopLeftCorner.getX() - rotatedTopLeftCorner.getX(),
origTopLeftCorner.getY() - rotatedTopLeftCorner.getY());
at.rotate(radians);
}
}
boolean noZoom = getFlagNoZoom();
if (noZoom) {
double scaleY = Math.abs(at.getScaleY());
if (scaleY != 1.0) {
double scaleX = Math.abs(at.getScaleX());
double rectHeight = Math.abs(rect.getHeight());
double resizedY = rectHeight * ((scaleY - 1.0) / scaleY);
at.translate(0.0, resizedY);
at.scale(1.0 / scaleX, 1.0 / scaleY);
}
}
GraphicsRenderingHints grh = GraphicsRenderingHints.getDefault();
g.setRenderingHints(grh.getRenderingHints(renderHintType));
g.setTransform(at);
Shape preAppearanceStreamClip = g.getClip();
// Shape annotationShape = deriveDrawingRectangle();
g.clip(deriveDrawingRectangle());
renderAppearanceStream(g);
g.setTransform(at);
g.setClip(preAppearanceStreamClip);
if (tabSelected) {
renderBorderTabSelected(g);
} else {
renderBorder(g);
}
g.setTransform(oldAT);
g.setClip(oldClip);
////g.dispose();
// Show the top left corner, that NoZoom and NoRotate annotations cling to
//origG.setColor( Color.blue );
//Rectangle2D.Double topLeft = new Rectangle2D.Double(
// rect.getMinX(), rect.getMaxY()-3, 3, 3 );
//origG.fill( topLeft );
}
protected void renderAppearanceStream(Graphics2D g) {
Appearance appearance = appearances.get(currentAppearance);
if (appearance == null) return;
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
if (appearanceState.getShapes() != null) {
AffineTransform matrix = appearanceState.getMatrix();
Rectangle2D bbox = appearanceState.getBbox();
// g.setColor( Color.blue );
// Rectangle2D.Float newRect = deriveDrawingRectangle();
// g.draw( newRect );
// step 1. appearance bounding box (BBox) is transformed, using
// Matrix, to produce a quadrilateral with arbitrary orientation.
Rectangle2D tBbox = matrix.createTransformedShape(bbox).getBounds2D();
// Step 2. matrix a is computed that scales and translates the
// transformed appearance box (tBbox) to align with the edges of
// the annotation's rectangle (Ret).
Rectangle2D rect = getUserSpaceRectangle();
AffineTransform tAs = AffineTransform.getScaleInstance(
(rect.getWidth() / tBbox.getWidth()),
(rect.getHeight() / tBbox.getHeight()));
if (matrix.getTranslateX() > 0 || matrix.getTranslateY() > 0) {
// we have to align the boxes.
matrix.setToTranslation(rect.getX() - matrix.getTranslateX(),
rect.getY() - matrix.getTranslateY());
}
// Step 3. matrix is concatenated with A to form a matrix AA
// that maps from the appearance's coordinate system to the
// annotation's rectangle in default user space.
tAs.concatenate(matrix);
g.transform(tAs);
// regular paint
appearanceState.getShapes().paint(g);
}
}
protected void renderBorder(Graphics2D g) {
// if( false ) {
// float width = 1.0f;
// Rectangle2D.Float jrect = deriveBorderDrawingRectangle( width );
// g.setColor( Color.red );
// g.setStroke( new BasicStroke(width) );
// g.draw( jrect );
// return;
// }
// we don't paint some borders as the BS has a different meanings.
if (this instanceof SquareAnnotation ||
this instanceof CircleAnnotation ||
this instanceof LineAnnotation ||
this instanceof FreeTextAnnotation ||
this instanceof InkAnnotation) {
return;
}
Color borderColor = getColor();
if (borderColor != null) {
g.setColor(borderColor);
}
BorderStyle bs = getBorderStyle();
if (bs != null) {
float width = bs.getStrokeWidth();
if (width > 0.0f && borderColor != null && canDrawBorder) {
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
if (bs.isStyleSolid()) {
g.setStroke(new BasicStroke(width));
g.draw(jrect);
} else if (bs.isStyleDashed()) {
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
width * 2.0f, bs.getDashArray(), 0.0f);
g.setStroke(stroke);
g.draw(jrect);
} else if (bs.isStyleBeveled()) {
jrect = deriveDrawingRectangle();
g.setStroke(new BasicStroke(1.0f));
Line2D.Double line;
// Upper top
g.setColor(BorderStyle.LIGHT);
line = new Line2D.Double( // Top line
jrect.getMinX() + 1.0, jrect.getMaxY() - 1.0, jrect.getMaxX() - 2.0, jrect.getMaxY() - 1.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 1.0f, jrect.getMinY() + 2.0, jrect.getMinX() + 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
// Inner top
g.setColor(BorderStyle.LIGHTEST);
line = new Line2D.Double( // Top line
jrect.getMinX() + 2.0, jrect.getMaxY() - 2.0, jrect.getMaxX() - 3.0, jrect.getMaxY() - 2.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 2.0f, jrect.getMinY() + 3.0, jrect.getMinX() + 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Inner bottom
g.setColor(BorderStyle.DARK);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 2.0, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0, jrect.getMinY() + 2.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 2.0f, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Lower bottom
g.setColor(BorderStyle.DARKEST);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 1.0, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0, jrect.getMinY() + 1.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 1.0f, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
} else if (bs.isStyleInset()) {
jrect = deriveDrawingRectangle();
g.setStroke(new BasicStroke(1.0f));
Line2D.Double line;
// Upper top
g.setColor(BorderStyle.DARK);
line = new Line2D.Double( // Top line
jrect.getMinX() + 1.0, jrect.getMaxY() - 1.0, jrect.getMaxX() - 1.0, jrect.getMaxY() - 1.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 1.0f, jrect.getMinY() + 1.0, jrect.getMinX() + 1.0f, jrect.getMaxY() - 1.0);
g.draw(line);
// Inner top
g.setColor(BorderStyle.DARKEST);
line = new Line2D.Double( // Top line
jrect.getMinX() + 2.0, jrect.getMaxY() - 2.0, jrect.getMaxX() - 2.0, jrect.getMaxY() - 2.0);
g.draw(line);
line = new Line2D.Double( // Left line
jrect.getMinX() + 2.0f, jrect.getMinY() + 2.0, jrect.getMinX() + 2.0f, jrect.getMaxY() - 2.0);
g.draw(line);
// Inner bottom
g.setColor(BorderStyle.LIGHTEST);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 3.0, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0, jrect.getMinY() + 2.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 2.0f, jrect.getMinY() + 2.0, jrect.getMaxX() - 2.0f, jrect.getMaxY() - 3.0);
g.draw(line);
// Lower bottom
g.setColor(BorderStyle.LIGHT);
line = new Line2D.Double( // Bottom line
jrect.getMinX() + 2.0, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0, jrect.getMinY() + 1.0);
g.draw(line);
line = new Line2D.Double( // Right line
jrect.getMaxX() - 1.0f, jrect.getMinY() + 1.0, jrect.getMaxX() - 1.0f, jrect.getMaxY() - 2.0);
g.draw(line);
} else if (bs.isStyleUnderline()) {
g.setStroke(new BasicStroke(width));
Line2D.Double line = new Line2D.Double(
jrect.getMinX(), jrect.getMinY(), jrect.getMaxX(), jrect.getMinY());
g.draw(line);
}
}
} else {
List borderVector = (List) getObject(BORDER_KEY);
if (borderVector != null) {
if (borderColor != null) {
float horizRadius = 0.0f;
float vertRadius = 0.0f;
float width = 1.0f;
float[] dashArray = null;
if (borderVector.size() >= 1)
horizRadius = ((Number) borderVector.get(0)).floatValue();
if (borderVector.size() >= 2)
vertRadius = ((Number) borderVector.get(1)).floatValue();
if (borderVector.size() >= 3)
width = ((Number) borderVector.get(2)).floatValue();
if (borderVector.size() >= 4) {
Object dashObj = borderVector.get(3);
// I guess some encoders like having fun with us,
// and feed a number when a number-array is appropriate. The problem
// is that for the specific PDF given, apparently no border is to be
// drawn, especially not the hugely thinck one described. So,
// instead of interpretting the 4th element (Number) into a Vector,
// I'm just not going to do the border if it's the Number. I know, hack.
// The only theory I have is that LinkAnnotation defaults the border
// color to black, when maybe it should be to null, but that could
// change a _lot_ of stuff, so I won't touch it now.
if (dashObj instanceof Number) {
// Disable border drawing
width = 0.0f;
} else if (dashObj instanceof List) {
List dashVector = (List) borderVector.get(3);
int sz = dashVector.size();
dashArray = new float[sz];
for (int i = 0; i < sz; i++) {
Number num = (Number) dashVector.get(i);
dashArray[i] = num.floatValue();
}
}
}
if (width > 0.0f) {
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
RoundRectangle2D.Double roundRect = new RoundRectangle2D.Double(
jrect.getX(), jrect.getY(), jrect.getWidth(), jrect.getHeight(),
horizRadius, vertRadius);
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dashArray, 0.0f);
g.setStroke(stroke);
g.draw(roundRect);
}
}
} else {
// Draw a solid rectangle, 1 pixel wide
if (borderColor != null && SUBTYPE_LINK.equals(subtype)) {
float width = 1.0f;
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
g.setStroke(new BasicStroke(width));
g.draw(jrect);
}
}
}
}
protected void renderBorderTabSelected(Graphics2D g) {
float width = 1.0f;
Rectangle2D.Float jrect = deriveBorderDrawingRectangle(width);
g.setColor(Color.black);
float[] dashArray = new float[]{2.0f};
BasicStroke stroke = new BasicStroke(
width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
10.0f, dashArray, 0.0f);
g.setStroke(stroke);
g.draw(jrect);
}
/**
* Gest the RGB colour of the annotation used for the following purposes:
* <ul>
* <li>the background of the annotaiton's icon when closed</li>
* <li>the title bar of the anntoation's pop-up window</li>
* <li>the border of a link annotation</li>
* </ul>
*
* @return A Color for the border, or null if none is to be used
*/
public Color getColor() {
return color;
}
/**
* Sets the Annotation colour and underlying
*
* @param color new colour value
*/
public void setColor(Color color) {
this.color = new Color(color.getRGB());
// put colour back in to the dictionary
float[] compArray = new float[3];
this.color.getColorComponents(compArray);
List<Float> colorValues = new ArrayList<Float>(compArray.length);
for (float comp : compArray) {
colorValues.add(comp);
}
entries.put(Annotation.COLOR_KEY, colorValues);
}
protected Rectangle2D.Float deriveDrawingRectangle() {
Rectangle2D.Float origRect = getUserSpaceRectangle();
Rectangle2D.Float jrect = new Rectangle2D.Float(origRect.x, origRect.y,
origRect.width, origRect.height);
jrect.x = 0.0f;
jrect.y = 0.0f;
return jrect;
}
private Rectangle2D.Float deriveBorderDrawingRectangle(float borderWidth) {
Rectangle2D.Float jrect = deriveDrawingRectangle();
float halfBorderWidth = borderWidth / 2.0f;
double minX = jrect.getMinX() + halfBorderWidth;
double minY = jrect.getMinY() + halfBorderWidth;
double maxX = jrect.getMaxX() - halfBorderWidth;
double maxY = jrect.getMaxY() - halfBorderWidth;
jrect.setFrameFromDiagonal(minX, minY, maxX, maxY);
return jrect;
}
/**
* @return Whether this annotation may be shown in any way to the user
*/
protected boolean allowScreenOrPrintRenderingOrInteraction() {
// Based off of the annotation flags' Invisible and Hidden values
if (getFlagHidden())
return false;
return !(getFlagInvisible() && isSupportedAnnotationType());
}
/**
* The PDF spec defines rules for displaying annotation subtypes that the viewer
* does not recognise. But, from a product point of view, we may or may not
* wish to make a best attempt at showing an unsupported annotation subtype,
* as that may make users think we're quality deficient, instead of
* feature deficient.
* Subclasses should override this, and return true, indicating that that
* particular annotation is supported.
*
* @return true, if this annotation is supported; else, false.
*/
protected boolean isSupportedAnnotationType() {
return true;
}
public boolean getFlagInvisible() {
return ((getInt(FLAG_KEY) & FLAG_INVISIBLE) != 0);
}
public boolean getFlagHidden() {
return ((getInt(FLAG_KEY) & FLAG_HIDDEN) != 0);
}
public boolean getFlagPrint() {
return ((getInt(FLAG_KEY) & FLAG_PRINT) != 0);
}
public boolean getFlagNoZoom() {
return ((getInt(FLAG_KEY) & FLAG_NO_ZOOM) != 0);
}
public boolean getFlagNoRotate() {
return ((getInt(FLAG_KEY) & FLAG_NO_ROTATE) != 0);
}
public boolean getFlagNoView() {
return ((getInt(FLAG_KEY) & FLAG_NO_VIEW) != 0);
}
public boolean getFlagReadOnly() {
return ((getInt(FLAG_KEY) & FLAG_READ_ONLY) != 0);
}
public boolean getFlagToggleNoView() {
return ((getInt(FLAG_KEY) & FLAG_TOGGLE_NO_VIEW) != 0);
}
public boolean getFlagLockedContents() {
return ((getInt(FLAG_KEY) & FLAG_LOCKED_CONTENTS) != 0);
}
public boolean getFlagLocked() {
return ((getInt(FLAG_KEY) & FLAG_LOCKED) != 0);
}
/**
* Set the specified flag key to either enabled or disabled.
*
* @param flagKey flag key to set.
* @param enable true or false key value.
*/
public void setFlag(final int flagKey, boolean enable) {
int flag = getInt(FLAG_KEY);
boolean isEnabled = (flag & flagKey) != 0;
if (!enable && isEnabled) {
flag = flag ^ flagKey;
entries.put(FLAG_KEY, flag);
} else if (enable && !isEnabled) {
flag = flag | flagKey;
entries.put(FLAG_KEY, flag);
}
}
public void setModifiedDate(String modifiedDate) {
entries.put(M_KEY, new LiteralStringObject(modifiedDate));
this.modifiedDate = new PDate(securityManager, modifiedDate);
}
public boolean hasAppearanceStream() {
return library.getObject(entries, APPEARANCE_STREAM_KEY) != null;
}
/**
* Returns the appearance stream as defined by the AP dictionary key N
*
* @return N appearance stream or null.
*/
public Stream getAppearanceStream() {
Object AP = getObject(APPEARANCE_STREAM_KEY);
if (AP instanceof HashMap) {
Object N = library.getObject(
(HashMap) AP, APPEARANCE_STREAM_NORMAL_KEY);
if (N instanceof HashMap) {
Object AS = getObject(APPEARANCE_STATE_KEY);
if (AS != null && AS instanceof Name)
N = library.getObject((HashMap) N, (Name) AS);
}
// n should be a Form but we have a few cases of Stream
if (N instanceof Stream) {
return (Stream) N;
}
}
return null;
}
/**
* Gets the Appearance Form object associated with the annotation's appearances. Many encoders do no create
* the stream if there is no data in the widget. This method insure that an appearance XObject/Form is
* created. The object new object is not added to the state manager.
*
* @return appearance for annotation.
*/
public Form getOrGenerateAppearanceForm() {
StateManager stateManager = library.getStateManager();
Form form = null;
if (hasAppearanceStream()) {
Stream stream = getAppearanceStream();
if (stream instanceof Form) {
form = (Form) stream;
} else if (stream != null) {
// build out an appearance stream, corner case iText 2.1
// didn't correctly set type = form on the appearance stream obj.
form = new Form(library, stream.getEntries(), null);
form.setPObjectReference(stream.getPObjectReference());
form.setRawBytes(stream.getDecodedStreamBytes());
form.init();
}
}// else a stream, we won't support this for annotations.
else {
// create a new xobject/form object
HashMap<Name, Object> formEntries = new HashMap<Name, Object>();
formEntries.put(Form.TYPE_KEY, Form.TYPE_VALUE);
formEntries.put(Form.SUBTYPE_KEY, Form.SUB_TYPE_VALUE);
form = new Form(library, formEntries, null);
form.setPObjectReference(stateManager.getNewReferencNumber());
library.addObject(form, form.getPObjectReference());
}
return form;
}
public String getContents() {
return content;
}
public void setContents(String content) {
this.content = content;
entries.put(CONTENTS_KEY, new LiteralStringObject(content));
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ANNOTATION= {");
Set keys = entries.keySet();
for (Object key : keys) {
Object value = entries.get(key);
sb.append(key.toString());
sb.append('=');
if (value == null)
sb.append("null");
else if (value instanceof StringObject)
sb.append(((StringObject) value).getDecryptedLiteralString(library.securityManager));
else
sb.append(value.toString());
sb.append(',');
}
sb.append('}');
if (getPObjectReference() != null) {
sb.append(" ");
sb.append(getPObjectReference());
}
for (int i = sb.length() - 1; i >= 0; i--) {
if (sb.charAt(i) < 32 || sb.charAt(i) >= 127)
sb.deleteCharAt(i);
}
return sb.toString();
}
public void syncBBoxToUserSpaceRectangle(Rectangle2D bbox) {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
appearanceState.setBbox(bbox);
Rectangle2D tBbox = appearanceState.getMatrix().createTransformedShape(bbox).getBounds2D();
setUserSpaceRectangle(new Rectangle2D.Float(
(float) tBbox.getX(), (float) tBbox.getY(),
(float) tBbox.getWidth(), (float) tBbox.getHeight()));
}
public abstract void resetAppearanceStream(double dx, double dy, AffineTransform pageSpace);
public void resetAppearanceStream(AffineTransform pageSpace) {
resetAppearanceStream(0, 0, pageSpace);
}
public Shapes getShapes() {
Appearance appearance = appearances.get(currentAppearance);
AppearanceState appearanceState = appearance.getSelectedAppearanceState();
return appearanceState.getShapes();
}
public HashMap<Name, Appearance> getAppearances() {
return appearances;
}
public void addPropertyChangeListener(
PropertyChangeListener listener) {
synchronized (this) {
if (listener == null) {
return;
}
if (changeSupport == null) {
changeSupport = new PropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
}
}
| [
"patrick.corless@8668f098-c06c-11db-ba21-f49e70c34f74"
] | patrick.corless@8668f098-c06c-11db-ba21-f49e70c34f74 |
e3981a5c3e006489a0702331ca4c7382b2b3ff3d | 72fe9dba584370367771facbfddaa62bd2d855c6 | /WordChainsProd/src/com/strumsoft/wordchainsfree/helper/WordGameProvider.java | 416bcdb9123147133581b01f99ebb6d127d8e128 | [] | no_license | eshaanb/Word-Chains | 2333f3b1101e4399eda91a3a1e7129c37b4565bc | d8b078feccea7dd108a52ec9f64abec4b70d24d3 | refs/heads/master | 2021-01-18T13:55:56.446203 | 2014-12-09T08:03:51 | 2014-12-09T08:03:51 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 18,315 | java | package com.strumsoft.wordchainsfree.helper;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.google.gson.Gson;
import com.strumsoft.wordchainsfree.model.Artists;
import com.strumsoft.wordchainsfree.model.FBMessage;
import com.strumsoft.wordchainsfree.model.Game;
import com.strumsoft.wordchainsfree.model.Games;
import com.strumsoft.wordchainsfree.model.Movies;
import com.strumsoft.wordchainsfree.model.TVShows;
public class WordGameProvider extends ContentProvider {
private DBHelper dbHelper;
public static final String GAMES_TABLE_NAME = "games";
private static final String DATABASE_NAME = "wordgames.db";
public static final String WORDS_TABLE_NAME = "words";
public static final String TEMP_WORDS_TABLE_NAME = "tempwords";
public static final String BOTWORDS_TABLE_NAME = "botwords";
public static final String FRIENDS_TABLE_NAME = "friends";
public static final String REGISTERED_FRIENDS_TABLE_NAME = "regfriends";
public static final String USERS_TABLE_NAME = "users";
public static final String MESSAGES_TABLE_NAME = "messages";
public static final String SCORE_TABLE_NAME = "score";
public static final String AUTHORITY = "com.strumsoft.wordgamefree.provider.WordGameProvider";
public static final Uri GAMES_URI = Uri.parse("content://"+AUTHORITY+"/"+GAMES_TABLE_NAME);
public static final Uri USERS_URI = Uri.parse("content://"+AUTHORITY+"/"+USERS_TABLE_NAME);
public static final Uri WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+WORDS_TABLE_NAME);
public static final Uri TEMP_WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+TEMP_WORDS_TABLE_NAME);
public static final Uri BOT_WORDS_URI = Uri.parse("content://"+AUTHORITY+"/"+BOTWORDS_TABLE_NAME);
public static final Uri FRIENDS_URI = Uri.parse("content://"+AUTHORITY+"/"+FRIENDS_TABLE_NAME);
public static final Uri REGISTERED_FRIENDS_URI = Uri.parse("content://"+AUTHORITY+"/"+REGISTERED_FRIENDS_TABLE_NAME);
public static final Uri ALL_URI = Uri.parse("content://"+AUTHORITY+"/all");
public static final Uri ALL_GAMES_URI = Uri.parse("content://"+AUTHORITY+"/allgames");
public static final Uri MESSAGES_URI = Uri.parse("content://"+AUTHORITY+"/messages");
public static final Uri SCORE_URI = Uri.parse("content://"+AUTHORITY+"/score");
private static final UriMatcher uriMatcher;
// Mapped to content://wordgame/games
private static final int GAMES = 1;
// Mapped to content://wordgame/messages
private static final int MESSAGES = 12;
// Mapped to content://wordgame/player
private static final int PLAYERS = 2;
// Mapped to content://wordgame/words
private static final int WORDS = 3;
private static final int BOT_WORDS = 9;
// Mapped to content://wordgame/games/*
private static final int GAME_ITEM = 4;
// Mapped to content://wordgame/users/*
private static final int PLAYER_ITEM = 5;
// Mapped to content://wordgame/words/*
private static final int WORD_ITEM = 6;
// Mapped to content://wordgame/botwords/*
private static final int BOT_WORD_ITEM = 11;
// Mapped to content://wordgame/messages/*
private static final int MESSAGE_ITEM = 13;
// Mapped to content://wordgame/all
private static final int ALL = 7;
private static final int REGISTERED_FRIENDS = 14;
private static final int SCORE_ITEM = 15;
private static final int SCORES = 16;
private static final int TEMP_WORDS = 17;
private static final int TEMP_WORD_ITEM = 18;
private static final HashMap<String, String> gamesProjection;
private static final HashMap<String, String> playersProjection;
private static final HashMap<String, String> wordsProjection;
static {
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(AUTHORITY, GAMES_TABLE_NAME, GAMES);
uriMatcher.addURI(AUTHORITY, USERS_TABLE_NAME, PLAYERS);
uriMatcher.addURI(AUTHORITY, WORDS_TABLE_NAME, WORDS);
uriMatcher.addURI(AUTHORITY, BOTWORDS_TABLE_NAME, BOT_WORDS);
uriMatcher.addURI(AUTHORITY, GAMES_TABLE_NAME+"/*", GAME_ITEM);
uriMatcher.addURI(AUTHORITY, USERS_TABLE_NAME+"/*", PLAYER_ITEM);
uriMatcher.addURI(AUTHORITY, WORDS_TABLE_NAME+"/*", WORD_ITEM);
uriMatcher.addURI(AUTHORITY, BOTWORDS_TABLE_NAME+"/*", BOT_WORD_ITEM);
uriMatcher.addURI(AUTHORITY, "all", ALL);
uriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME, MESSAGES);
uriMatcher.addURI(AUTHORITY, MESSAGES_TABLE_NAME+"/*", MESSAGE_ITEM);
uriMatcher.addURI(AUTHORITY, REGISTERED_FRIENDS_TABLE_NAME, REGISTERED_FRIENDS);
uriMatcher.addURI(AUTHORITY, SCORE_TABLE_NAME, SCORES);
uriMatcher.addURI(AUTHORITY, SCORE_TABLE_NAME+"/*", SCORE_ITEM);
uriMatcher.addURI(AUTHORITY, TEMP_WORDS_TABLE_NAME, TEMP_WORDS);
uriMatcher.addURI(AUTHORITY, TEMP_WORDS_TABLE_NAME+"/*", TEMP_WORD_ITEM);
gamesProjection = new HashMap<String, String>();
gamesProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
gamesProjection.put(DBHelper.CREATOR, DBHelper.CREATOR);
gamesProjection.put(DBHelper.TURNCOUNT, DBHelper.TURNCOUNT);
gamesProjection.put(DBHelper.TYPE, DBHelper.TYPE);
playersProjection = new HashMap<String, String>();
playersProjection.put(DBHelper.USER_USERNAME, DBHelper.USER_USERNAME);
playersProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection = new HashMap<String, String>();
wordsProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection.put(DBHelper.MY_ORDER, DBHelper.MY_ORDER);
wordsProjection.put(DBHelper.GAME_ID, DBHelper.GAME_ID);
wordsProjection.put(DBHelper.WORD_USERNAME, DBHelper.WORD_USERNAME);
wordsProjection.put(DBHelper.WORD, DBHelper.WORD);
}
public static ContentValues gameToContentValues(Game g) {
ContentValues gameTableCv = new ContentValues();
gameTableCv.put(DBHelper.GAME_ID, g.getStrId());
gameTableCv.put(DBHelper.TYPE, g.getType());
gameTableCv.put(DBHelper.PIC_URL, g.getPicUrl());
gameTableCv.put(DBHelper.CURRENT_PLAYER, g.getCurrPlayer());
gameTableCv.put(DBHelper.CREATOR, g.getGameCreator());
gameTableCv.put(DBHelper.MODE, g.getMode());
return gameTableCv;
}
public static FBMessage messageCurToMessage(Cursor c) {
if (c.getCount() < 1) {
return null;
}
return new FBMessage(c.getString(c.getColumnIndex(DBHelper.BODY)),
c.getInt(c.getColumnIndex(DBHelper.MY_ORDER)),
c.getString(c.getColumnIndex(DBHelper.USERID)),
c.getString(c.getColumnIndex(DBHelper.PIC_URL)));
}
public static Game gameCurToGame(Cursor c) {
if (c.getCount() < 1) {
return null;
}
if (c.getColumnIndex(DBHelper.CURRENT_PLAYER) != -1) {
String id = c.getString(c.getColumnIndex(DBHelper.GAME_ID));
String type = c.getString(c.getColumnIndex(DBHelper.TYPE));
String currPlayer = c.getString(c.getColumnIndex(DBHelper.CURRENT_PLAYER));
String creator = c.getString(c.getColumnIndex(DBHelper.CREATOR));
String picUrl = c.getString(c.getColumnIndex(DBHelper.PIC_URL));
String mode = c.getString(c.getColumnIndex(DBHelper.MODE));
int index;
ArrayList<String> ids = null;
ArrayList<String> names = null;
if ((index = c.getColumnIndex(DBHelper.USERLIST)) != -1) {
String userids = c.getString(c.getColumnIndex(DBHelper.USERIDS));
String userList = c.getString(index);
if (userList != null) {
names = new ArrayList<String>(Arrays.asList(userList.split(",")));
}
if (userids != null) {
ids = new ArrayList<String>(Arrays.asList(userids.split(",")));
}
}
return new Game(ids, names, creator, id, null, currPlayer, type, picUrl, mode);
}
else {
String id = c.getString(c.getColumnIndex(DBHelper.GAME_ID));
String type = c.getString(c.getColumnIndex(DBHelper.TYPE));
return new Game(null, null, null, id, null, null, type, null, null);
}
}
public static String getUserName(Context c, String userid) {
Cursor myCur = c.getContentResolver().query(USERS_URI,
new String[] {DBHelper.USER_USERNAME},
DBHelper.USERID+"=?",
new String[] {userid},
null);
myCur.moveToFirst();
if (myCur.getCount() > 0) {
String retString = myCur.getString(myCur.getColumnIndex(DBHelper.USER_USERNAME));
myCur.close();
return retString;
}
else {
return userid;
}
}
public static LinkedHashMap<String, HashMap<String, String>> wordCurToWordList(Context con, Cursor c) {
c.moveToFirst();
LinkedHashMap<String, HashMap<String, String>> wordList = new LinkedHashMap<String, HashMap<String, String>>();
while (!c.isAfterLast()) {
String word = c.getString(c.getColumnIndex(DBHelper.WORD));
String name = c.getString(c.getColumnIndex(DBHelper.WORD_USERNAME));
int order = c.getInt(c.getColumnIndex(DBHelper.MY_ORDER));
HashMap<String, String> wordToPlayer = new HashMap<String, String>();
wordToPlayer.put(word, name);
wordList.put(""+order, wordToPlayer);
c.moveToNext();
}
return wordList;
}
public static Games jsonStringToGamesList(String json) {
Gson gson2 = new Gson();
Games games = gson2.fromJson(json, Games.class);
return games;
}
public static Artists jsonStringToArtists(String json) {
Gson gson2 = new Gson();
Artists artists = gson2.fromJson(json, Artists.class);
return artists;
}
public static Movies jsonStringToMovies(String json) {
Gson gson2 = new Gson();
Movies movies = gson2.fromJson(json, Movies.class);
return movies;
}
public static TVShows jsonStringToTVShows(String json) {
Gson gson2 = new Gson();
TVShows shows = gson2.fromJson(json, TVShows.class);
return shows;
}
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count = 0;
Uri gameUri = null;
switch (uriMatcher.match(uri)) {
case GAME_ITEM:
gameUri = Uri.withAppendedPath(GAMES_URI, whereArgs[0]);
count = db.delete(GAMES_TABLE_NAME, where, whereArgs);
break;
case PLAYER_ITEM:
gameUri = Uri.withAppendedPath(USERS_URI, whereArgs[0]);
count = db.delete(USERS_TABLE_NAME, where, whereArgs);
break;
case WORD_ITEM:
gameUri = Uri.withAppendedPath(WORDS_URI, whereArgs[0]);
count = db.delete(WORDS_TABLE_NAME, where, whereArgs);
break;
case BOT_WORD_ITEM:
gameUri = Uri.withAppendedPath(BOT_WORDS_URI, whereArgs[0]);
count = db.delete(BOTWORDS_TABLE_NAME, where, whereArgs);
break;
case MESSAGE_ITEM:
gameUri = Uri.withAppendedPath(MESSAGES_URI, whereArgs[0]);
count = db.delete(MESSAGES_TABLE_NAME, where, whereArgs);
break;
case REGISTERED_FRIENDS:
count = db.delete(REGISTERED_FRIENDS_TABLE_NAME, where, whereArgs);
break;
case SCORE_ITEM:
gameUri = Uri.withAppendedPath(SCORE_URI, whereArgs[0]);
count = db.delete(SCORE_TABLE_NAME, where, whereArgs);
break;
case TEMP_WORD_ITEM:
count = db.delete(TEMP_WORDS_TABLE_NAME, where, whereArgs);
break;
case ALL:
count += db.delete(GAMES_TABLE_NAME, where, whereArgs);
count += db.delete(USERS_TABLE_NAME, null, null);
count += db.delete(WORDS_TABLE_NAME, null, null);
count += db.delete(SCORE_TABLE_NAME, null, null);
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
if (null != gameUri) {
getContext().getContentResolver().notifyChange(gameUri, null);
}
return count;
}
@Override
public String getType(Uri arg0) {
return null;
}
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
long row = 0L;
Uri notifyUri = null;
switch (uriMatcher.match(uri)) {
// games/*
case GAME_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(GAMES_URI, values.getAsString("gameid"));
}
row = db.insert(GAMES_TABLE_NAME, "", values);
break;
// users/*
case PLAYER_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(USERS_URI, values.getAsString("gameid"));
}
row = db.insert(USERS_TABLE_NAME, "", values);
break;
// words/*
case WORD_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(WORDS_URI, values.getAsString("gameid"));
}
row = db.insert(WORDS_TABLE_NAME, "", values);
break;
case BOT_WORD_ITEM:
row = db.insert(BOTWORDS_TABLE_NAME, "", values);
break;
case REGISTERED_FRIENDS:
row = db.insert(REGISTERED_FRIENDS_TABLE_NAME, "", values);
break;
case SCORE_ITEM:
if (values.containsKey("gameid")) {
notifyUri = Uri.withAppendedPath(SCORE_URI, values.getAsString("gameid"));
}
row = db.insert(SCORE_TABLE_NAME, "", values);
break;
case TEMP_WORD_ITEM:
row = db.insert(TEMP_WORDS_TABLE_NAME, "", values);
break;
case MESSAGE_ITEM:
if (values.containsKey(DBHelper.THREAD_ID)) {
notifyUri = Uri.withAppendedPath(MESSAGES_URI, values.getAsString(DBHelper.THREAD_ID));
}
row = db.insert(MESSAGES_TABLE_NAME, "", values);
Cursor q = db.query(MESSAGES_TABLE_NAME, null, DBHelper.THREAD_ID+"=?", new String[] {values.getAsString(DBHelper.THREAD_ID)}, null, null, null);
if (q.getCount() > 19) {
db.delete(MESSAGES_TABLE_NAME, DBHelper.MY_ORDER+"=?", new String[] {String.valueOf(values.getAsInteger(DBHelper.MY_ORDER)-20)});
}
q.close();
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
// if successful
if (row > 0) {
getContext().getContentResolver().notifyChange(uri, null);
if (null != notifyUri) {
getContext().getContentResolver().notifyChange(notifyUri, null);
}
return uri;
}
return null;
}
@Override
public boolean onCreate() {
dbHelper = DBHelper.getInstance(getContext(), DATABASE_NAME);
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = null;
switch (uriMatcher.match(uri)) {
case GAMES:
cursor = db.query(GAMES_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case PLAYERS:
cursor = db.query(USERS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case WORDS:
cursor = db.query(WORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case BOT_WORDS:
cursor = db.query(BOTWORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case MESSAGES:
cursor = db.query(MESSAGES_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case REGISTERED_FRIENDS:
cursor = db.query(REGISTERED_FRIENDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case SCORES:
cursor = db.query(SCORE_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
case TEMP_WORDS:
cursor = db.query(TEMP_WORDS_TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
break;
default:
throw new IllegalArgumentException("Unsupported Operation for Uri=" + uri);
}
cursor.setNotificationUri(getContext().getContentResolver(), uri);
return cursor;
}
@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
int count;
switch (uriMatcher.match(uri)) {
case GAME_ITEM:
count = db.update(GAMES_TABLE_NAME, values, where, whereArgs);
break;
default:
throw new IllegalArgumentException("Unknown URI " + uri);
}
getContext().getContentResolver().notifyChange(uri, null);
return count;
}
}
| [
"[email protected]"
] | |
6083313d85e8933ff11d4916e0a65b571edcdf6f | fc420ee4f989de2b6cf112670a52c298aee4d202 | /CifradoRino/src/cifradorino/Crypto.java | f77e7b5921b2aaaa2c75424308dafad0df312607 | [] | no_license | NeoTRAN001/Crypto | e74b8b10673b84049dee2136e2e3211e0f269903 | 2ac817f1bfaa7e4574e9af9ded9291b53543bebc | refs/heads/master | 2020-04-08T22:01:51.168585 | 2019-05-16T19:54:51 | 2019-05-16T19:54:51 | 159,768,437 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,332 | java | package cifradorino;
/**
*
* @author Neo
*/
import java.util.StringTokenizer;
public class Crypto {
public String create(String word) {
char[] arrayWord = word.toCharArray();
char auxWord;
int total = 0;
String index = "", result = "";
for(int i = 0; i < arrayWord.length; i++) {
auxWord = arrayWord[i];
System.out.println(auxWord);
if(auxWord != '1') {
for(int j = 0; j < arrayWord.length; j++) {
if(auxWord == arrayWord[j])
{
if(j == (arrayWord.length - 1)) {
arrayWord[j] = '1';
index += j; total++;
} else {
arrayWord[j] = '1';
index += j + "$"; total++;
}
}
}
} else continue;
result += auxWord + "%" + total + "╚" + index + "^";
index = ""; total = 0;
}
return word.length() + "(/>♂<)/" + result;
}
public String killRino(String word) {
StringTokenizer tokenSize = new StringTokenizer(word,"(/>♂<)/");
int size = Integer.parseInt(tokenSize.nextToken());
char[] arrayWord = new char[size];
String result = "";
char wordC;
int index, rep;
StringTokenizer tokenWord = new StringTokenizer(tokenSize.nextToken(), "^");
while(tokenWord.hasMoreElements()) {
StringTokenizer tokenChar = new StringTokenizer(tokenWord.nextToken(), "%╚$");
while(tokenChar.hasMoreElements()) {
wordC = tokenChar.nextToken().charAt(0);
rep = Integer.parseInt(tokenChar.nextToken());
for(int i = 0; i < rep; i++) {
index = Integer.parseInt(tokenChar.nextToken());
arrayWord[index] = wordC;
}
}
}
for(int i =0; i < arrayWord.length; i++) {
result += arrayWord[i];
}
return result;
}
}
| [
"[email protected]"
] | |
e2ed39346843d43ff3be09ff0c82a87ccdcba942 | 986abddca774fd196545e71da96a19c5a1f18a4f | /src/chapter2/code/ClassLoaderTest2.java | 5ac905eae4d79e5cafe0a88edf4a27dce45e71e3 | [] | no_license | yunyatian/JVMcode | 9bbda5d4a0e4f7aaf6a780dc01f921e429add6be | 7a2b0cc754dc16804ddd84bee69b3d940db0c3e1 | refs/heads/master | 2023-06-28T06:51:57.077962 | 2021-07-28T11:09:33 | 2021-07-28T11:09:33 | 385,200,203 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,289 | java | package chapter2.code;
import sun.security.ec.point.Point;
import java.net.URL;
import java.security.Provider;
public class ClassLoaderTest2 {
public static void main(String[] args) {
System.out.println("-------------启动类(引导类)加载器-----------------");
//获取bootstrapClassLoader能够加载的所有Api路径
URL[] urls = sun.misc.Launcher.getBootstrapClassPath().getURLs();
for (URL element:urls) {
System.out.println(element.toExternalForm());
}
//以上jar包任取一个解压,获取其中某一类的加载器
ClassLoader classLoader = Provider.class.getClassLoader();
System.out.println(classLoader);//null
System.out.println();
System.out.println("-------------扩展类加载器-----------------");
//获取扩展类加载器能够加载的所有API路径
String extDirs = System.getProperty("java.ext.dirs");
for (String path:extDirs.split(";")) {
System.out.println(path);
}
//以上jar包任取一个解压,获取其中某一类的加载器
ClassLoader classLoader1 = Point.class.getClassLoader();
System.out.println(classLoader1);//sun.misc.Launcher$ExtClassLoader@3af49f1c
}
}
| [
"[email protected]"
] | |
6ac4ca279ff95ec45775422f594354af71658e54 | 2c2dcf30857f38c10ebf8190d980a61cff44ca1a | /app/src/test/java/com/android/ingan/prueba/ExampleUnitTest.java | fb870ebe93425d8251d92216334f89dd4c826254 | [] | no_license | araad1992/Prueba | 84141fca5ee76d5f561dd6578a8b95cf7a83bd73 | 2e5baef0c3b02fa6f2647407fa0448f5629f2438 | refs/heads/master | 2021-01-25T06:06:59.323784 | 2017-06-06T15:46:41 | 2017-06-06T15:46:41 | 93,528,543 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | java | package com.android.ingan.prueba;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"[email protected]"
] | |
32d6e6d96cffb9022200b963100d3bf9697caf9a | 20cf48c45546b3a4ffd201079b0189c137cb8e0f | /war/src/main/java-user/com/omdasoft/orderonline/gwt/order/client/userView/presenter/UserViewPresenterImpl.java | 3dac9baee63a778c9e836a244e62cc95051d1bab | [] | no_license | winglight/orderonline | 6a1f4b5833cb77da344c3f405e8c5546bc8110db | 2cd108e85ec702e7eb49a5a44174b9d926fd498a | refs/heads/master | 2021-01-15T16:56:42.166403 | 2013-09-28T09:00:03 | 2013-09-28T09:00:03 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,442 | java | package com.omdasoft.orderonline.gwt.order.client.userView.presenter;
import net.customware.gwt.dispatch.client.DispatchAsync;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.omdasoft.orderonline.gwt.order.client.breadCrumbs.presenter.BreadCrumbsPresenter;
import com.omdasoft.orderonline.gwt.order.client.core.Platform;
import com.omdasoft.orderonline.gwt.order.client.mvp.BasePresenter;
import com.omdasoft.orderonline.gwt.order.client.mvp.ErrorHandler;
import com.omdasoft.orderonline.gwt.order.client.mvp.EventBus;
import com.omdasoft.orderonline.gwt.order.client.userAdd.dataprovider.UserWinAdapter;
import com.omdasoft.orderonline.gwt.order.client.userAdd.plugin.UserAddConstants;
import com.omdasoft.orderonline.gwt.order.client.userView.model.UserWinClient;
import com.omdasoft.orderonline.gwt.order.client.userView.request.UserViewRequest;
import com.omdasoft.orderonline.gwt.order.client.userView.request.UserViewResponse;
import com.omdasoft.orderonline.gwt.order.client.view.constant.CssStyleConstants;
import com.omdasoft.orderonline.gwt.order.client.widget.EltNewPager;
import com.omdasoft.orderonline.gwt.order.client.widget.ListCellTable;
import com.omdasoft.orderonline.gwt.order.client.win.Win;
import com.omdasoft.orderonline.gwt.order.model.user.UserRoleVo;
import com.omdasoft.orderonline.gwt.order.util.StringUtil;
public class UserViewPresenterImpl extends
BasePresenter<UserViewPresenter.UserViewDisplay> implements
UserViewPresenter {
private final DispatchAsync dispatch;
//private final SessionManager sessionManager;
private final Win win;
final ErrorHandler errorHandler;
private final BreadCrumbsPresenter breadCrumbs;
String staffId;
boolean colleague=false;
EltNewPager pager;
ListCellTable<UserWinClient> cellTable;
UserWinAdapter listViewAdapter;
@Inject
public UserViewPresenterImpl(EventBus eventBus, UserViewDisplay display,
DispatchAsync dispatch, Win win,
BreadCrumbsPresenter breadCrumbs, ErrorHandler errorHandler) {
super(eventBus, display);
this.dispatch = dispatch;
// this.sessionManager = sessionManager;
this.errorHandler = errorHandler;
this.win = win;
this.breadCrumbs = breadCrumbs;
}
@Override
public void bind() {
breadCrumbs.loadChildPage("用户详细信息");
display.setBreadCrumbs(breadCrumbs.getDisplay().asWidget());
init();
registerHandler(display.getupadateBtnClickHandlers().addClickHandler(
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Platform.getInstance()
.getEditorRegistry()
.openEditor(
UserAddConstants.EDITOR_STAFFADD_SEARCH,
"EDITOR_STAFFADD_SEARCH_DO_ID", staffId);
}
}));
}
void init() {
if(colleague==true)
{
display.displayUpdateBtn(colleague);
}
dispatch.execute(new UserViewRequest(staffId),
new AsyncCallback<UserViewResponse>() {
@Override
public void onFailure(Throwable t) {
win.alert(t.getMessage());
}
@Override
public void onSuccess(UserViewResponse resp) {
display.setStaffNo(resp.getStaffNo());
display.setStaffName(resp.getStaffName());
display.setPhone(resp.getPhone());
if(resp.getUserRoleVos()!=null && resp.getUserRoleVos().size()>0)
{
String roleString="";
for (UserRoleVo role:resp.getUserRoleVos()) {
if(role==UserRoleVo.CORP_ADMIN)
roleString+="管理员;";
if(role==UserRoleVo.DEPT_MGR)
roleString+="分店管理员;";
}
if(!StringUtil.isEmpty(roleString))
display.getStaffRoles().setText(roleString);
else
display.getStaffRoles().getElement().getParentElement().getParentElement().addClassName(CssStyleConstants.hidden);
}
else
{
display.getStaffRoles().getElement().getParentElement().getParentElement().addClassName(CssStyleConstants.hidden);
}
}
});
}
@Override
public void initUserView(String staffId) {
this.staffId = staffId;
}
@Override
public void initUserView_Colleague(String staffId,boolean colleague) {
this.staffId = staffId;
this.colleague=colleague;
}
}
| [
"[email protected]"
] | |
ddd620f10b0fd29370b7309a0374fe85fe1e4903 | 5db5f33faab148887324b1a01cdb6373b14d4ead | /app/src/main/java/com/zjzf/shoescircleandroid/model/GoodsListInfo.java | d2d6c4410e4097c1efa8123d9ee24b871fa2cca0 | [] | no_license | UserChenille/Android-ShoesCircle | 745ce70a23638d6dfa446e67342b091779a87833 | 66fa171227f6c28b75c95f03cd9d9699a7e159a1 | refs/heads/master | 2020-04-30T01:33:27.315683 | 2019-03-20T06:27:11 | 2019-03-20T06:27:11 | 176,531,765 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,727 | java | package com.zjzf.shoescircleandroid.model;
import com.zjzf.shoescircle.lib.base.baseadapter.MultiType;
import java.util.List;
/**
* Created by 陈志远 on 2018/8/5.
*/
public class GoodsListInfo {
/**
* offset : 0
* limit : 2147483647
* total : 8
* size : 1
* pages : 8
* current : 1
* searchCount : true
* openSort : true
* orderByField : id
* records : [{"id":1015889815853224000,"enable":1,"createTime":"2018-07-08 09:29:37","memId":1,"member":{"id":1,"enable":1,"createTime":"2018-07-08 08:46:54","account":"hehaoyang","phone":"15857193035","memName":"何昊阳","avatar":"","sex":0,"evaluate":5,"score":0,"level":1},"name":"乔丹6","photo":"tfhf23121312","freightNo":"AA223AA5","size":"41,42","price":111,"state":1}]
* condition : null
* asc : true
* offsetCurrent : 0
*/
private int offset;
private int limit;
private int total;
private int size;
private int pages;
private int current;
private boolean searchCount;
private boolean openSort;
private String orderByField;
private Object condition;
private boolean asc;
private int offsetCurrent;
private List<RecordsBean> records;
public int getOffset() {
return offset;
}
public void setOffset(int offset) {
this.offset = offset;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
public boolean isSearchCount() {
return searchCount;
}
public void setSearchCount(boolean searchCount) {
this.searchCount = searchCount;
}
public boolean isOpenSort() {
return openSort;
}
public void setOpenSort(boolean openSort) {
this.openSort = openSort;
}
public String getOrderByField() {
return orderByField;
}
public void setOrderByField(String orderByField) {
this.orderByField = orderByField;
}
public Object getCondition() {
return condition;
}
public void setCondition(Object condition) {
this.condition = condition;
}
public boolean isAsc() {
return asc;
}
public void setAsc(boolean asc) {
this.asc = asc;
}
public int getOffsetCurrent() {
return offsetCurrent;
}
public void setOffsetCurrent(int offsetCurrent) {
this.offsetCurrent = offsetCurrent;
}
public List<RecordsBean> getRecords() {
return records;
}
public void setRecords(List<RecordsBean> records) {
this.records = records;
}
public static class RecordsBean implements MultiType {
/**
* id : 1015889815853224000
* enable : 1
* createTime : 2018-07-08 09:29:37
* memId : 1
* member : {"id":1,"enable":1,"createTime":"2018-07-08 08:46:54","account":"hehaoyang","phone":"15857193035","memName":"何昊阳","avatar":"","sex":0,"evaluate":5,"score":0,"level":1}
* name : 乔丹6
* photo : tfhf23121312
* freightNo : AA223AA5
* size : 41,42
* price : 111
* state : 1
*/
private long id;
private int enable;
private String createTime;
private int memId;
private MemberBean member;
private String name;
private String photo;
private String freightNo;
private String size;
private int price;
private int state;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public int getMemId() {
return memId;
}
public void setMemId(int memId) {
this.memId = memId;
}
public MemberBean getMember() {
return member;
}
public void setMember(MemberBean member) {
this.member = member;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getFreightNo() {
return freightNo;
}
public void setFreightNo(String freightNo) {
this.freightNo = freightNo;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
@Override
public int getItemType() {
return 0;
}
public static class MemberBean {
/**
* id : 1
* enable : 1
* createTime : 2018-07-08 08:46:54
* account : hehaoyang
* phone : 15857193035
* memName : 何昊阳
* avatar :
* sex : 0
* evaluate : 5
* score : 0
* level : 1
*/
private int id;
private int enable;
private String createTime;
private String account;
private String phone;
private String memName;
private String avatar;
private int sex;
private int evaluate;
private int score;
private int level;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getEnable() {
return enable;
}
public void setEnable(int enable) {
this.enable = enable;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getMemName() {
return memName;
}
public void setMemName(String memName) {
this.memName = memName;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public int getEvaluate() {
return evaluate;
}
public void setEvaluate(int evaluate) {
this.evaluate = evaluate;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
}
}
}
| [
"[email protected]"
] | |
86e644bbc2e859fd8c2972bf97bcbb895cdf16f1 | 89a8bb56d27ab4479a5e5f0b49f368e2d70b09ff | /src/main/java/web/UsuarioFiltrar.java | c9193834651c3d72eb5e971b2053d95b0f7e1a07 | [] | no_license | renzorodrigues/Leilao-de-Livros | 6bfa6c0d2b90f21a2995b093e20f5bfe398e9fe6 | beacae1a3b27c857086b30f235ae142f41b9c80d | refs/heads/master | 2021-01-21T13:25:42.277708 | 2016-05-31T02:07:52 | 2016-05-31T02:07:52 | 53,894,888 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 907 | java | package web;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dominio.Usuario;
import servico.UsuarioServico;
@WebServlet("/usuarios/filtrar")
public class UsuarioFiltrar extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String DESTINO = "/usuarios/listar.jsp";
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UsuarioServico uS = new UsuarioServico();
String nome = request.getParameter("busca");
List<Usuario> itens = uS.buscarPorNome(nome);
request.setAttribute("itens", itens);
request.getRequestDispatcher(DESTINO).forward(request, response);
}
}
| [
"[email protected]"
] | |
5d8726548e494da03ae22a84ab3c1d81a7fb6812 | 9b1fc35c32ae6acd6bbde87d9184735bb8f1ea6f | /1/Fundamental/src/controlflow/Main.java | fc8d992ebaef59f5927b63ac269289d88cf61a77 | [] | no_license | adasoraninda/mosh-java | b599f13b5b778515f65b7de4260185a63acaa401 | bf02c5f03498afa5e4814d8bbab1b2de28dc475d | refs/heads/main | 2023-05-07T02:18:47.101729 | 2021-06-14T06:07:01 | 2021-06-14T06:07:01 | 376,719,807 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,406 | java | package controlflow;
import java.text.NumberFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final byte MONTHS_IN_YEAR = 12;
final byte PERCENT = 100;
final int PRINCIPAL_MINIMUM = 1000;
final int PRINCIPAL_MAXIMUM = 1_000_000;
final float ANNUAL_INTEREST_MINIMUM = 1F;
final float ANNUAL_INTEREST_MAXIMUM = 30F;
final byte YEARS_MINIMUM = 1;
final byte YEARS_MAXIMUM = 30;
Scanner scanner = new Scanner(System.in);
int principal = 0;
float annualInterest = 0F;
float monthlyInterest = 0F;
byte years = 0;
int numberOfPayments = 0;
// Principal
while (true) {
System.out.print("Principal ($1K - $1M): ");
principal = scanner.nextInt();
if (principal >= PRINCIPAL_MINIMUM && principal <= PRINCIPAL_MAXIMUM) {
break;
}
System.out.println("Enter a number between 1,000 and 1,000,000.");
}
// Annual Interest
while (true) {
System.out.print("Annual Interest Rate: ");
annualInterest = scanner.nextFloat();
if (annualInterest >= ANNUAL_INTEREST_MINIMUM && annualInterest <= ANNUAL_INTEREST_MAXIMUM) {
monthlyInterest = annualInterest / PERCENT / MONTHS_IN_YEAR;
break;
}
System.out.println("Enter a value greater than " + (int) ANNUAL_INTEREST_MINIMUM
+ " and less than or equal to " + (int) ANNUAL_INTEREST_MAXIMUM + ".");
}
// Years
while (true) {
System.out.print("Period (Years): ");
years = scanner.nextByte();
if (years >= YEARS_MINIMUM && years <= YEARS_MAXIMUM) {
numberOfPayments = years * MONTHS_IN_YEAR;
break;
}
System.out.println("Enter a value between " + YEARS_MINIMUM + " and " + YEARS_MAXIMUM + ".");
}
double mortgage = principal * (monthlyInterest * Math.pow(1 + monthlyInterest, numberOfPayments))
/ (Math.pow(1 + monthlyInterest, numberOfPayments) - 1);
String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage: " + mortgageFormatted);
scanner.close();
}
}
| [
"[email protected]"
] | |
e0b4af7fdb51748b8d54ba32608dd7f5a1df1a8c | 09c9ee4b342571423ada8186c881b4fca1660a07 | /src/main/java/org/primefaces/showcase/view/input/CheckboxView2.java | 5062ba55458e76cef63adc38508d88524a19ecbf | [] | no_license | GeorgeSalu/Primefaces | 4a0c93a14c922ab8c53066fd1675d2017c2478a5 | 9f77599c6f5edb5a7eaf891c39665b131472d9de | refs/heads/master | 2020-06-24T19:19:47.327176 | 2016-12-22T00:30:58 | 2016-12-22T00:30:58 | 74,625,395 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 347 | java | package org.primefaces.showcase.view.input;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class CheckboxView2 {
private String[] selectedConsoles;
public String[] getSelectedConsoles() {
return selectedConsoles;
}
public void setSelectedConsoles(String[] selectedConsoles) {
this.selectedConsoles = selectedConsoles;
}
}
| [
"[email protected]"
] | |
e7b31bd6063436cd53ddce419ed8f30527bfad0e | 2f8264af5cb8f89a3c48f25a5724f036a8af5976 | /Android/Day1(21.05.28)/CalcculationLayout/app/src/androidTest/java/com/aoslec/calcculationlayout/ExampleInstrumentedTest.java | 68652627102a746980f8e53d3e931680e5bc3659 | [] | no_license | ReplaceMyBrain/Class | 731c9988cf226a2f971412a84e3ddb205188f09b | b214e0c456ca3665f116903fa75e7fbe5fe85abd | refs/heads/main | 2023-07-12T21:04:04.401420 | 2021-08-27T18:53:48 | 2021-08-27T18:53:48 | 352,622,172 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 772 | java | package com.aoslec.calcculationlayout;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.aoslec.calcculationlayout", appContext.getPackageName());
}
} | [
"[email protected]"
] | |
a742ecf4ea58c5bca8930ab04591b7e0b212f81f | 5cb1f58740c658712b514696d9df284b3000ab8c | /src/main/java/com/mn/data/GifRepositoryImpl.java | e785ce3a5e13ac7f68fdbf2545486548f7b7b0d7 | [] | no_license | michaln889/DemotyApp | eb44163ec8df78e905fe75b8aef26281d8103b69 | 780bfd84a537a25443b2295ba8062a5ac2d23f89 | refs/heads/master | 2021-01-19T09:08:31.662506 | 2017-12-19T18:47:57 | 2017-12-19T18:47:57 | 87,725,323 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,176 | java | package com.mn.data;
import com.mn.model.Gif;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Repository
public class GifRepositoryImpl implements GifRepository
{
private List<Gif> allGifs = Arrays.asList(
new Gif(1, "gif1", "aaa", LocalDate.now(), false, 1),
new Gif(2, "gif2", "bbb", LocalDate.now(), true, 2),
new Gif(3, "gif3", "ccc", LocalDate.now(), true, 3),
new Gif(4, "gif4", "ddd", LocalDate.now(), false, 1),
new Gif(5, "gif5", "eee", LocalDate.now(), true, 2),
new Gif(6, "2841-1792494-StickSkok", "fff", LocalDate.now(), false, 2)
);
@Autowired
private UserRepository userRepository;
@Override
public List<Gif> findAll()
{
return allGifs;
}
@Override
public Gif findByName(String name)
{
for(Gif el : allGifs)
{
if(el.getName().equals(name))
{
return el;
}
}
return null;
}
@Override
public List<Gif> findFavorites()
{
List<Gif> gifs = new ArrayList<>();
for(Gif el : allGifs)
{
if(el.isFavorite())
{
gifs.add(el);
}
}
return gifs;
}
@Override
public List<Gif> findByCategoryId(int id)
{
List<Gif> gifs = new ArrayList<>();
for(Gif el : allGifs)
{
if(el.getCategoryId() == id)
{
gifs.add(el);
}
}
return gifs;
}
@Override
public Gif findById(int id) {
for(Gif el : allGifs)
{
if(el.getId() == id)
{
return el;
}
}
return null;
}
@Override
public void makeFavoriteOrUnfavorite(Gif gif) {
if(!gif.isFavorite())
{
gif.setFavorite(true);
}
else
{
gif.setFavorite(false);
}
}
}
| [
"[email protected]"
] | |
e91a61ba34fd6e70b54e818ce9841dfeea89f1dd | b770b8799b43ca5ffe2fea9b293fb37d929c80cc | /JavaExamples/src/examples/google/GoogleSample2.java | 1962088a0394043be4d118f62baa01cead354ddd | [] | no_license | Malifter/Examples | 868a2714a962782343524cde64d15f2a46cfe5fd | 16ab6ef818dd370ae10e0405b2bcd8b1735f3c8c | refs/heads/master | 2021-01-10T17:03:55.661693 | 2016-01-09T01:45:34 | 2016-01-09T01:45:34 | 46,088,244 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,770 | java | package examples.google;
public class GoogleSample2 {
public static void main(String [] args) {
String S = "dir1\n"
+ " dir11\n"
+ " dir12\n"
+ " picturepicturepicturepicturepicture.jpeg\n"
+ " dir121\n"
+ " file1.txt\n"
+ " dir3\n"
+ " file3.txt\n"
+ " dir5\n"
+ " longpicture.png\n"
+ " dir4\n"
+ "dir2\n"
+ " longpicturelongpicture.gif\n";
System.out.println(solution3(S));
}
// O(n) if we solve it backwards because now we don't have to backtrack at all
public static int solution3(String S) {
int max = 0;
String [] parts = S.split("\n");
max = solution3Recursive(parts, parts.length, parts.length-1, "");
return max;
}
public static int solution3Recursive(String [] parts, int lastLevel, int i, String path) {
if(i == -1) return 0;
String part = parts[i];
int level = part.lastIndexOf(' ') + 1;
part = part.replaceAll("\\s+", "");
int max = 0;
if(level > lastLevel) {
path = "/" + part;
} else if(level < lastLevel) {
path = "/" + part + path;
} else if((part.contains(".jpeg") ||
part.contains(".png") ||
part.contains(".gif")) &&
part.length()+1 > path.length()) {
path = "/" + part;
}
System.out.println(path);
max = Math.max(path.length(), solution3Recursive(parts, level, i-1, path));
return max;
}
// O(h*n) time complexity
public static int solution2(String S) {
int max = 0;
String [] parts = S.split("\n");
max = solution2Recursive(parts, -1, 0, "");
return max;
}
public static int solution2Recursive(String [] parts, int lastLevel, int i, String path) {
if(i == parts.length) return 0;
String part = parts[i];
int level = part.lastIndexOf(' ') + 1;
part = part.replaceAll("\\s+", "");
int max = 0;
if(level > lastLevel) {
path += "/" + part;
} else if(level < lastLevel) {
for(int dif = (lastLevel - level); dif > 0; dif--) {
path = path.substring(0, path.lastIndexOf('/'));
}
if(level == 0) {
path = "/" + part;
} else {
path = path.substring(0, path.lastIndexOf('/'));
path += "/" + part;
}
} else {
path = path.substring(0, path.lastIndexOf('/'));
path += "/" + part;
}
System.out.println(path);
max = Math.max(max, solution2Recursive(parts, level, i+1, path));
if((path.contains(".jpeg") ||
path.contains(".png") ||
path.contains(".gif") &&
level >= lastLevel)) {
return Math.max(max, path.length());
}
return max;
}
// O(h*n) time complexity
public static int solution1(String S) {;
String longestPath = "";
String currentPath = "";
String [] parts = S.split("\n");
int lastLevel = -1;
for(int i = 0; i < parts.length; i++) {
String part = parts[i];
int level = part.lastIndexOf(' ')+1;
part = part.replaceAll("\\s+", "");
if(level > lastLevel) {
currentPath += "/" + part;
} else if(level < lastLevel) {
for(int dif = (lastLevel - level); dif > 0; dif--) {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
}
if(level == 0) {
currentPath = "/" + part;
} else {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
currentPath += "/" + part;
}
} else {
currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
currentPath += "/" + part;
}
lastLevel = level;
if((currentPath.contains(".jpeg") ||
currentPath.contains(".png") ||
currentPath.contains(".gif")) &&
currentPath.length() > longestPath.length()) {
longestPath = currentPath;
}
System.out.println(currentPath);
}
return longestPath.length();
}
}
| [
"[email protected]"
] | |
6514d45bf854a4c77a8fea62f61735af14656d5c | 78a7a33adca4836c51c5fa7811150d535b19313d | /src/main/java/com/pms/model/appointment/AppointmentKey.java | 30be80cad6b82c51d7cbbade71706b13e0aed8d2 | [] | no_license | DimMilios/Pms-backend | 4390d095a92709d6698b4980cf2479f72030f451 | 574dd608586d90aab5847390e41a53b74c8dc052 | refs/heads/master | 2023-07-19T13:27:54.495311 | 2022-05-03T09:11:36 | 2022-05-03T09:11:36 | 231,906,841 | 0 | 0 | null | 2023-07-07T21:57:03 | 2020-01-05T11:26:02 | Java | UTF-8 | Java | false | false | 1,153 | java | package com.pms.model.appointment;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class AppointmentKey implements Serializable {
@Column(name = "doctor_id")
private Long doctorId;
@Column(name = "ssn")
private Long patientSsn;
public void setDoctorId(Long doctorId) {
this.doctorId = doctorId;
}
public void setPatientSsn(Long patientSsn) {
this.patientSsn = patientSsn;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AppointmentKey that = (AppointmentKey) o;
return Objects.equals(doctorId, that.doctorId) &&
Objects.equals(patientSsn, that.patientSsn);
}
@Override
public int hashCode() {
return Objects.hash(doctorId, patientSsn);
}
@Override
public String toString() {
return "AppointmentKey{" +
"doctorId=" + doctorId +
", patientSsn=" + patientSsn +
'}';
}
}
| [
"[email protected]"
] | |
6bbdb65bf9e04c83465bdfaa8a939bb6ee579761 | b38ebf4de362aeb74a5ce8a2e0f9fa0f94208147 | /src/java/com/proyectoCFIP/entities/Profesiograma.java | 02d7a5dd61d151419e341da5d0b18c45d947f2d9 | [] | no_license | juanCodoba/ultima | 7c14815ef3961cff30ead6fc81b197808ede680a | 3bb7eda388bbef9aa777649ffd7da72195355f52 | refs/heads/master | 2020-04-01T03:11:04.715528 | 2019-09-09T22:14:11 | 2019-09-09T22:14:11 | 152,812,536 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,226 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.proyectoCFIP.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author Luis Carlos Cabal
*/
@Entity
@Table(name = "profesiograma")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Profesiograma.findAll", query = "SELECT p FROM Profesiograma p"),
@NamedQuery(name = "Profesiograma.findByIdProfesiograma", query = "SELECT p FROM Profesiograma p WHERE p.idProfesiograma = :idProfesiograma"),
@NamedQuery(name = "Profesiograma.findByDescripcion", query = "SELECT p FROM Profesiograma p WHERE p.descripcion = :descripcion")
})
public class Profesiograma implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id_profesiograma")
private Integer idProfesiograma;
@Size(max = 255)
@Column(name = "descripcion")
private String descripcion;
@JoinColumn(name = "id_tipo_profesiograma", referencedColumnName = "id_tipo_profesiograma")
@ManyToOne(optional = true)
private TipoProfesiograma idTipoProfesiograma;
@Size(max = 1000000)
@Column(name = "url_profesiograma")
private String urlProfesiograma;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "idProfesiograma")
private List<Cargos> cargosList;
public Profesiograma() {
}
public Profesiograma(Integer idProfesiograma) {
this.idProfesiograma = idProfesiograma;
}
public Profesiograma(Integer idProfesiograma, TipoProfesiograma idTipoProfesiograma) {
this.idProfesiograma = idProfesiograma;
this.idTipoProfesiograma = idTipoProfesiograma;
}
public Integer getIdProfesiograma() {
return idProfesiograma;
}
public void setIdProfesiograma(Integer idProfesiograma) {
this.idProfesiograma = idProfesiograma;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public TipoProfesiograma getIdTipoProfesiograma() {
return idTipoProfesiograma;
}
public void setIdTipoProfesiograma(TipoProfesiograma idTipoProfesiograma) {
this.idTipoProfesiograma = idTipoProfesiograma;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idProfesiograma != null ? idProfesiograma.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Profesiograma)) {
return false;
}
Profesiograma other = (Profesiograma) object;
if ((this.idProfesiograma == null && other.idProfesiograma != null) || (this.idProfesiograma != null && !this.idProfesiograma.equals(other.idProfesiograma))) {
return false;
}
return true;
}
@Override
public String toString() {
return getDescripcion();
}
public List<Cargos> getCargosList() {
return cargosList;
}
public void setCargosList(List<Cargos> cargosList) {
this.cargosList = cargosList;
}
public String getUrlProfesiograma() {
return urlProfesiograma;
}
public void setUrlProfesiograma(String urlProfesiograma) {
this.urlProfesiograma = urlProfesiograma;
}
}
| [
"Luis Carlos Cabal"
] | Luis Carlos Cabal |
186307cb1c3a4b7c0348fabed0946004695d747e | 6e4cdb5b2aa1307cb25fb2581acb520caedfc029 | /Exercises_Threads_1_Fall_2015/src/main/java/Exercise_2/evenClass.java | fc9a61046bf8d8825a2caf0c4d6e4adf64efda17 | [] | no_license | PhilipWestChristiansen/sp2 | b35d005789e6dd834d7341d5b8cf4f68f4cbe82c | d4ae296d901e788425ce35ea29b5af6c2b671393 | refs/heads/master | 2020-05-20T23:50:36.405201 | 2016-09-02T12:13:11 | 2016-09-02T12:13:11 | 67,219,732 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 175 | java | package Exercise_2;
public class evenClass {
private static int n = 0;
public synchronized static int next() {
n++;
n++;
return n;
}
}
| [
"[email protected]"
] | |
93d7485f2b76ff488691c8804e3aa647cb2d6e4d | 05835a7bcf0446786d5ae2d1d8402666bbd62798 | /hermes-monitor/src/main/java/com/ctrip/hermes/monitor/service/KafkaMonitor.java | 9266b1d14cb2de43dc64e9b33b8f1b695b46a66f | [
"Apache-2.0"
] | permissive | richarwu/hermes | 10f4b56d03b2d5974dd98a58d542c06586079ad7 | 80ca70a7067114f4d22d4336cf0032aaaaaf695d | refs/heads/master | 2021-01-18T00:11:30.688586 | 2015-11-04T03:34:59 | 2015-11-04T03:34:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,539 | java | package com.ctrip.hermes.monitor.service;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.elasticsearch.action.index.IndexResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.ctrip.hermes.monitor.Bootstrap;
import com.ctrip.hermes.monitor.config.MonitorConfig;
import com.ctrip.hermes.monitor.domain.MonitorItem;
import com.ctrip.hermes.monitor.stat.StatResult;
import com.ctrip.hermes.monitor.zabbix.ZabbixApiGateway;
import com.ctrip.hermes.monitor.zabbix.ZabbixConst;
import com.zabbix4j.ZabbixApiException;
import com.zabbix4j.history.HistoryObject.HISOTRY_OBJECT_TYPE;
import com.zabbix4j.host.HostObject;
import com.zabbix4j.item.ItemObject;
@Service
public class KafkaMonitor implements IZabbixMonitor {
private static final Logger logger = LoggerFactory.getLogger(KafkaMonitor.class);
public static void main(String[] args) throws Throwable {
ConfigurableApplicationContext context = SpringApplication.run(Bootstrap.class);
KafkaMonitor monitor = context.getBean(KafkaMonitor.class);
monitor.monitorPastHours(24 * 2, 5);
context.close();
}
@Autowired
private ESMonitorService service;
@Autowired
private ZabbixApiGateway zabbixApi;
@Autowired
private MonitorConfig config;
@Scheduled(cron = "0 5 * * * *")
public void monitorHourly() throws Throwable {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Date timeTill = cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, -1);
Date timeFrom = cal.getTime();
monitorKafka(timeFrom, timeTill);
}
private void monitorKafka(Date timeFrom, Date timeTill) throws Throwable {
Map<Integer, HostObject> kafkaHosts = zabbixApi.searchHostsByName(config.getZabbixKafkaBrokerHosts());
Map<Integer, StatResult> messageInStat = statMessageIn(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> byteInStat = statByteIn(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> byteOutStat = statByteOut(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> failedProduceRequestsStat = statFailedProduceRequests(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> failedFetchRequestsStat = statFailedFetchRequests(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestQueueSizeStat = statRequestQueueSize(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestRateProduceStat = statRequestRateProduce(timeFrom, timeTill, kafkaHosts);
Map<Integer, StatResult> requestRateFetchConsumerStat = statRequestRateFetchConsumer(timeFrom, timeTill,
kafkaHosts);
Map<Integer, StatResult> requestRateFetchFollowerStat = statRequestRateFetchFollower(timeFrom, timeTill,
kafkaHosts);
int MINUTE_IN_SECONDS = (int) ((timeTill.getTime() - timeFrom.getTime()) / 1000 / 60);
for (Integer hostid : kafkaHosts.keySet()) {
Map<String, Object> stat = new HashMap<String, Object>();
stat.put("kafka.messagein.sumbymin", messageInStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.messagein.meanbysec", messageInStat.get(hostid).getMean());
stat.put("kafka.bytein.sumbymin", byteInStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.bytein.meanbysec", byteInStat.get(hostid).getMean());
stat.put("kafka.byteout.sumbymin", byteOutStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.byteout.meanbysec", byteOutStat.get(hostid).getMean());
stat.put("kafka.failedproducerequest.sumbymin", failedProduceRequestsStat.get(hostid).getSum()
* MINUTE_IN_SECONDS);
stat.put("kafka.failedproducerequest.meanbysec", failedProduceRequestsStat.get(hostid).getMean());
stat.put("kafka.failedfetchrequest.sumbymin", failedFetchRequestsStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.failedfetchrequest.meanbysec", failedFetchRequestsStat.get(hostid).getMean());
stat.put("kafka.requestqueuesize.meanbysec", requestQueueSizeStat.get(hostid).getMean());
stat.put("kafka.produce.sumbymin", requestRateProduceStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.produce.meanbysec", requestRateProduceStat.get(hostid).getMean());
stat.put("kafka.fetchconsumer.sumbymin", requestRateFetchConsumerStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.fetchconsumer.meanbysec", requestRateFetchConsumerStat.get(hostid).getMean());
stat.put("kafka.fetchfollower.sumbymin", requestRateFetchFollowerStat.get(hostid).getSum() * MINUTE_IN_SECONDS);
stat.put("kafka.fetchfollower.meanbysec", requestRateFetchFollowerStat.get(hostid).getMean());
MonitorItem item = new MonitorItem();
item.setCategory(ZabbixConst.CATEGORY_KAFKA);
item.setSource(ZabbixConst.SOURCE_ZABBIX);
item.setStartDate(timeFrom);
item.setEndDate(timeTill);
item.setHost(kafkaHosts.get(hostid).getHost());
item.setGroup(ZabbixConst.GROUP_KAFKA_BROKER);
item.setValue(stat);
try {
IndexResponse response = service.prepareIndex(item);
logger.info(response.getId());
} catch (IOException e) {
logger.warn("Save item failed", e);
}
}
}
public void monitorPastHours(int hours, int requestIntervalSecond) throws Throwable {
for (int i = hours - 1; i >= 0; i--) {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.add(Calendar.HOUR_OF_DAY, -i);
Date timeTill = cal.getTime();
cal.add(Calendar.HOUR_OF_DAY, -1);
Date timeFrom = cal.getTime();
monitorKafka(timeFrom, timeTill);
try {
Thread.sleep(requestIntervalSecond * 1000);
} catch (InterruptedException e) {
}
}
}
private Map<Integer, StatResult> statByteIn(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(), ZabbixConst.KAFKA_BYTE_IN_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Bytes In(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Bytes In(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statByteOut(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(), ZabbixConst.KAFKA_BYTE_OUT_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Bytes Out(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Bytes Out(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statFailedFetchRequests(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_FAILED_FETCH_REQUESTS);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += validResult.getSum() * 60;
logger.info(String.format(
"%14s Failed Fetch Request(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts.get(hostid)
.getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Failed Fetch Request(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statFailedProduceRequests(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_FAILED_PRODUCE_REQUESTS);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format(
"%14s Failed Produce Request(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Failed Produce Request(%s - %s) %,12d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statMessageIn(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_MESSAGE_IN_RATE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Message In(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)", hosts
.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Message In(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestQueueSize(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_QUEUE_SIZE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getMean() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += validResult.getMean();
logger.info(String.format("%14s Request Queue Size(%s - %s) %,9.0f(By Second) ", hosts.get(hostid).getHost(),
timeFrom, timeTill, validResult.getMean()));
}
logger.info(String.format("%14s Request Queue Size(%s - %s) %,12d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateFetchConsumer(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_FETCHCONSUMER);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Fetch Consumer(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Fetch Consumer(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateFetchFollower(Date timeFrom, Date timeTill,
Map<Integer, HostObject> hosts) throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_FETCHFOLLOWER);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Fetch Follower(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Fetch Follower(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
private Map<Integer, StatResult> statRequestRateProduce(Date timeFrom, Date timeTill, Map<Integer, HostObject> hosts)
throws ZabbixApiException {
Map<Integer, List<ItemObject>> ids = zabbixApi.searchItemsByName(hosts.keySet(),
ZabbixConst.KAFKA_REQUEST_RATE_PRODUCE);
Map<Integer, StatResult> result = new HashMap<Integer, StatResult>();
long totalSum = 0;
for (Integer hostid : hosts.keySet()) {
Map<Integer, StatResult> statResults = zabbixApi.getHistoryStat(timeFrom, timeTill, hostid, ids.get(hostid),
HISOTRY_OBJECT_TYPE.INTEGER);
StatResult validResult = new StatResult();
for (StatResult value : statResults.values()) {
if (value.getSum() > 0) {
validResult = value;
break;
}
}
result.put(hostid, validResult);
totalSum += (validResult.getSum() * 60);
logger.info(String.format("%14s Produce(%s - %s) Sum: %,15.0f(By Minute), Mean: %,9.0f(By Second)",
hosts.get(hostid).getHost(), timeFrom, timeTill, validResult.getSum() * 60, validResult.getMean()));
}
logger.info(String.format("%14s Produce(%s - %s) %,15d ", "Total", timeFrom, timeTill, totalSum));
return result;
}
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.