text
stringlengths
10
2.72M
package code.enemy; import code.achievments.AchievementController; import code.achievments.GameMessage; import code.buttons.ButtonController; import code.global.GlobalVariables; import code.graphics.FurnitureObjects; import code.intersectObjects.IntersectsObjectLevel1; import code.player.Player; import code.player.Sprite; import javafx.animation.AnimationTimer; import javafx.scene.image.Image; import javafx.scene.paint.Color; import java.util.ArrayDeque; import java.util.concurrent.atomic.AtomicInteger; public class MonstersController { private static final int MONSTER_IMAGE_REQUESTED_WIDTH = 50; private static final int MONSTER_IMAGE_REQUESTED_HEIGHT = 44; private static final int MAXIMUM_MONSTERS_COUNT = 15; private static final int ATTACK_SOUND_VOLUME = 1; private static final int ATTACK_SOUND_BALANCE = 0; private static final double ATTACK_SOUND_RATE = 1.0; private static final double ATTACK_SOUND_PAN = 0.0; private static final int ATTACK_SOUND_PRIORITY = -5; private static final int GAME_OVER_MESSAGE_DURATION = 100000000; private static final int PLAYER_MIN_HEALTH = 0; private static final int MONSTERS_MAX_COUNT = 200; private static final int GAME_OVER_MESSAGE_X = 317; private static final int GAME_OVER_MESSAGE_Y = 299; private static final int MONSTER_RANDOM_POSITION_ADDITION = 100; private static final String IMG_MONSTER_TYPE1 = "img/monster.gif"; private static final String IMG_MONSTER_TYPE2 = "img/monster1.png"; private static final String IMG_MONSTER_TYPE3 = "img/monster2.png"; private static final String PLAYER_HIT_MONSTER_TEXT = "Ouch!"; private static final String GAME_OVER_TEXT = "Bugs owned the house and ate you, Game Over!"; private static ArrayDeque<String> monstersImages; public static void setMonsterImages() { monstersImages = new ArrayDeque<>(); monstersImages.addLast(IMG_MONSTER_TYPE1); monstersImages.addLast(IMG_MONSTER_TYPE2); monstersImages.addLast(IMG_MONSTER_TYPE3); } public static void createMonsters() { GlobalVariables.setMonsterList(new ArrayDeque<>()); for (int i = 0; i < MAXIMUM_MONSTERS_COUNT; i++) { Sprite monster = new Sprite(); String tempImage = monstersImages.pop(); monstersImages.addLast(tempImage); Image monsterImage = new Image(tempImage, MONSTER_IMAGE_REQUESTED_WIDTH, MONSTER_IMAGE_REQUESTED_HEIGHT, false, false); monster.setImage(monsterImage); GlobalVariables.getMonsterList().add(monster); } } public static void checkCollision(AnimationTimer animationTimer) { AchievementController AM = new AchievementController(Player.getInstance(), GlobalVariables.getGraphicContext(), GlobalVariables.getRoot()); GameMessage GM = new GameMessage(Player.getInstance(), GlobalVariables.getRoot()); for (Sprite monster : GlobalVariables.getMonstersToRender()) { if (Player.getInstance().intersects(monster)) { GM.renderMessage(PLAYER_HIT_MONSTER_TEXT, 2, Color.RED, Player.getInstance().getX(), Player.getInstance().getY()); if (!GlobalVariables.getMute()[0] && !GlobalVariables.getAttack().isPlaying()) { GlobalVariables.getAttack().play(ATTACK_SOUND_VOLUME, ATTACK_SOUND_BALANCE, ATTACK_SOUND_RATE, ATTACK_SOUND_PAN, ATTACK_SOUND_PRIORITY); } if ((int) Player.getInstance().getPlayerHealth() <= PLAYER_MIN_HEALTH) GM.renderMessage(GAME_OVER_TEXT, GAME_OVER_MESSAGE_DURATION, Color.RED, GAME_OVER_MESSAGE_X, GAME_OVER_MESSAGE_Y); Player.getInstance().subtractPlayerHealth(); if (Player.getInstance().getPlayerHealth() <= PLAYER_MIN_HEALTH) { GlobalVariables.getRoot().getChildren().remove(ButtonController.buttonQuit); GlobalVariables.getRoot().getChildren().add(ButtonController.buttonQuit); GlobalVariables.getRoot().getChildren().remove(ButtonController.buttonStartNewGame); GlobalVariables.getRoot().getChildren().add(ButtonController.buttonStartNewGame); animationTimer.stop(); } AM.observe(); } } } public static void displayMonsters(AtomicInteger monsterCounter) { IntersectsObjectLevel1 intersectObject = new IntersectsObjectLevel1(); monsterCounter.addAndGet(1); if (monsterCounter.get() == MONSTERS_MAX_COUNT) { Sprite tempMonster = GlobalVariables.getMonsterList().pop(); GlobalVariables.getMonsterList().addLast(tempMonster); double px = (Player.getInstance().getX() * Math.random() + MONSTER_RANDOM_POSITION_ADDITION); double py = (Player.getInstance().getY() * Math.random() + MONSTER_RANDOM_POSITION_ADDITION); tempMonster.setPosition(px, py); if (!intersectObject.intersect(tempMonster)) { GlobalVariables.getMonstersToRender().add(tempMonster); } monsterCounter.set(0); } for (Sprite monster : GlobalVariables.getMonstersToRender()) { monster.render(GlobalVariables.getGraphicContext()); } } }
package com.rachelgrau.rachel.health4theworldstroke.Activities; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.GridView; import com.rachelgrau.rachel.health4theworldstroke.Adapters.MusicAdapter; import com.rachelgrau.rachel.health4theworldstroke.R; public class ChatBotMusic extends AppCompatActivity { String[] audio_name; int[] file_time; int position_2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chatbot_music); GridView gridview = (GridView) findViewById(R.id.grid_view); gridview.setNumColumns(3); /*gridview.setAdapter(new MusicAdapter(this));*/ // Initializing a new String Array audio_name = new String[]{ "Acoustic Guitar Piano", "Acoustic Loop", "Acoustic Loop 2", "Ambient Background Music", "Dawn", "Gymnopedie", "Happy Gmaj Piano", "Acoustic Guitar Jam", "Just a Smile", "Life", "Melodic Acoustic Music", "Melodic Piano Atmosphere", "Mid Summer Evening", "Mozart Piano Sonata", "Sit Back And Relax Ambient", "Sleeping Peacefully", "Sunrise Without You", "Sweet Sweet Dreams", "Under The Ocean Sun", "Welcome Home", "Yesterday" }; file_time = new int[] { R.drawable.fill1, R.drawable.fill2, R.drawable.fill3, R.drawable.fill4, R.drawable.fill5, R.drawable.fill6, R.drawable.fill7, R.drawable.fill8, R.drawable.fill9, R.drawable.fill10, R.drawable.fill11, R.drawable.fill12, R.drawable.fill13, R.drawable.fill14, R.drawable.fill15, R.drawable.fill16, R.drawable.fill17, R.drawable.fill18, R.drawable.fill19, R.drawable.fill20, R.drawable.fill21 }; // Data bind GridView with MusicAdapter (String Array elements) gridview.setAdapter(new MusicAdapter(this, audio_name, file_time)); gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { position_2=position; music_player(position_2); } }); } public void music_player(int audio_Index) { Intent intent=new Intent(this,music_player.class); intent.putExtra("audio_position",audio_Index); startActivity(intent); } }
package com.binarysprite.evemat.page.blueprint.data; import java.io.Serializable; /** * * @author Tabunoki * */ public class CharaterSelect implements Serializable { private final long id; private final String characterName; public CharaterSelect(long id, String name) { super(); this.id = id; this.characterName = name; } public long getId() { return id; } public String getCharacterName() { return characterName; } }
package model; public class GeneticAlgorithm { private static int populationSize = 10; private static int maxGenerations = 10000; private static double mutationRate = 0.5; public static Chromosome generateTimeTable(){ Generator gen = Generator.getInstance(); gen.initializePopulation(populationSize); gen.getPopulation().calculateAllFitness(); Utilities.printPopulation(gen.getPopulation()); int generationCount = 0; System.out.println("Generation: " + generationCount + " averageFitness: " + gen.getPopulation().getAverageFitness()+" Fittest: " + gen.getPopulation().getFittestScore()+ "\n"); while (gen.getPopulation().getFittestScore() < 1 && generationCount < maxGenerations) { generationCount++; //Do selection gen.selection(); //Do crossover gen.crossover(); //Do mutation under a random probability gen.mutation(mutationRate); //Add fittest offspring to population gen.addOffSpring(); //Calculate new fitness value gen.getPopulation().calculateAllFitness(); Utilities.printPopulation(gen.getPopulation()); System.out.println("Generation: " + generationCount + " averageFitness: " + gen.getPopulation().getAverageFitness()+" Fittest: " + gen.getPopulation().getFittestScore()); } if((Math.abs(gen.getPopulation().getFittestScore() - 1.0)) < 1e-9) return gen.getPopulation().getFittestChromosome(); else return null; } }
package DuckHunt.GUI; import DuckHunt.Constant.Request; import DuckHunt.Constant.Responses; import DuckHunt.Global.GameGlobalVariables; import DuckHunt.Main.Game; import DuckHunt.Request.GroupDetails; import DuckHunt.Request.Response; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXPasswordField; import com.jfoenix.controls.JFXTextField; import javafx.animation.FadeTransition; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.RowConstraints; import javafx.scene.text.*; import javafx.util.Duration; public class GroupSelect extends GridPane { private JFXTextField clientName; private JFXTextField groupName; private JFXPasswordField password; private Text error; public GroupSelect(){ setPrefSize(600,600); // setHgap(10); setVgap(20); HBox buttonContainer = new HBox(); buttonContainer.setPrefHeight(100); buttonContainer.setPrefWidth(100); buttonContainer.getChildren().addAll(buttonCreater("Create Group"),buttonCreater("Join Group"),buttonCreater("Random")); Text text1 = textCreater("Your Name"); Text text2 = textCreater("Group Name"); Text text3 = textCreater("Password"); error = textCreater(""); Font f = error.getFont(); clientName = new JFXTextField(); groupName = new JFXTextField(); password = new JFXPasswordField(); clientName.setFont(Font.font("verdana", FontWeight.LIGHT, FontPosture.REGULAR, 18)); groupName.setFont(Font.font("verdana", FontWeight.LIGHT, FontPosture.REGULAR, 18)); password.setFont(Font.font("verdana", FontWeight.LIGHT, FontPosture.REGULAR, 18)); getColumnConstraints().addAll(new ColumnConstraints(300),new ColumnConstraints(300)); getRowConstraints().addAll(new RowConstraints(100),new RowConstraints(100),new RowConstraints(100),new RowConstraints(100),new RowConstraints(100),new RowConstraints(100)); add(text1, 0, 0); add(text2, 0, 1); add(text3, 0, 2); add(clientName, 1, 0); add(groupName, 1, 1); add(password, 1, 2); add(error,0,5,2,1); add(buttonContainer,0,3,2,2); init(); } private void init() { setOpacity(0); FadeTransition fadeTransition = new FadeTransition(Duration.millis(2000),this); fadeTransition.setFromValue(0.0); fadeTransition.setToValue(1.0); setLayoutX(1920/2 - 600/2); setLayoutY(1080/2 - 600/2); fadeTransition.play(); } public JFXButton buttonCreater(String str){ JFXButton button = new JFXButton(); button.setPrefHeight(100); button.setPrefWidth(200); button.setText(str); button.setFont(Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 20)); button.setTextAlignment(TextAlignment.CENTER); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { clickEventHandller(((JFXButton)e.getTarget()).getText()); } }); return button; } public Text textCreater(String str){ Text text = new Text(str); text.setFont(Font.font("verdana", FontWeight.LIGHT, FontPosture.REGULAR, 18)); return text; } public void clickEventHandller(String str) { System.out.println(str); if (str.equals("Create Group")) { createAction(); } else if (str.equals("Join Group")) { joinAction(); } else if (str.equals("Random")) { randomAction(); } } private void randomAction() { if (clientName.getText().equals("" )) { error.setText("Please enter name."); return; } GameGlobalVariables.getInstance().getGamer().sendMessage(new GroupDetails("", "", clientName.getText(), String.valueOf(Request.RANDOM))); Response response = (Response) GameGlobalVariables.getInstance().getGamer().receiveMessage(); error.setText(response.getErrorMessage()); if(response.getStatus().equals(Responses.OK)) { GameGlobalVariables.getInstance().getGamer().setName(clientName.getText(),response.getErrorMessage()); nextStage(); }else{ } } private void joinAction() { if (groupName.getText()=="" || password.getText()=="" || clientName.getText()=="") { error.setText("Please enter name and Password."); return; } GameGlobalVariables.getInstance().getGamer().sendMessage(new GroupDetails(password.getText(), groupName.getText(), clientName.getText(), String.valueOf(Request.JOINGROUP))); Response response = (Response) GameGlobalVariables.getInstance().getGamer().receiveMessage(); error.setText(response.getErrorMessage()); if(response.getStatus().equals(Responses.OK)) { GameGlobalVariables.getInstance().getGamer().setName(clientName.getText(),groupName.getText()); nextStage(); }else{ } } private void createAction() { if (groupName.getText()=="" || password.getText()=="" || clientName.getText()=="") { error.setText("Please enter name and Password."); return; } GameGlobalVariables.getInstance().getGamer().sendMessage(new GroupDetails(password.getText(), groupName.getText(), clientName.getText(), String.valueOf(Request.CREATEGROUP))); Response response = (Response) GameGlobalVariables.getInstance().getGamer().receiveMessage(); error.setText(response.getErrorMessage()); if(response.getStatus().equals(Responses.OK)) { GameGlobalVariables.getInstance().getGamer().setName(clientName.getText(),groupName.getText()); GameGlobalVariables.getInstance().getGamer().makeOwner(); nextStage(); }else{ } } private void nextStage() { System.out.println("Ready for Group Wait"); Group group = (Group)this.getScene().getRoot(); ObservableList<Node> observableList = group.getChildren(); observableList.remove(this); observableList.add(new GroupView()); } }
package com.example.dolly0920.week8; import java.io.SerializablePermission; public class CustomObjectStreamConstants { private CustomObjectStreamConstants() {} public static final short STREAM_MAGIC = (short) 0xaced; public static final short STREAM_VERSION = 5; public static final byte TC_BASE = 0x70; public static final byte TC_NULL = (byte) 0x70; public static final byte TC_REFERENCE = (byte) 0x71; public static final byte TC_CLASSDESC = (byte) 0x72; public static final byte TC_OBJECT = (byte) 0x73; public static final byte TC_STRING = (byte) 0x74; public static final byte TC_ARRAY = (byte) 0x75; public static final byte TC_CLASS = (byte) 0x76; public static final byte TC_BLOCKDATA = (byte) 0x77; public static final byte TC_ENDBLOCKDATA = (byte) 0x78; public static final byte TC_RESET = (byte) 0x79; public static final byte TC_BLOCKDATALONG = (byte) 0x7A; public static final byte TC_EXCEPTION = (byte) 0x7B; public static final byte TC_LONGSTRING = (byte) 0x7C; public static final byte TC_PROXYCLASSDESC = (byte) 0x7D; public static final byte TC_ENUM = (byte) 0x7E; public static final byte TC_MAX = (byte) 0x7E; public static final int baseWireHandle = 0x7e0000; public static final byte SC_WRITE_METHOD = 0x01; public static final byte SC_BLOCK_DATA = 0x08; public static final byte SC_SERIALIZABLE = 0x02; public static final byte SC_EXTERNALIZABLE = 0x04; public static final byte SC_ENUM = 0x10; public static final SerializablePermission SUBSTITUTION_PERMISSION = new SerializablePermission("enableSubstitution"); public static final SerializablePermission SUBCLASS_IMPLEMENTATION_PERMISSION = new SerializablePermission("enableSubclassImplementation"); public static final SerializablePermission SERIAL_FILTER_PERMISSION = new SerializablePermission("serialFilter"); public static final int PROTOCOL_VERSION_1 = 1; public static final int PROTOCOL_VERSION_2 = 2; }
package com.yukai.monash.student_seek; import android.app.Fragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SearchView; import android.widget.Toast; import com.dexafree.materialList.card.Card; import com.dexafree.materialList.card.CardProvider; import com.dexafree.materialList.card.OnActionClickListener; import com.dexafree.materialList.card.action.TextViewAction; import com.dexafree.materialList.listeners.RecyclerItemClickListener; import com.dexafree.materialList.view.MaterialListView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.squareup.picasso.Picasso; import org.json.JSONException; import org.json.JSONObject; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import cz.msebera.android.httpclient.Header; import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator; /** * Created by yukaima on 8/05/16. */ public class searchFragment extends Fragment { private SearchView searchView; private Context mContext; private MaterialListView mListView; private ArrayList<JobModel> jobsArrayList; private SharedPreferenceHelper sharedPreferenceHelper; private static final String UserIconUrlPrefix = "http://173.255.245.239/jobs/image/"; public static searchFragment newInstance() { searchFragment sampleFragment = new searchFragment(); return sampleFragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search, container, false); searchView = (SearchView) view.findViewById(R.id.searchView); mListView = (MaterialListView) view.findViewById(R.id.material_listview); sharedPreferenceHelper = new SharedPreferenceHelper(getContext(),"Login Credentials"); //set searchview to show search box // searchView.setIconifiedByDefault(true); //set searchview submitButton searchView.setSubmitButtonEnabled(true); //set searchview background searchView.setBackgroundColor(getResources().getColor(R.color.searchview_bg)); //set hint on searchview searchView.setQueryHint("Search(e.g.sales,hostess)"); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { searchJobs(query); return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); //set card views mContext = getActivity(); mListView.setItemAnimator(new SlideInLeftAnimator()); mListView.getItemAnimator().setAddDuration(300); mListView.getItemAnimator().setRemoveDuration(300); //set empty view in card views final ImageView emptyView = (ImageView) view.findViewById(R.id.imageView); emptyView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); mListView.setEmptyView(emptyView); Picasso.with(getActivity()) .load("https://www.skyverge.com/wp-content/uploads/2012/05/github-logo.png") .resize(100, 100) .centerInside() .into(emptyView); // Add the ItemTouchListener mListView.addOnItemTouchListener(new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(@NonNull Card card, int position) { int index = Integer.parseInt("" + card.getTag()); String employerid = jobsArrayList.get(index).getEmployerid(); String jobid = jobsArrayList.get(index).getJobid(); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); String userid = sharedPreferenceHelper.loadPreferences("userid"); params.add("emp_id", employerid); params.add("jobid", jobid); params.add("userid", userid); client.post(getContext(), "http://173.255.245.239/jobs/apply_job.php", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = new String(responseBody); JSONObject object = null; try { object = new JSONObject(response); String success = object.getString("message"); if (success.equals("0")) { Toast.makeText(getContext(), "Error,Please try later.", Toast.LENGTH_LONG).show(); } else if (success.equals("1")) { Toast.makeText(getContext(), "Apply successfully.", Toast.LENGTH_LONG).show(); } else if (success.equals("2")) { Toast.makeText(getContext(), "You have applied this job already.", Toast.LENGTH_LONG).show(); } } catch (JSONException e) { } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } @Override public void onItemLongClick(@NonNull Card card, int position) { Log.d("LONG_CLICK", "" + card.getTag()); } }); getJobsArrayList(); return view; } public void searchJobs(String query) { jobsArrayList = new ArrayList<JobModel>(); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); Log.d("query",query); params.add("keyword",query); client.post(getContext(), "http://173.255.245.239/jobs/get_jobs_info.php", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = new String(responseBody); JsonReader reader = new JsonReader(new StringReader(response)); //reader.setLenient(true); if(responseBody.length > 0) { jobsArrayList = new Gson().fromJson(reader, new TypeToken<List<JobModel>>() { }.getType()); mListView.getAdapter().clearAll(); fillArray(jobsArrayList); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } private void fillArray(ArrayList<JobModel> jobsArrayListParam) { List<Card> cards = new ArrayList<>(); try { for (int i = 0; i < jobsArrayListParam.size(); i++) { String desc = jobsArrayListParam.get(i).getJobdesc(); String company = jobsArrayListParam.get(i).getCompany(); String companyFileName = jobsArrayListParam.get(i).getCompanyPicFile(); String picUrl = UserIconUrlPrefix + companyFileName + ".png"; cards.add(getRandomCard(i, desc, company, picUrl)); } }catch (NullPointerException e){} mListView.getAdapter().addAll(cards); } private Card getRandomCard(final int position,String company,String desciptionParam,String picUrl) { // String title = "Job number " + (position + 1); String description = desciptionParam; final CardProvider provider = new Card.Builder(getActivity()) .setTag(""+position) .setDismissible() .withProvider(new CardProvider()) .setLayout(R.layout.material_image_with_buttons_card) // .setTitle(title) .setDescription(company) .setDrawable(picUrl) .addAction(R.id.left_text_button, new TextViewAction(getActivity()) .setText(description) .setTextResourceColor(R.color.black_button)) .addAction(R.id.right_text_button, new TextViewAction(getActivity()) .setText("Apply") .setTextResourceColor(R.color.accent_material_dark) .setListener(new OnActionClickListener() { @Override public void onActionClicked(View view, Card card) { // Toast.makeText(mContext, position, Toast.LENGTH_SHORT).show(); } })); if (position % 2 == 0) { provider.setDividerVisible(true); } return provider.endConfig().build(); } private Card generateNewCard() { return new Card.Builder(getActivity()) .setTag("BASIC_IMAGE_BUTTONS_CARD") .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_image_buttons_card_layout) .setTitle("I'm new") .setDescription("I've been generated on runtime!") .setDrawable(R.drawable.ic_favorite) .endConfig() .build(); } public ArrayList<JobModel> getJobsArrayList() { jobsArrayList = new ArrayList<JobModel>(); AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); client.post(getContext(), "http://173.255.245.239/jobs/get_jobs_info.php", params, new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { String response = new String(responseBody); JsonReader reader = new JsonReader(new StringReader(response)); //reader.setLenient(true); jobsArrayList = new Gson().fromJson(reader, new TypeToken<List<JobModel>>() {}.getType()); fillArray(jobsArrayList); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); return jobsArrayList; } }
package com.socialportal.domain.blog.model; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.List; @Document(collection = "blogEntries") public class BlogEntry { @Id private String entryId; private String title; private String text; private String userDisplayName; private String userDisplayId; private List<BlogEntryComment> comments; public String getUserDisplayName() { return userDisplayName; } public void setUserDisplayName(String userDisplayName) { this.userDisplayName = userDisplayName; } public String getUserDisplayId() { return userDisplayId; } public void setUserDisplayId(String userDisplayId) { this.userDisplayId = userDisplayId; } public String getEntryId() { return entryId; } public void setEntryId(String entryId) { this.entryId = entryId; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public List<BlogEntryComment> getComments() { return comments; } public void setComments(List<BlogEntryComment> comments) { this.comments = comments; } }
package com.example.hhx.teacher; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.hhx.teacher.bmob.LoginBmob; import com.example.hhx.teacher.dbHelper.MyDbHelper; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.SaveListener; public class Registered extends AppCompatActivity { private Button button; private EditText et1,et2,et3; private MyDbHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registered); button= (Button) findViewById(R.id.button_re); et1= (EditText) findViewById(R.id.editText_re); et2= (EditText) findViewById(R.id.editText2_re); et3= (EditText) findViewById(R.id.editText3_re); et2.setTransformationMethod(PasswordTransformationMethod.getInstance()); et3.setTransformationMethod(PasswordTransformationMethod.getInstance()); dbHelper=new MyDbHelper(this,"login.db",null,1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { click(); } }); } private void click(){ Boolean show=true; String user; String psw; String psw2; user=et1.getText().toString(); psw=et2.getText().toString(); psw2=et3.getText().toString(); if(user.isEmpty()&&show){ Toast.makeText(this,"用户名不能为空",Toast.LENGTH_SHORT).show(); show=false; } if(user.length()!=12&&show){ Toast.makeText(this,"用户名为12为学号",Toast.LENGTH_SHORT).show(); show=false; } if(psw.isEmpty()&&show){ Toast.makeText(this,"密码不能为空",Toast.LENGTH_SHORT).show(); show=false; } if(!psw.equals(psw2)&&show){ Toast.makeText(this,"两次密码不相等",Toast.LENGTH_SHORT).show(); show=false; } if(show){ SQLiteDatabase db=dbHelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put("username",user); values.put("password",psw); db.insert("Login",null,values); LoginBmob loginbb=new LoginBmob(); loginbb.setUsername(user); loginbb.setPassword(psw); loginbb.save(new SaveListener<String>() { @Override public void done(String s, BmobException e) { } }); Toast.makeText(this,"注册成功",Toast.LENGTH_LONG).show(); Intent intent=new Intent(Registered.this,MainActivity.class); startActivity(intent); } } }
package com.dh.comunicacao.comunicacaoactivityfragment; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import com.dh.comunicacao.R; public class MainActivity extends AppCompatActivity implements FragmentListener { private CallbackFragment callbackFragment = new CallbackFragment(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_ati_frag); //o que é isso - e -> :) findViewById(R.id.buttonAttach).setOnClickListener(e -> attachFragment()); findViewById(R.id.buttonDetach).setOnClickListener(e -> detachFragment()); } private void attachFragment(){ getSupportFragmentManager() .beginTransaction() .add(R.id.frameLayout, callbackFragment) .commit(); } private void detachFragment(){ getSupportFragmentManager() .beginTransaction() .remove(callbackFragment) .commit(); } @Override public void answerFragment(String message) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show(); } }
package com.redrocket.photoeditor.screens.presentation; import android.content.Context; /** * Базовый интерфейс для всех view в терминах MVP. */ public interface MvpView { Context getContext(); }
package com.kab.chatclient.dummy; import android.content.Context; import com.kab.chatclient.Utility; import java.util.Random; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.TimeUnit.SECONDS; /** * Created by Kraskovskiy on 21.09.16. */ public class SenderMessageScheduler { private static final int UPDATE_TIME_SEED = 6; private static int sUpdateTime = 6; private static Boolean sIsCanceled = false; private ScheduledExecutorService mScheduler = Executors.newScheduledThreadPool(1); public void sendMessageSchedule(final Context context) { mScheduler.schedule(new Runnable() { @Override public void run() { Utility.saveMessageInDb(context, Utility.messageGenerator(context)); changeUpdateTime(UPDATE_TIME_SEED); if (!sIsCanceled) { sendMessageSchedule(context); } } } , sUpdateTime, SECONDS); } public void startScheduler() { sIsCanceled = false; } public void stopScheduler() { sIsCanceled = true; mScheduler.shutdownNow(); } private void changeUpdateTime(int timeSeed) { Random rnd = new Random(); sUpdateTime = rnd.nextInt(timeSeed) + 1; } }
package sample; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import sample.main.FileUtil; import java.io.IOException; public class Main extends Application{ private static Stage stage; @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("login/Login.fxml")); primaryStage.setTitle("Media Watcher Login"); primaryStage.setScene(new Scene(root, 750, 600)); setStage(primaryStage); primaryStage.show(); } public static void main(String[] args){ try{ FileUtil.init(); }catch(IOException e){ e.printStackTrace(); } launch(args); } public static void setStage(Stage stage){ Main.stage = stage; } public static Stage getStage(){ return Main.stage; } }
package com.web.common; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.io.Serializable; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import com.web.common.user.UserMemDTO; import com.web.framework.logging.Log; import com.web.framework.logging.LogFactory; import com.web.framework.util.StringUtil; import com.oreilly.servlet.MultipartRequest; public class BaseAction implements Serializable{ private static boolean isParamDebug = true; //parameter디버깅 public static boolean isXMLDebug = false; //XML디버깅 public static String PARAMFAIL_MNG = ""; //param값 이상유무시메시지 public static String ERROR_FORWARD = "/jsp/imagefax/common/error.jsp"; //에러페이지. // TODO: Action Param Debug boolean. static Log log = LogFactory.getLog("BASE init"); /** * 세션정보를 셋팅하여 넘김. * @param req * @return * @throws Exception */ public static UserMemDTO getSession(HttpServletRequest req) throws Exception{ UserMemDTO newUserInfo = null; try{ HttpSession session = req.getSession(); newUserInfo = new UserMemDTO(); newUserInfo.setUserId((String)session.getAttribute("USERID")); newUserInfo.setUserNm((String)session.getAttribute("USERNAME")); newUserInfo.setGroupid((String)session.getAttribute("GROUPID")); newUserInfo.setGroupname((String)session.getAttribute("GROUPNAME")); newUserInfo.setAuthid((String)session.getAttribute("AUTHID")); newUserInfo.setAuthname((String)session.getAttribute("AUTHNAME")); newUserInfo.setExcelauth((String)session.getAttribute("EXCELAUTH")); newUserInfo.setFaxno((String)session.getAttribute("FAXNO")); newUserInfo.setPhone((String)session.getAttribute("PHONE")); newUserInfo.setFaxnoFormat((String)session.getAttribute("FAXNOFOMAT")); newUserInfo.setPhoneFormat((String)session.getAttribute("PHONEFORMAT")); newUserInfo.setGroupfaxview((String)session.getAttribute("GROUPFAXVIEW")); if(newUserInfo == null || newUserInfo.getUserId().equals("")){ // log.error("세션 작업중 오류", new Throwable()); } } catch (Exception e) { log.error(e.getMessage(), e); } return newUserInfo; } /** * 세션 유효 체크여부. * @param req * @return * @throws Exception */ public static boolean isSession(HttpServletRequest req) throws Exception { try{ HttpSession session = req.getSession(false); String userID =(String)session.getAttribute("USERID"); if(userID == null || userID.equals("")){ return false; } } catch (Exception e) { log.error(e.getMessage(), e); } return true; } public static void setLoginForward(HttpServletRequest request, String strAction, String strCmd) throws Exception{ ArrayList l = new ArrayList(); Enumeration e1 = request.getParameterNames(); String name = null; String[] strTemp = null; HashMap m = null; int iCnt = 0; while (e1.hasMoreElements()){ name = e1.nextElement().toString(); if(request.getParameterValues(name) != null && request.getParameterValues(name).length > 1) { strTemp = request.getParameterValues(name); for(int i = 0; i < strTemp.length; i++){ m = new HashMap(); if( StringUtil.isNotNull(strCmd) && "cmd".equals(name) ){ m.put(name, strCmd); } else { m.put(name, strTemp[i]); } l.add(m); } } else { m = new HashMap(); if( StringUtil.isNotNull(strCmd) && "cmd".equals(name) ){ m.put(name, strCmd); } else { m.put(name, request.getParameter(name)); } l.add(m); } iCnt++; } HttpSession session = request.getSession(false); session.setAttribute("LoginREQUEST", l); session.setAttribute("LoginCMD", strAction); } /** * 파라메타 넘어온 값을 로그에 남김. * 개발테스트용으로 씀. * @param request * @param strMsg * @throws Exception */ public static void printPrameter(HttpServletRequest request, Class strMsg) throws Exception{ if( isParamDebug ){ Enumeration e1 = request.getParameterNames(); String name = null; String[] strTemp = null; int iCnt = 0; log.debug("============================= Param Value Start ["+strMsg.getName()+"]==========="); while (e1.hasMoreElements()){ name = e1.nextElement().toString(); if(request.getParameterValues(name) != null && request.getParameterValues(name).length > 1) { strTemp = request.getParameterValues(name); for(int i = 0; i < strTemp.length; i++) log.debug("*= "+ iCnt + " \t[" + name + "\t:" + i + "]\t\t = \t" + strTemp[i]); } else { log.debug("= " + iCnt + " \t[" + name + "]\t\t = \t" + request.getParameter(name)); } iCnt++; } } } public static void printPrameter(MultipartRequest request, Class strMsg) throws Exception{ if( isParamDebug ){ Enumeration e1 = request.getParameterNames(); String name = null; String[] strTemp = null; int iCnt = 0; log.debug("============================= Param Value Start ["+strMsg.getName()+"]==========="); while (e1.hasMoreElements()){ name = e1.nextElement().toString(); if(request.getParameterValues(name) != null && request.getParameterValues(name).length > 1) { strTemp = request.getParameterValues(name); for(int i = 0; i < strTemp.length; i++) log.debug("*= "+ iCnt + " \t[" + name + "\t:" + i + "]\t\t = \t" + strTemp[i]); } else { log.debug("= " + iCnt + " \t[" + name + "]\t\t = \t" + request.getParameter(name)); } iCnt++; } } } public static void printPrameter(HttpServletRequest request, String strMsg) throws Exception{ if( isParamDebug ){ Enumeration e1 = request.getParameterNames(); String name = null; String[] strTemp = null; int iCnt = 0; log.debug("============================= Param Value Start ["+strMsg+"]==========="); while (e1.hasMoreElements()){ name = e1.nextElement().toString(); if(request.getParameterValues(name) != null && request.getParameterValues(name).length > 1) { strTemp = request.getParameterValues(name); for(int i = 0; i < strTemp.length; i++) log.debug("*= "+ iCnt + " \t[" + name + "\t:" + i + "]\t\t = \t" + strTemp[i]); } else { log.debug("= " + iCnt + " \t[" + name + "]\t\t = \t" + request.getParameter(name)); } iCnt++; } } } public static void SesseionLogout( String SesstionID, String UserID ) { CommonDAO comDao=new CommonDAO(); LogInDTO loginDto=new LogInDTO(); loginDto.setUserID( UserID ); loginDto.setSessionID( SesstionID ); try { comDao.setLogoutHistory(loginDto); } catch (Exception e) { } } }
package com.dokyme.alg4.sorting.basic; import com.dokyme.alg4.sorting.CompareUtil; import com.dokyme.alg4.sorting.Sorting; import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.Stopwatch; import static com.dokyme.alg4.sorting.basic.Example.*; import java.util.*; /** * Created by intellij IDEA.But customed by hand of Dokyme. * * @author dokym * @date 2018/3/10-15:08 * Description: */ public class Shell implements Sorting { @Override public void sort(Comparable[] a, Comparator c) { throw new RuntimeException(); } public static boolean compare(Comparable[] a, Comparable[] b) { for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { return false; } } return true; } public boolean check(Comparable[] a) { Comparable[] backup = new Comparable[a.length]; for (int i = 0; i < a.length; i++) { backup[i] = a[i]; } sort(a); if (!compare(a, backup)) { return false; } Arrays.sort(backup); if (!compare(a, backup)) { return false; } return true; } public static void sort(double[] a) { int si = 0; while (hArray[si + 1] < a.length) { si++; } while (si >= 0) { for (int i = 0; i < a.length; i++) { for (int j = i; j >= hArray[si] && a[j] < a[j - hArray[si]]; j -= hArray[si]) { double d = a[j]; a[j] = a[j - hArray[si]]; a[j - hArray[si]] = d; } } si--; } } @Override public void sort(Comparable[] a) { int N = a.length; int h = hArray[a.length]; while (h >= 1) { for (int i = 0; i < N; i++) { for (int j = i; j >= h && Example.less(a[j], a[j - h]); j -= h) { Example.exch(a, j, j - h); } } h = h / 3; } } public static int[] geometric(int g) { int[] seq = new int[1 << 10]; seq[0] = 1; for (int i = 1; i < seq.length; i++) { seq[i] = seq[i - 1] * g; } return seq; } public static int[] sedgewick() { int[] seq = new int[1 << 10]; int i = 0, j = 2; int c = 0; int value1 = 1; int value2 = 5; while (c < seq.length) { if (value1 < value2) { seq[c++] = value1; i++; value1 = Double.valueOf(9 * Math.pow(4.0, i * 1.0) - 9 * Math.pow(2.0, i * 1.0) + 1).intValue(); } else { seq[c++] = value2; j++; value2 = Double.valueOf(Math.pow(4.0, j * 1.0) - 3 * Math.pow(2.0, j * 1.0) + 1).intValue(); } } return seq; } public static int[] gonnet() { int[] seq = new int[1 << 20]; seq[0] = 1; for (int i = 1; i < seq.length; i++) { seq[i] = 2 * seq[i - 1] + 1; } return seq; } public static int[] hibbard() { int[] seq = new int[1 << 20]; seq[0] = 1; for (int i = 1; i < seq.length; i++) { seq[i] = 2 * seq[i - 1] + 1; } return seq; } public static int[] shell() { int[] seq = new int[1 << 20]; seq[0] = 1; for (int i = 1; i < seq.length; i++) { seq[i] = 2 * seq[i - 1]; } return seq; } public static int[] knuth() { int i = 1, h = 1; int[] seq = new int[1 << 20]; while (i < seq.length) { while (i < (h + 1) * 3 && i < seq.length) { seq[i] = h; i++; } h = 3 * h + 1; } return seq; } public static double testSpecifiedSequence(int times, int length, int[] hArray) { double[] array = new double[length]; double t = 0.0; for (int i = 0; i < times; i++) { for (int j = 0; j < array.length; j++) { array[j] = StdRandom.uniform(); } Stopwatch stopwatch = new Stopwatch(); sort(array, hArray); t += stopwatch.elapsedTime(); if (i % 10 == 0) { StdOut.println(i); } } return t; } public static void sort(double[] a, int[] hArray) { int N = a.length; int hi = 0; for (; hi < hArray.length && hArray[hi] < N; hi++) { } while (hi >= 0) { for (int i = 0; i < a.length; i++) { for (int j = i; j >= hArray[hi] && a[j] < a[j - 1]; j -= hArray[hi]) { Example.exch(a, j, j - hArray[hi]); } } hi--; } } public static void sort(Comparable[] a, int[] hArray) { int hi = 0; int N = a.length; for (; hi < hArray.length && N > hArray[hi]; hi++) { } while (hi >= 0) { for (int i = 0; i < a.length; i++) { for (int j = i; j >= hArray[hi] && a[j].compareTo(a[j - hArray[hi]]) < 0; j -= hArray[hi]) { Example.exch(a, j, j - hArray[hi]); } } hi--; } } public static void sort(Comparable[] a, boolean x) { int N = a.length; int h = hArray[a.length]; Map<Integer, Double> comparsionFactor = new LinkedHashMap(); while (h >= 1) { int time = 0; for (int i = 0; i < N; i++) { for (int j = i; j >= h; j -= h) { time++; if (Example.less(a[j], a[j - h])) { Example.exch(a, j, j - h); } else { break; } } } comparsionFactor.put(h, (double) time / (double) N); h = h / 3; } System.out.println("N=" + a.length); for (Map.Entry<Integer, Double> hi : comparsionFactor.entrySet()) { System.out.println("\th=" + hi.getKey() + "\tcomparsion/N=" + hi.getValue()); } System.out.println(); } public static void main(String[] args) { double[] a = new double[1000]; for (int i = 0; i < 1000; i++) { a[i] = StdRandom.uniform(); } sort(a); assert isSorted(a); } public static int[] hArray; static { int i = 1, h = 1; hArray = new int[1 << 25]; while (i < hArray.length) { while (i < (h + 1) * 3 && i < hArray.length) { hArray[i] = h; i++; } h = 3 * h + 1; } } }
package webBasedPopup; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.chrome.ChromeDriver; public class HiddenDivisionPopup { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver","./drivers/chromedriver.exe");//we avoid IllegalStateException we set the path of driver executable file ChromeDriver driver=new ChromeDriver();// launch the chrome browser driver.manage().window().maximize();//maximize the browser // driver.get("https://www.cleartrip.com/"); // Actions act = new Actions(driver); // Actions target = act.moveToElement(driver.findElement(By.xpath("//div[@class='flex flex-middle p-relative homeCalender']"))); // Thread.sleep(5000); // driver.findElement(By.xpath("//div[@class='flex flex-middle p-relative homeCalender']")).click(); Thread.sleep(3000); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("window.scrollBy(0,4500)");//down Thread.sleep(2000); driver.findElement(By.xpath("//button[.='Mon, Jun 7']")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//div[@class='p-1 day-gridContent flex flex-middle flex-column flex-center flex-top' and .='18']")).click(); } }
package com.bitwise.ticketbooking; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.RequestDispatcher; 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 javax.servlet.http.HttpSession; public class DeletMovieServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session =request.getSession(); MovieList list = (MovieList)session.getAttribute("movielist"); PrintWriter out=response.getWriter(); RequestDispatcher rd = request.getRequestDispatcher("DisplayMovie.jsp"); String name=(String)request.getParameter("moviename"); String tname=(String)request.getParameter("theatername"); int seats=Integer.parseInt(request.getParameter("seats")); String stime=(String)request.getParameter("stime"); String etime=(String)request.getParameter("etime"); list.deletMovie(new Movie(name,tname,seats,stime,etime)); out.println("<font color='blue'>Movie deleted successfully</font><br>"); rd.include(request, response); out.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
import java.io.IOException; /** * A fake appendable that only throws exceptions, intending to fail to write to it. */ public class MockFailAppendable implements Appendable { /** * Would append given sequence to the structure, but instead only throws an exception. * * @param csq would be a character sequence to be appended * @return would return the appendable itself, with updated content * @throws IOException if writing fails, which we care about! */ @Override public Appendable append(CharSequence csq) throws IOException { throw new IOException(); } /** * Would append given sequence to the structure, but instead only throws an exception. * * @param csq would be a character sequence to be appended * @param start would be where to start the append * @param end would be where to end the append * @return would return the appendable itself, with updated content * @throws IOException if writing fails, which we care about! */ @Override public Appendable append(CharSequence csq, int start, int end) throws IOException { throw new IOException(); } /** * Would append given character to the structure, but instead only throws an exception. * * @param c would be a character to be appended * @return would return the appendable itself, with updated content * @throws IOException if writing fails, which we care about! */ @Override public Appendable append(char c) throws IOException { throw new IOException(); } }
import javax.swing.*; import java.awt.event.*; import java.awt.Dimension; import java.awt.*; import java.util.*; public class Bucket{ int amount; int x, y; public Bucket(int aX, int aY, int anAmount){ x = aX; y = aY; amount = anAmount; } public void fill(int diff){ //change the amount of water amount+= diff; } public void empty(int diff){ //change the amount of water amount-= diff; } public boolean isEmpty(){ return amount<= 0; //return false; } public void paint(Graphics g){ g.setColor(new Color(255,255,255)); g.fillRect(x, y, 100, amount); } }
package com.meizu.scriptkeeper.view.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; import com.meizu.scriptkeeper.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Author: jinghao * Date: 2014-12-31 */ public class CaseAdapter extends BaseAdapter { public static final String CASE_NAME = "name"; public static final String CASE_RESULT = "result"; private List<HashMap<String, Object>> dataSourceList; public List<Boolean> checkList = new ArrayList<Boolean>(); private Context context; static class ViewHolder{ TextView case_name; ImageView case_screenshot; ImageView case_result; CheckBox case_check_box; } public CaseAdapter(Context context, List<HashMap<String, Object>> dataSourceList, List<Boolean> checkList){ this.context = context; this.dataSourceList = dataSourceList; this.checkList = checkList; } public List<Boolean> getCheckList(){ return checkList; } public void setChecked(int position, boolean isChecked){ getCheckList().set(position, isChecked); } public boolean isChecked(int position){ return getCheckList().get(position); } @Override public int getCount() { return dataSourceList.size(); } @Override public Object getItem(int position) { return dataSourceList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final ViewHolder holder; if(convertView == null || convertView.getTag() == null){ holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.item_case_result, null); holder.case_name = (TextView) convertView.findViewById(R.id.item_case_name); holder.case_screenshot = (ImageView) convertView.findViewById(R.id.item_case_screenshot); holder.case_result = (ImageView) convertView.findViewById(R.id.item_case_result); holder.case_check_box = (CheckBox) convertView.findViewById(R.id.item_check); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.case_check_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { setChecked(position, b); } }); holder.case_check_box.setChecked(getCheckList().get(position)); return convertView; } }
package com.example.banque.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import java.util.List; import javax.persistence.DiscriminatorColumn; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; @Entity @Data @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorColumn(name="typeDeCompte") public abstract class Compte implements Serializable { @Id private String codeCompte; private BigDecimal solde; private Date dateDeCreation; @JsonIgnore @ManyToOne @JoinColumn(name="codeClient") private Client client; @OneToMany(mappedBy="compte") private List<Operation> operations; }
/* * Copyright (C) 2016 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.google.android.cameraview.demo; import android.Manifest; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.Color; import android.hardware.Camera; import android.media.CamcorderProfile; import android.media.MediaRecorder; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.annotation.StringRes; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.app.DialogFragment; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.TextureView; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.android.cameraview.AspectRatio; import com.google.android.cameraview.CameraView; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Date; import java.util.List; import java.util.Set; /** * This demo app saves the taken picture to a constant file. * $ adb pull /sdcard/Android/data/com.google.android.cameraview.demo/files/Pictures/picture.jpg */ public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback, AspectRatioFragment.Listener { private static final String TAG = "MainActivity"; private static final int REQUEST_CAMERA_PERMISSION = 1; public static final String WHICH_CAMERA = "com.example.ylmz.giris"; public static final String WHICH_FLASH = "com.example.ylmz.giris.Flash"; public static final String PICTURE_PATH = "com.example.ylmz.giris.Path"; public static final String WHICH_ASPECTRATIO = "com.example.ylmz.giris.Ratio"; public static String whichCamera="Arka kamera"; public static String whichFlash="AUTO"; public static String picturePath=""; public static String whichAspectratio=""; private static final String FRAGMENT_DIALOG = "dialog"; //video değişkenleri private Camera mCamera; private TextureView mPreview; private MediaRecorder mMediaRecorder; private File mOutputFile; private boolean isRecording = false; private static final String TAGFORVIDEO = "Recorder"; private FloatingActionButton fab; private boolean longPressed = false; private static final int[] FLASH_OPTIONS = { CameraView.FLASH_AUTO, CameraView.FLASH_OFF, CameraView.FLASH_ON, }; private static final int[] FLASH_ICONS = { R.drawable.ic_flash_auto, R.drawable.ic_flash_off, R.drawable.ic_flash_on, }; private static final int[] FLASH_TITLES = { R.string.flash_auto, R.string.flash_off, R.string.flash_on, }; private int mCurrentFlash; private CameraView mCameraView; private Handler mBackgroundHandler; final Context context = this; private View.OnClickListener mOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.take_picture: if (mCameraView != null && !longPressed) { mCameraView.takePicture(); } break; } } }; private View.OnLongClickListener mOnLongClickListener = new View.OnLongClickListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean onLongClick(View v) { v.setBackgroundTintList(ColorStateList.valueOf(Color.RED)); Toast.makeText(MainActivity.this, "asfsafgsa", Toast.LENGTH_SHORT).show(); longPressed =true; onCaptureClick(v); return false; } }; private View.OnTouchListener mOnTouchClickListener = new View.OnTouchListener() { @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override public boolean onTouch(View v, MotionEvent event) { v.onTouchEvent(event); if (event.getAction() == MotionEvent.ACTION_UP) { // We're only interested in anything if our speak button is currently pressed. //stop yapılacak if(longPressed) { v.setBackgroundTintList(ColorStateList.valueOf(Color.GREEN)); onCaptureClick(v); } } return true; } }; @SuppressLint("ResourceAsColor") @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); whichCamera="Arka kamera"; whichFlash="Flash otamatik"; whichAspectratio="4:3"; mCameraView = (CameraView) findViewById(R.id.camera); mPreview = (TextureView) findViewById(R.id.surface_view); mPreview.setVisibility(View.INVISIBLE); if (mCameraView != null) { mCameraView.addCallback(mCallback); } fab = (FloatingActionButton) findViewById(R.id.take_picture); if (fab != null) { fab.setOnClickListener(mOnClickListener); fab.setOnLongClickListener(mOnLongClickListener); fab.setOnTouchListener(mOnTouchClickListener); } Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayShowTitleEnabled(false); } } public void alertCameraButtom(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); alertDialog.setTitle("Alert Dialog ") .setMessage("Yeni pencereye gitmek ister misiniz? ") .setCancelable(false) .setIcon(R.mipmap.ic_launcher) .setPositiveButton("Evet", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { goShowActivity(); } }) .setNegativeButton("Hayır", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } public void goShowActivity(){ Intent intent = new Intent(MainActivity.this,ShowActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra(WHICH_CAMERA, whichCamera); intent.putExtra(WHICH_FLASH,whichFlash); intent.putExtra(PICTURE_PATH,picturePath); intent.putExtra(WHICH_ASPECTRATIO,whichAspectratio); startActivity(intent); finish(); } @Override protected void onResume() { super.onResume(); if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { mCameraView.start(); } else if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) { ConfirmationDialogFragment .newInstance(R.string.camera_permission_confirmation, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION, R.string.camera_permission_not_granted) .show(getSupportFragmentManager(), FRAGMENT_DIALOG); } else { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); } } @Override protected void onPause() { mCameraView.stop(); super.onPause(); // if we are using MediaRecorder, release it first releaseMediaRecorder(); // release the camera immediately on pause event releaseCamera(); } @Override protected void onDestroy() { super.onDestroy(); if (mBackgroundHandler != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { mBackgroundHandler.getLooper().quitSafely(); } else { mBackgroundHandler.getLooper().quit(); } mBackgroundHandler = null; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case REQUEST_CAMERA_PERMISSION: if (permissions.length != 1 || grantResults.length != 1) { throw new RuntimeException("Error on requesting camera permission."); } if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, R.string.camera_permission_not_granted, Toast.LENGTH_SHORT).show(); } // No need to start camera here; it is handled by onResume break; } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.aspect_ratio: FragmentManager fragmentManager = getSupportFragmentManager(); if (mCameraView != null && fragmentManager.findFragmentByTag(FRAGMENT_DIALOG) == null) { final Set<AspectRatio> ratios = mCameraView.getSupportedAspectRatios(); Log.d("mesaj",ratios.toString()); final AspectRatio currentRatio = mCameraView.getAspectRatio(); AspectRatioFragment.newInstance(ratios, currentRatio) .show(fragmentManager, FRAGMENT_DIALOG); } return true; case R.id.switch_flash: if (mCameraView != null) { mCurrentFlash = (mCurrentFlash + 1) % FLASH_OPTIONS.length; item.setTitle(FLASH_TITLES[mCurrentFlash]); item.setIcon(FLASH_ICONS[mCurrentFlash]); if(mCurrentFlash==0) whichFlash="AUTO"; else if(mCurrentFlash==1) whichFlash="Flash kapalı"; else whichFlash="Flash acık"; mCameraView.setFlash(FLASH_OPTIONS[mCurrentFlash]); } return true; case R.id.switch_camera: if (mCameraView != null) { int facing = mCameraView.getFacing(); if(facing==CameraView.FACING_FRONT){ mCameraView.setFacing(CameraView.FACING_BACK); whichCamera="Arka kamera"; }else{ mCameraView.setFacing(CameraView.FACING_FRONT); whichCamera="On kamera"; } } return true; } return super.onOptionsItemSelected(item); } @Override public void onAspectRatioSelected(@NonNull AspectRatio ratio) { if (mCameraView != null) { Toast.makeText(this, ratio.toString(), Toast.LENGTH_SHORT).show(); whichAspectratio=ratio.toString(); mCameraView.setAspectRatio(ratio); } } private Handler getBackgroundHandler() { if (mBackgroundHandler == null) { HandlerThread thread = new HandlerThread("background"); thread.start(); mBackgroundHandler = new Handler(thread.getLooper()); } return mBackgroundHandler; } private CameraView.Callback mCallback = new CameraView.Callback() { @Override public void onCameraOpened(CameraView cameraView) { Log.d(TAG, "onCameraOpened"); } @Override public void onCameraClosed(CameraView cameraView) { Log.d(TAG, "onCameraClosed"); } @Override public void onPictureTaken(CameraView cameraView, final byte[] data) { final Date now = new Date(); android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now); Log.d(TAG, "onPictureTaken " + data.length); Toast.makeText(cameraView.getContext(), R.string.picture_taken, Toast.LENGTH_SHORT) .show(); picturePath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"; /////Alert alertCameraButtom(); getBackgroundHandler().post(new Runnable() { @Override public void run() { File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg"); OutputStream os = null; try { os = new FileOutputStream(file); os.write(data); os.close(); } catch (IOException e) { Log.w(TAG, "Cannot write to " + file, e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { // Ignore } } } } }); } }; public static class ConfirmationDialogFragment extends DialogFragment { private static final String ARG_MESSAGE = "message"; private static final String ARG_PERMISSIONS = "permissions"; private static final String ARG_REQUEST_CODE = "request_code"; private static final String ARG_NOT_GRANTED_MESSAGE = "not_granted_message"; public static ConfirmationDialogFragment newInstance(@StringRes int message, String[] permissions, int requestCode, @StringRes int notGrantedMessage) { ConfirmationDialogFragment fragment = new ConfirmationDialogFragment(); Bundle args = new Bundle(); args.putInt(ARG_MESSAGE, message); args.putStringArray(ARG_PERMISSIONS, permissions); args.putInt(ARG_REQUEST_CODE, requestCode); args.putInt(ARG_NOT_GRANTED_MESSAGE, notGrantedMessage); fragment.setArguments(args); return fragment; } @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final Bundle args = getArguments(); return new AlertDialog.Builder(getActivity()) .setMessage(args.getInt(ARG_MESSAGE)) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String[] permissions = args.getStringArray(ARG_PERMISSIONS); if (permissions == null) { throw new IllegalArgumentException(); } ActivityCompat.requestPermissions(getActivity(), permissions, args.getInt(ARG_REQUEST_CODE)); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getActivity(), args.getInt(ARG_NOT_GRANTED_MESSAGE), Toast.LENGTH_SHORT).show(); } }) .create(); } } /** * The capture button controls all user interaction. When recording, the button click * stops recording, releases {@link android.media.MediaRecorder} and {@link android.hardware.Camera}. When not recording, * it prepares the {@link android.media.MediaRecorder} and starts recording. * * @param view the view generating the event. */ public void onCaptureClick(View view) { mPreview.setVisibility(View.VISIBLE); if (isRecording) { // BEGIN_INCLUDE(stop_release_media_recorder) // stop recording and release camera try { mMediaRecorder.stop(); // stop the recording } catch (RuntimeException e) { // RuntimeException is thrown when stop() is called immediately after start(). // In this case the output file is not properly constructed ans should be deleted. Log.d(TAGFORVIDEO, "RuntimeException: stop() is called immediately after start()"); //noinspection ResultOfMethodCallIgnored mOutputFile.delete(); } releaseMediaRecorder(); // release the MediaRecorder object mCamera.lock(); // take camera access back from MediaRecorder // inform the user that recording has stopped isRecording = false; releaseCamera(); // END_INCLUDE(stop_release_media_recorder) } else { // BEGIN_INCLUDE(prepare_start_media_recorder) new MediaPrepareTask().execute(null, null, null); // END_INCLUDE(prepare_start_media_recorder) } } private void releaseMediaRecorder(){ if (mMediaRecorder != null) { // clear recorder configuration mMediaRecorder.reset(); // release the recorder object mMediaRecorder.release(); mMediaRecorder = null; // Lock camera for later use i.e taking it back from MediaRecorder. // MediaRecorder doesn't need it anymore and we will release it if the activity pauses. mCamera.lock(); } } private void releaseCamera(){ if (mCamera != null){ // release the camera for other applications mCamera.release(); mCamera = null; } } @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) private boolean prepareVideoRecorder(){ // BEGIN_INCLUDE (configure_preview) mCamera = CameraHelper.getDefaultCameraInstance(); // We need to make sure that our preview and recording video size are supported by the // camera. Query camera to find all the sizes and choose the optimal size given the // dimensions of our preview surface. Camera.Parameters parameters = mCamera.getParameters(); // Orientation parameters.set("orientation", "portrait"); mCamera.setParameters(parameters); mCamera.setDisplayOrientation(90); List<Camera.Size> mSupportedPreviewSizes = parameters.getSupportedPreviewSizes(); List<Camera.Size> mSupportedVideoSizes = parameters.getSupportedVideoSizes(); Camera.Size optimalSize = CameraHelper.getOptimalVideoSize(mSupportedVideoSizes, mSupportedPreviewSizes, mCameraView.getWidth(), mCameraView.getHeight()); // Use the same size for recording profile. CamcorderProfile profile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH); profile.videoFrameWidth = optimalSize.width; profile.videoFrameHeight = optimalSize.height; // likewise for the camera object itself. parameters.setPreviewSize(profile.videoFrameWidth, profile.videoFrameHeight); mCamera.setParameters(parameters); try { // Requires API level 11+, For backward compatibility use {@link setPreviewDisplay} // with {@link SurfaceView} mCamera.setPreviewTexture(mPreview.getSurfaceTexture()); } catch (IOException e) { Log.e(TAGFORVIDEO, "Surface texture is unavailable or unsuitable" + e.getMessage()); return false; } // END_INCLUDE (configure_preview) // BEGIN_INCLUDE (configure_media_recorder) mMediaRecorder = new MediaRecorder(); // Step 1: Unlock and set camera to MediaRecorder mCamera.unlock(); mMediaRecorder.setCamera(mCamera); // Step 2: Set sources mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT ); mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA); // Step 3: Set a CamcorderProfile (requires API Level 8 or higher) mMediaRecorder.setProfile(profile); // Step 4: Set output file mOutputFile = CameraHelper.getOutputMediaFile(CameraHelper.MEDIA_TYPE_VIDEO); if (mOutputFile == null) { return false; } mMediaRecorder.setOutputFile(mOutputFile.getPath()); // END_INCLUDE (configure_media_recorder) // Step 5: Prepare configured MediaRecorder try { mMediaRecorder.prepare(); } catch (IllegalStateException e) { Log.d(TAGFORVIDEO, "IllegalStateException preparing MediaRecorder: " + e.getMessage()); releaseMediaRecorder(); return false; } catch (IOException e) { Log.d(TAGFORVIDEO, "IOException preparing MediaRecorder: " + e.getMessage()); releaseMediaRecorder(); return false; } return true; } /** * Asynchronous task for preparing the {@link android.media.MediaRecorder} since it's a long blocking * operation. */ class MediaPrepareTask extends AsyncTask<Void, Void, Boolean> { @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB) @Override protected Boolean doInBackground(Void... voids) { // initialize video camera if (prepareVideoRecorder()) { // Camera is available and unlocked, MediaRecorder is prepared, // now you can start recording mMediaRecorder.start(); isRecording = true; } else { // prepare didn't work, release the camera releaseMediaRecorder(); return false; } return true; } @Override protected void onPostExecute(Boolean result) { if (!result) { MainActivity.this.finish(); } // inform the user that recording has started } } }
package GUI; /*Doing the needed imports*/ import java.awt.Container; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Button; public class ScreenButton extends ScreenElement implements InputDevice { Button button; boolean inputAvailable = false; //boolean to register da input public ScreenButton(String naam, Point locatie) { super(naam, locatie); button = new Button(naam); // create a new button with a new label button.setBounds(pos.x, pos.y, 15 + 15 * naam.length(), 30); // define the length, width and position of the buttons /* Create a new actionlistener and evenhandler for the buttons */ button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { inputAvailable = true; //button is pressed } }); } @Override void setContainer(Container container) { // TODO Auto-generated method stub container.add(button); } /* Return the label of the button if the button is pressed else return null*/ @Override public String getInput() { if (inputAvailable) { inputAvailable = false; //System.out.println(button.getLabel()); return button.getLabel(); } else { return null; } } }
package reflect; /** * 简述: * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2019/12/23 12:08 */ public class User { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User{" + "name='" + name + '\'' + '}'; } }
/* * 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 pt.uminho.sdc.railmanager; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class RailManagerImpl implements RailManager, Serializable { public Map<String, Rail> rails; List<String> alarms; public RailManagerImpl() { this.rails = new HashMap<>(); this.alarms = new ArrayList<>(); } @Override public boolean access(String line, int segment, char composition) { if (this.rails.containsKey(line)) { Rail rail = this.rails.get(line); return rail.isAccessible(composition, segment); } return false; } @Override public boolean enter(String line, int segment, char composition) { boolean res = true; if (!this.access(line, segment, composition)) { this.alarms.add("L" + line + "S" + segment + "C" + composition); res = false; } if (this.rails.containsKey(line)) { Rail rail = this.rails.get(line); rail.addPresence(composition, segment); } return res; } @Override public void leave(String line, int segment, char composition) { if (!this.rails.containsKey(line)) { return; } Rail rail = this.rails.get(line); rail.removePresence(composition, segment); } @Override public Map<Integer, char[]> getPositions(String line) { Rail rail = this.rails.get(line); return rail.getPositions(); } @Override public List<String> getAlarms() { List<String> res = new ArrayList<>(); for (String alarm : this.alarms) { res.add(alarm); } return res; } @Override public Map<String, Integer> getRails() { Map<String, Integer> res = new HashMap<>(); for(String railName : this.rails.keySet()) { res.put(railName, this.rails.get(railName).getNumberSegments()); } return res; } public void addRail(String name, Rail rail) { this.rails.put(name, rail); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Rails [").append(this.rails.size()).append("]\n"); for(String railName : this.rails.keySet()) { Rail r = this.rails.get(railName); sb.append(railName).append("\t"); sb.append(r.toString()).append('\n'); } sb.append("Alamrs [").append(this.alarms.size()).append("]\n"); for(String alarm : this.alarms) { sb.append(alarm).append('\n'); } return sb.toString(); } }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; /** * Routines for converting time values to and from YYYYMMDDHHMMSS format. * * @author Brian Wellington */ final class FormattedTime { private static final DateTimeFormatter DEFAULT_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.UTC); private FormattedTime() {} /** * Converts a Date into a formatted string. * * @param date The Instant to convert. * @return The formatted string. */ public static String format(Instant date) { return DEFAULT_FORMAT.format(date); } /** * Parses a formatted time string into an Instant. * * @param s The string, in the form YYYYMMDDHHMMSS or seconds since epoch (1 January 1970 00:00:00 * UTC). * @return The Instant object. * @throws DateTimeParseException The string was invalid. */ public static Instant parse(String s) throws DateTimeParseException { // rfc4034#section-3.2 if (s.length() == 14) { return DEFAULT_FORMAT.parse(s, Instant::from); } else if (s.length() <= 10) { return Instant.ofEpochSecond(Long.parseLong(s)); } throw new DateTimeParseException("Invalid time encoding: ", s, 0); } }
package com.wdl.entity.rbac; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import com.wdl.base.entity.BaseEntity; @Entity @Table(name = "t_org") public class Org extends BaseEntity { private static final long serialVersionUID = -892723165144628561L; @Column(name = "name", length = 200) private String name; @Column(name = "code", length = 20) private String code; @Column(name = "parentId", length = 20) private Long parentId; @Column(name = "levelCode", length = 36) private String levelCode; @Column(name = "remark", length = 300) private String remark; @Column(name = "deleted", length = 5) private Integer deleted; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getLevelCode() { return levelCode; } public void setLevelCode(String levelCode) { this.levelCode = levelCode; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public Integer getDeleted() { return deleted; } public void setDeleted(Integer deleted) { this.deleted = deleted; } }
package in.vamsoft.excersise2; public class MappingTest { public static void main(String[] args) { Mapping mapper = new Mapping(); System.out.println("English names"); printNumbers(mapper, 22); String[] spanishNums = {"cero", "uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "ocho", "nueve", "diez", "once", "doce", "trece", "catorce"}; mapper = new Mapping(spanishNums); System.out.println("Spanish names"); printNumbers(mapper, 17); } private static void printNumbers(Mapping mapper, int n) { for(int i=0; i<n; i++) { System.out.printf("The value of %s is %s.%n", i, mapper.wordForNumber(i)); } } }
package burst.test.tags; import com.tngtech.jgiven.annotation.TagDescriptionGenerator; import com.tngtech.jgiven.config.TagConfiguration; import java.lang.annotation.Annotation; public class NarrativeDescriptionGenerator implements TagDescriptionGenerator { @Override public String generateDescription(TagConfiguration tagConfiguration, Annotation annotation, Object value) { return String.format("Narrative : %s", value, value); } }
package com.rationaleemotions.pojo; import com.rationaleemotions.utils.Preconditions; import com.rationaleemotions.utils.Strings; import java.io.File; /** * Represents the attributes of a user for whom a remote ssh is being attempted. */ public class SSHUser { private static final String USER_NAME = "user.name"; private static final String USER_HOME = "user.home"; private static final String SSH = ".ssh"; private String userName; private String password; private File sshFolder; private File privateKey; private String passphrase; private boolean useAgentIdentities = false; private SSHUser() { //We have a builder to construct this object. So hide the constructor. } /** * @return - a {@link File} object that represents the actual location of the <b>.ssh</b> folder. * Typically this is in the HOME directory <b>"~"</b> */ public File sshFolderLocation() { return sshFolder; } /** * @return - A {@link File} object that represents a user's private key location. The private key [id_rsa (or) * id_dsa ] is typically located under <b>~/.ssh</b> folder. */ public File privateKeyLocation() { return privateKey; } /** * @return - The user for which ssh would be attempted. */ public String getUserName() { return userName; } /** * @return - The password for the current user. */ public String getPassword() { return password; } /** * @return - The location to where the <b>known_hosts</b> file exists. * This location is typically <b>~/.ssh/known_hosts</b> file. Here <b>~/.ssh</b> will be different based * on what was provided to instantiate a {@link SSHUser} object. */ public String knownHostsFileLocation() { return sshFolder.getAbsolutePath() + File.separator + "known_hosts"; } public String getPassphrase() { return passphrase; } /** * @return - Whether to use identities available via ssh-agent or pageant.exe */ public boolean isUseAgentIdentities() { return useAgentIdentities; } /** * Creates a {@link SSHUser} object for the currently logged in user. * Here are the assumptions that is made here : * <ol> * <li>User name - The currently logged-in user as identified via the Java property <b>user.name</b></li> * <li>User's home directory - The home directory of the currently logged-in user as identified via the * Java property <b>user.home</b></li> * </ol> */ public static class Builder { private SSHUser user; public Builder() { user = new SSHUser(); } /** * Creates a {@link SSHUser} object for a user that is different from the currently logged in user. * Here are the assumptions that is made here : * <ol> * <li>User's home directory - The home directory is calculated relatively to the home directory of the * currently * logged in user. For e.g., if the current logged in user's home directory is <b>/home/ram</b> and if the * user for whom ssh is being attempted at <b>krishna</b> then the home directory is calculated as * <b>/home/krishna</b></li> * </ol> * * @param user - The user for whom ssh is being attempted. */ public Builder forUser(String user) { this.user.userName = user; return this; } /** * @param password - The password to be used for ssh. */ public Builder withPasswordAs(String password) { this.user.password = password; return this; } /** * @param sshFolder - The location of the <b>.ssh</b> folder. */ public Builder withSshFolder(File sshFolder) { this.user.sshFolder = sshFolder; return this; } /** * @param privateKey - The location of the private key (either <b>id_rsa</b> (or) <b>id_dsa</b> ) */ public Builder usingPrivateKey(File privateKey) { this.user.privateKey = privateKey; return this; } /** * @param passphrase - A passphrase if applicable that is to be used to access the private keys. */ public Builder usingPassphrase(String passphrase) { this.user.passphrase = passphrase; return this; } /** * @param useAgentIdentities - <b>true</b> or <b>false</b>. Enable/Disable the ability to use * credentials available via ssh-agent or pageant.exe. Disabled by default. * @return */ public Builder usingAgentIdentities(boolean useAgentIdentities) { this.user.useAgentIdentities = useAgentIdentities; return this; } public SSHUser build() { if (user.userName == null || user.userName.trim().isEmpty()) { user.userName = System.getProperty(USER_NAME); } if (user.sshFolder == null) { user.sshFolder = locateSshFolderFolder(user.userName); } if (Strings.isNullOrEmpty(user.password) && user.privateKey == null) { user.privateKey = constructLocationFrom(user.sshFolder); } if (Strings.isNullOrEmpty(user.password) && user.privateKey == null) { throw new IllegalStateException("Please provide either the password or the private key for authentication"); } return this.user; } private static File locateSshFolderFolder(String userName) { String currentuser = System.getProperty(USER_NAME); if (currentuser.equalsIgnoreCase(userName)) { return new File(System.getProperty(USER_HOME) + File.separator + SSH); } File file = new File(System.getProperty(USER_HOME)); String raw = file.getParentFile().getAbsolutePath() + File.separator + userName + File.separator + SSH; return new File(raw); } private static File constructLocationFrom(File home) { Preconditions.checkArgument(home != null, "Home directory cannot be null."); Preconditions .checkArgument(home.exists(), String.format("Home directory [%s] does not exist.", home.getAbsolutePath())); Preconditions.checkArgument(home.isDirectory(), String.format("Home directory [%s] is not a directory", home.getAbsolutePath())); File file = new File(home, "id_dsa"); if (file.exists()) { return file; } file = new File(home, "id_rsa"); if (file.exists()) { return file; } throw new IllegalStateException( "No private keys [id_dsa/id_rsa] found in [" + home.getAbsolutePath() + "]"); } } }
package com.example.logsys.service; import com.example.logsys.entity.BusClick; import java.util.List; public interface ExcelService { List<BusClick> getBusClick(); }
package shulei.july26; import java.awt.Container; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import shulei.UI.util.Console; public class Applet extends JApplet { private JButton b1 = new JButton("²éѯ"); private JLabel label = new JLabel("ÈÕÆÚ(1990-1-3)£º"); private JTextField textField = new JTextField(10); private JTextArea textArea = new JTextArea(20, 40); @Override public void init() { // super.init(); Container container = this.getContentPane(); container.setLayout(new FlowLayout()); container.add(label); container.add(textField); container.add(b1); container.add(new JScrollPane(textArea)); b1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if (DateUtil.MatchYMD(textField)) { // String lundarString= ChineseCalendar // .sCalendarSolarToLundar(DateUtil.getYMD(textField // .getText())); int[] inttemp = DateUtil.getYMD(textField.getText()); SolarDate solarDate = new SolarDate(inttemp[0], inttemp[1], inttemp[2]); textArea.append(solarDate.toLunarDate().toString() + " " + solarDate.toWeek().toString()); textArea.append("\n"); } } }); } /** * @param args */ public static void main(String[] args) { Console.run(new Applet(), 500, 500); } }
/* * Copyright 2002-2023 the original author or 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 * * https://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.messaging.rsocket.service; import java.util.HashSet; import java.util.Set; import org.springframework.aop.framework.AopProxyUtils; import org.springframework.aot.generate.GenerationContext; import org.springframework.aot.hint.ProxyHints; import org.springframework.beans.factory.aot.BeanRegistrationAotContribution; import org.springframework.beans.factory.aot.BeanRegistrationAotProcessor; import org.springframework.beans.factory.aot.BeanRegistrationCode; import org.springframework.beans.factory.support.RegisteredBean; import org.springframework.core.annotation.MergedAnnotations; import org.springframework.core.annotation.MergedAnnotations.Search; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import org.springframework.util.ReflectionUtils; import static org.springframework.core.annotation.MergedAnnotations.SearchStrategy.TYPE_HIERARCHY; /** * An AOT {@link BeanRegistrationAotProcessor} that detects the presence of * {@link RSocketExchange @RSocketExchange} on methods and creates the required * proxy hints. * * @author Sebastien Deleuze * @author Olga Maciaszek-Sharma * @since 6.0.5 * @see org.springframework.web.service.annotation.HttpExchangeBeanRegistrationAotProcessor */ class RSocketExchangeBeanRegistrationAotProcessor implements BeanRegistrationAotProcessor { @Nullable @Override public BeanRegistrationAotContribution processAheadOfTime(RegisteredBean registeredBean) { Class<?> beanClass = registeredBean.getBeanClass(); Set<Class<?>> exchangeInterfaces = new HashSet<>(); Search search = MergedAnnotations.search(TYPE_HIERARCHY); for (Class<?> interfaceClass : ClassUtils.getAllInterfacesForClass(beanClass)) { ReflectionUtils.doWithMethods(interfaceClass, method -> { if (!exchangeInterfaces.contains(interfaceClass) && search.from(method).isPresent(RSocketExchange.class)) { exchangeInterfaces.add(interfaceClass); } }); } if (!exchangeInterfaces.isEmpty()) { return new RSocketExchangeBeanRegistrationContribution(exchangeInterfaces); } return null; } private static class RSocketExchangeBeanRegistrationContribution implements BeanRegistrationAotContribution { private final Set<Class<?>> rSocketExchangeInterfaces; public RSocketExchangeBeanRegistrationContribution(Set<Class<?>> rSocketExchangeInterfaces) { this.rSocketExchangeInterfaces = rSocketExchangeInterfaces; } @Override public void applyTo(GenerationContext generationContext, BeanRegistrationCode beanRegistrationCode) { ProxyHints proxyHints = generationContext.getRuntimeHints().proxies(); for (Class<?> rSocketExchangeInterface : this.rSocketExchangeInterfaces) { proxyHints.registerJdkProxy(AopProxyUtils.completeJdkProxyInterfaces(rSocketExchangeInterface)); } } } }
package ur.ur_item_ctr; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.ambit.city_guide.R; import lib.hyxen.ui.SimpleViewController; import ur.ur_flow.coupon.obj.CateObj; /** * Created by redjack on 15/9/24. */ public class CouponCateItemCtrl extends SimpleViewController<CateObj> { TextView titleText; ImageView checkImage; public CouponCateItemCtrl(Context mContext) { super(mContext); } @Override public View onCreateView(Context context) { View mainView = LayoutInflater.from(context).inflate(R.layout.ur_i_coupon_cate, null); titleText = (TextView) mainView.findViewById(R.id.ur_i_coupon_cate_text_title); checkImage = (ImageView) mainView.findViewById(R.id.ur_i_coupon_cate_img_check); return mainView; } @Override public void onInitial(CateObj data) { titleText.setText(data.getTitle()); checkImage.setVisibility(data.isChecked ? View.VISIBLE : View.INVISIBLE); } }
package com.github.reubuisnessgame.gamebank.stockexchangeservice.dao; import com.github.reubuisnessgame.gamebank.stockexchangeservice.model.ChangingPriceModel; import com.github.reubuisnessgame.gamebank.stockexchangeservice.model.CompanyModel; import com.github.reubuisnessgame.gamebank.stockexchangeservice.model.ShareModel; import com.github.reubuisnessgame.gamebank.stockexchangeservice.model.TeamModel; import com.github.reubuisnessgame.gamebank.stockexchangeservice.repository.ChangingPriceRepository; import com.github.reubuisnessgame.gamebank.stockexchangeservice.repository.CompanyRepository; import com.github.reubuisnessgame.gamebank.stockexchangeservice.repository.ShareRepository; import javassist.NotFoundException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; @Component public class StockExchangeDAO { private final ShareRepository shareRepository; private final CompanyRepository companyRepository; private final ChangingPriceRepository changingPriceRepository; private final RepositoryComponent repositoryComponent; private static final int STOCK_PRICE_CHANGE = 300_000; //5 minutes private static final int CHANGING_DELAY = 120_000; //2 minutes private static final String formatDate = "HH:mm:ss"; static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatDate); private Random random = new Random(); private final Logger LOGGER = LoggerFactory.getLogger(StockExchangeDAO.class.getSimpleName()); private boolean isGameStarted; public StockExchangeDAO(ShareRepository shareRepository, CompanyRepository companyRepository, ChangingPriceRepository changingPriceRepository, RepositoryComponent repositoryComponent) { this.shareRepository = shareRepository; this.companyRepository = companyRepository; this.changingPriceRepository = changingPriceRepository; /*ChangingRandomPriceThread priceThread = new ChangingRandomPriceThread(); priceThread.start();*/ this.repositoryComponent = repositoryComponent; } public CompanyModel createCompany(String companyName, Double sharePrice, long fullCount) { if (sharePrice <= 0 || fullCount <= 0) { throw new IllegalArgumentException("Illegal data in creating company"); } return companyRepository.findByCompanyName(companyName).orElse(companyRepository.save( new CompanyModel(sharePrice, companyName, fullCount))); } public CompanyModel changeSharesCount(String companyName, long count) throws IllegalAccessException { if (isGameStarted) { CompanyModel companyModel = companyRepository.findByCompanyName(companyName).orElseThrow(() -> new UsernameNotFoundException("Company with name " + companyName + " not found")); long freeCount = companyModel.getFreeCount(); long fullCount = companyModel.getFullCount(); if (count < 0 && -count > freeCount) { count = -freeCount; } companyModel.setFullCount(fullCount + count); return calculateNewSharePrice(count, companyModel); } throw new IllegalAccessException("The game has not started yet"); } public void changeSharePrice(long companyId, double changingPrice) throws IllegalAccessException { LOGGER.info("Is game started " + isGameStarted); if (isGameStarted) { CompanyModel model = companyRepository.findById(companyId).orElseThrow(() -> new UsernameNotFoundException("Company with ID " + companyId + " not found")); if (-changingPrice > model.getSharePrice()) { throw new IllegalArgumentException("Changing price can not be less then price"); } LOGGER.info("Start changing price"); Thread t = new Thread(new ChangingWorkerRunnable(model, changingPrice)); t.start(); return; } throw new IllegalAccessException("The game has not started yet"); } public Iterable<ShareModel> buyShares(long number, int count, String companyName) throws IllegalAccessException { LOGGER.info("Buying shares"); if (isGameStarted) { LOGGER.info("Game ok"); TeamModel teamModel = repositoryComponent.getTeamByNumber(number); CompanyModel companyModel = companyRepository.findByCompanyName(companyName).orElseThrow(() -> new UsernameNotFoundException("Company with name " + companyName + " not found")); double fullPrice = count * companyModel.getSharePrice(); if (fullPrice > teamModel.getScore()) { LOGGER.info("Recalculate count"); count = (int) (teamModel.getScore() / companyModel.getSharePrice()); fullPrice = count * companyModel.getSharePrice(); } LOGGER.info("Full price: " + fullPrice + ", team: " + teamModel.getUsername() + ", score: " + teamModel.getScore()); if (count < 0) { count = 0; LOGGER.info("Incorrect count in buying"); } calculateNewSharePrice(-count, companyModel); teamModel.setScore(teamModel.getScore() - fullPrice); repositoryComponent.saveTeam(teamModel); shareRepository.save(new ShareModel(teamModel.getId(), companyModel.getId(), count, companyModel)); return shareRepository.findAllByUserId(teamModel.getId()); } throw new IllegalAccessException("The game has not started yet"); } private CompanyModel calculateNewSharePrice(long count, CompanyModel companyModel) { double lastPrice; lastPrice = recalculateNewPrice(companyModel, count); LOGGER.info("Second calculate Step: " + lastPrice); lastPrice = Math.round(lastPrice * 100000.0) / 100000.0; companyModel.setFreeCount(companyModel.getFreeCount() + count); companyModel.setSharePrice(lastPrice); changingPriceRepository.save(new ChangingPriceModel(companyModel.getId(), lastPrice, simpleDateFormat.format(new Date()))); return companyRepository.save(companyModel); } public Iterable<ShareModel> sellShares(long number, int count, String companyName) throws IllegalAccessException { if (isGameStarted) { TeamModel teamModel = repositoryComponent.getTeamByNumber(number); CompanyModel companyModel = companyRepository.findByCompanyName(companyName).orElseThrow(() -> new UsernameNotFoundException("Company with name " + companyName + " not found")); ShareModel shareModel = shareRepository.findByCompanyIdAndUserId(companyModel.getId(), teamModel.getId()).orElseThrow(() -> new IllegalArgumentException("Not found shares")); if (count >= shareModel.getSharesNumbers()) { count = shareModel.getSharesNumbers(); shareRepository.deleteByCompanyIdAndUserId(companyModel.getId(), teamModel.getId()); } else { shareModel.setSharesNumbers(shareModel.getSharesNumbers() - count); shareRepository.save(shareModel); } calculateNewSharePrice(count, companyModel); return shareRepository.findAllByUserId(teamModel.getId()); } throw new IllegalAccessException("The game has not started yet"); } public Iterable<CompanyModel> getAllCompanies() throws NotFoundException { Iterable<CompanyModel> companyModels = companyRepository.findAll(); if (!companyModels.iterator().hasNext()) { throw new NotFoundException("Companies not found"); } return companyModels; } public Iterable<ShareModel> getAllShares() throws NotFoundException { Iterable<ShareModel> shareModels = shareRepository.findAll(); if (!shareModels.iterator().hasNext()) { throw new NotFoundException("Companies not found"); } return shareModels; } public void deleteCompany(String companyName) { CompanyModel companyModel = companyRepository.findByCompanyName(companyName).orElseThrow(() -> new UsernameNotFoundException("Company with name " + companyName + " not found")); Long id = companyModel.getId(); changingPriceRepository.deleteAllByCompanyId(id); companyRepository.deleteById(id); shareRepository.deleteAllByCompanyId(id); } public Iterable<ChangingPriceModel> getChangingPrise(String companyName) throws NotFoundException { CompanyModel companyModel = companyRepository.findByCompanyName(companyName).orElseThrow(() -> new UsernameNotFoundException("Company with name " + companyName + " not found")); return getChangingPrice(companyModel.getId()); } private Iterable<ChangingPriceModel> getChangingPrice(long companyId) throws NotFoundException { Iterable<ChangingPriceModel> changingPriceModels = changingPriceRepository.findAllByCompanyId(companyId); if (!changingPriceModels.iterator().hasNext()) { throw new NotFoundException("Changing price not found"); } return changingPriceModels; } public void clearAll() { LOGGER.info("Cleaning repository"); shareRepository.deleteAll(); companyRepository.deleteAll(); } public void stopStartGame(boolean gameStarted) { LOGGER.info("Is game started " + isGameStarted); isGameStarted = gameStarted; } /* private synchronized double recalculateNewPrice(CompanyModel model, long count){ double stablePrice = model.getStablePrice(); return stablePrice * (2 - ((double)model.getFreeCount()- count)/model.getFullCount()); }*/ private double recalculateNewPrice(CompanyModel model, long count){ return model.getStablePrice(); } private double recalculateNewPrice(CompanyModel model){ return recalculateNewPrice(model, 0); } /* private class ChangingRandomPriceThread extends Thread { public void run() { try { //noinspection InfiniteLoopStatement while (true) { Thread.sleep(STOCK_PRICE_CHANGE); if (isGameStarted) { LOGGER.info("Random changing price"); Iterable<CompanyModel> companyModels = companyRepository.findAll(); List<CompanyModel> companyModelList = new ArrayList<>(); List<ChangingPriceModel> changingPriceModels = new ArrayList<>(); companyModels.forEach((company) -> { double lastPrice = company.getStablePrice(); boolean sign = random.nextBoolean(); if (sign) { lastPrice *= ((double) (random.nextInt(10) + 89) / 100); } else { lastPrice *= ((double) (random.nextInt(10) + 101) / 100); } LOGGER.info("Last price in company " + company.getCompanyName() + " : " + lastPrice); lastPrice = Math.round(lastPrice * 100000.0) / 100000.0; if (lastPrice < 0) { lastPrice = -lastPrice; } String date = simpleDateFormat.format(new Date()); company.setStablePrice(lastPrice); lastPrice = recalculateNewPrice(company); changingPriceModels.add(new ChangingPriceModel(company.getId(), lastPrice, date)); company.setSharePrice(lastPrice); companyModelList.add(company); }); changingPriceRepository.saveAll(changingPriceModels); companyRepository.saveAll(companyModelList); } } } catch (InterruptedException e) { LOGGER.warn(e.getMessage(), e); } } }*/ private class ChangingWorkerRunnable implements Runnable { private final CompanyModel model; private final double changingPrice; ChangingWorkerRunnable(CompanyModel model, double changingPrice) { this.model = model; this.changingPrice = changingPrice; } @Override public void run() { try { Thread.sleep(CHANGING_DELAY); LOGGER.info("Changing price of company " + model.getCompanyName()); double tmpSharePrice = model.getStablePrice() + changingPrice; tmpSharePrice = Math.round(tmpSharePrice * 100000.0) / 100000.0; model.setStablePrice(tmpSharePrice); double newFullPrice = recalculateNewPrice(model); model.setSharePrice(newFullPrice); changingPriceRepository.save(new ChangingPriceModel(model.getId(), newFullPrice, simpleDateFormat.format(new Date()))); companyRepository.save(model); } catch (InterruptedException e) { LOGGER.warn(e.getMessage(), e); } } } }
package reflect; /** * 简述: * * @author WangLipeng 1243027794@qq.com * @version 1.0 * @since 2019/12/24 9:00 */ public class TT { }
/* Level Order Traversal of a Binary Tree */ public class Solution { public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> ll = new ArrayList<>(); Queue<TreeNode> q = new LinkedList(); if(root==null) return ll; q.add(root); while(!q.isEmpty()) { int level = q.size(); List<Integer> l = new LinkedList<>(); /* Add all children of one level to 'l' */ for(int i=0; i<level; i++) { if(q.peek().left != null) q.add(q.peek().left); if(q.peek().right != null) q.add(q.peek().right); l.add(q.poll().val); } ll.add(l); } return ll; } }
package stringhandling; public class AlphabeticalOrder { public static void main(String args[]) { String name[]={"Prashant","Mayur","Tejas","Ali","Nandani","Prajakta","Ashlesha"}; for(int i=0;i<name.length;i++) { for(int j=i+1;j<name.length;j++) { if(name[i].compareToIgnoreCase(name[j])>0) { String temp=name[i]; name[i]=name[j]; name[j]=temp; } } } for(int i=0;i<name.length;i++) { System.out.println(name[i]); } } }
package com.example.demo.service; import com.example.demo.entity.PageInfo; import com.example.demo.entity.ProjectApprovalProject; import com.baomidou.mybatisplus.extension.service.IService; import com.example.demo.entity.PubProjectVO; import com.example.demo.entity.PublishSearchParams; import java.util.List; /** * <p> * 服务类 * </p> * * @author zjp * @since 2020-11-30 */ public interface IProjectApprovalProjectService extends IService<ProjectApprovalProject> { /** * 分页查询 已出版的文件 和 立项的项目 * * @param params pageSize && pageNumber && user * @return PubProjectVO */ PageInfo<PubProjectVO> getApprovalProjectList(PublishSearchParams params); /** * 获取项目组立项项目 * * @param params 部门id 项目组id 年份 * @return list */ PageInfo<ProjectApprovalProject> getApprovalList(PublishSearchParams params); /** * 获取部门所有的立项 * * @param deptId 部门id * @return list */ List<ProjectApprovalProject> getAllApprovalList(String deptId); }
package com.yhkx.core.storage.dao.mapper; import com.yhkx.core.storage.dao.entity.SkillInfo; import tk.mybatis.mapper.common.Mapper; /** * <p> * </p> * * @author uniqu * @date 2018-10-09 11:01:51 * @version */ public interface SkillInfoMapper extends Mapper<SkillInfo> { }
package com.evature.evasdk.evaapis.crossplatform.flow; import com.evature.evasdk.evaapis.crossplatform.EvaLocation; import com.evature.evasdk.util.DLog; import java.io.Serializable; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public class ReplyElement extends FlowElement implements Serializable { private static final String TAG = "ReplyElement"; public String attributeType; public Object attributeValue; public enum ReplyAttribute { Unknown, CallSupport, ReservationID, Cancellation, Baggage, MultiSegment }; public ReplyAttribute attributeKey; public ReplyElement(JSONObject jFlowElement, List<String> parseErrors, EvaLocation[] locations, JSONObject jApiReply) { super(jFlowElement, parseErrors, locations); try { String jAttributeKey = jFlowElement.getString("AttributeKey"); attributeType = jFlowElement.getString("AttributeType"); if (jApiReply.has(attributeType)) { attributeValue = jApiReply.getJSONObject(attributeType).opt(jAttributeKey); } try { attributeKey = ReplyAttribute.valueOf(jAttributeKey.replace(" ","").replace("-","")); } catch(IllegalArgumentException e) { DLog.w(TAG, "Unexpected ReplyAttribute in Flow element", e); attributeKey = ReplyAttribute.Unknown; } } catch(JSONException e) { parseErrors.add("Exception during parsing Reply element: "+e.getMessage()); } } }
package com.test; import java.util.ArrayList; import java.util.List; /** * Given an array of words and a width maxWidth, * format the text such that each line has exactly maxWidth characters * and is fully (left and right) justified. * * 给一串字符串,以及一个最大宽度;格式化text,使得每一行的宽度都是最大宽度; * * You should pack your words in a greedy approach; * that is, pack as many words as you can in each line. * Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters. * 你需要包装你的单次,使用' '填充 * * Extra spaces between words should be distributed as evenly as possible. * If the number of spaces on a line do not divide evenly between words, * the empty slots on the left will be assigned more spaces than the slots on the right. * 如果空格不能均分,则左侧比右侧多一个空格 * * For the last line of text, it should be left justified and * no extra space is inserted between words. * 对于最后一行,需要左对齐 * * Note: 注意事项 * A word is defined as a character sequence consisting of non-space characters only. * 字符必须由非空字符串组成 * * Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. * 每个单次的长度,0 < 大小 <= maxWidth * * The input array words contains at least one word. * 输入的单词,数量大于1 * * @author YLine * * 2019年6月16日 上午11:25:54 */ public class SolutionA { public List<String> fullJustify(String[] words, int maxWidth) { List<String> result = new ArrayList<>(); dfs(result, words, maxWidth, 0); return result; } private void dfs(List<String> result, String[] words, int maxWidth, int index) { int wordWidth = words[index].length(); int spaceWidth = 1; int nextIndex = index + 1; while (nextIndex < words.length) { if (wordWidth + spaceWidth + words[nextIndex].length() > maxWidth) { alignSide(result, words, maxWidth, wordWidth, index, nextIndex); dfs(result, words, maxWidth, nextIndex); return; } else { wordWidth += words[nextIndex].length(); spaceWidth++; nextIndex++; } } alignLeft(result, words, maxWidth, index, words.length); } /** * 左右两边对齐 */ private void alignSide(List<String> result, String[] words, int maxWidth, int wordWidth, int index, int nextIndex) { if (nextIndex - index == 1) { // 长度为1,则直接左对齐实现 alignLeft(result, words, maxWidth, index, nextIndex); } else { // 长度大于1,左右对齐需要计算空格[没有末尾] char[] lineArray = new char[maxWidth]; int spaceWidth = maxWidth - wordWidth; int eachSpace = spaceWidth / (nextIndex - index - 1); // 每个空格,个数 int restSpace = spaceWidth % (nextIndex - index - 1); // 多余的空格 // 字符填入 int count = 0; for (int i = index; i < nextIndex; i++) { words[i].getChars(0, words[i].length(), lineArray, count); count += words[i].length(); // 间隔 if (i != nextIndex - 1) // 不是最后一个 { // 每个空格 for (int j = 0; j < eachSpace; j++) { lineArray[count + j] = ' '; } count += eachSpace; // 未能均分的空格 if (restSpace > 0) { lineArray[count] = ' '; count += 1; restSpace--; } } } result.add(new String(lineArray)); } } /** * 左边对齐 */ private void alignLeft(List<String> result, String[] words, int maxWidth, int index, int nextIndex) { char[] lineArray = new char[maxWidth]; // 字符填入 int width = 0; for (int i = index; i < nextIndex; i++) { words[i].getChars(0, words[i].length(), lineArray, width); width += words[i].length(); // 间隔 if (i != nextIndex - 1) { lineArray[width] = ' '; width += 1; } } // 末尾空格填充 for (; width < lineArray.length; width++) { lineArray[width] = ' '; } result.add(new String(lineArray)); } }
package org.giddap.dreamfactory.mitbbs.amazon; import org.giddap.dreamfactory.leetcode.commons.TreeNode; import java.util.HashMap; import java.util.Map; /** * There is a binary tree that each node has a value of single digit 0-9. * <p/> * Find a node-to-node path from the tree that generates the largest integer. * <p/> * <pre> * Example #1 * 1 * / \ * 2 5 * / \ * 4 3 * output: 5123 (order matters) * --- * Example #2 * 1 * / * 2 * / \ * 4 3 * / * 6 * output: 6423 (not 6421!) * </pre> */ public class MaxIntegerFromWeightedBinaryTree { private int maxNumber = Integer.MIN_VALUE; // left bottom up // left top down // right bottom up // right top down private Map<TreeNode, String[]> nodePossibleValues = null; public int solve(TreeNode node) { nodePossibleValues = new HashMap<TreeNode, String[]>(); return 0; } public String[] solveRecursively(TreeNode node) { if (node == null) { return new String[4]; } String[] lefts = solveRecursively(node.left); String[] rights = solveRecursively(node.right); int numFromLeftToRight = Integer.parseInt(lefts[0] + node.val + rights[3]); int numFromRightToLeft = Integer.parseInt(rights[2] + node.val + lefts[1]); maxNumber = Math.max(maxNumber, Math.max(numFromLeftToRight, numFromRightToLeft)); String[] ret = new String[4]; ret[0] = lefts[0] + node.val; ret[1] = lefts[1] + node.val; ret[0] = lefts[0] + node.val; ret[0] = lefts[0] + node.val; return ret; } }
package global.dao; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import global.model.Teachingtask; import global.model.View_teacher; import global.model.View_teachingtask; /** * 教学任务数据访问类 * * @author czy * */ public class Teachingtaskaccess { /** * 将教学任务信息插入数据库中 * * @author czy * @param con * :数据库的连接 * @param tt * :待插入的教学任务信息 * @return:如果插入成功,返回教学任务id,否则返回-1或-2。 * @throws ClassNotFoundException * @throws SQLException */ public static int insert(Connection con, Teachingtask tt) throws ClassNotFoundException, SQLException { // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; String sql; // 生成数据库声明对象 Statement st = con.createStatement(); // 生成查找下一个教学任务id的sql语句 sql = "SELECT max(tt_id)+1 as next_id FROM courseschedule.teachingtask"; // 执行sql语句,返回记录集 ResultSet rs = st.executeQuery(sql); // 定义教学任务id,并初始化为1 int tt_id = 1; // 如果结果集有数据,则取出下一个教学任务id if (rs.next()) tt_id = rs.getInt("next_id"); // 生成sql语句用于插入教学任务信息 sql = "INSERT INTO teachingtask (tt_id, cou_id,cou_theoryhour,cou_experimentalhours,cou_practicehour, t_id, sy_id, multimedia,m_id,tt_grade,Practicescheduling,tt_state) VALUES (" + tt_id + ", '" + tt.getCou_id() + "', " + tt.getCou_theoryhour() + ", " + tt.getCou_experimentalhours() + ", " + tt.getCou_practicehour() + ", '" + tt.getT_id() + "', '" + tt.getSy_id() + "', '" + tt.getMultimedia() + "', '" + tt.getM_id() + "', '" + tt.getTt_grade() + "', '" + tt.getPracticescheduling() + "', " + tt.getTt_state() + ")"; // 声明对象执行SQL语句,返回教学任务id if (st.executeUpdate(sql) > 0) return tt_id; // 否则返回-2 else return -2; } /** * 根据条件取得View_teachingtask视图中数据 * * @author czy * @param condition * :查询条件 * @return 满足条件的View_teachingtask类的数组列表 */ public static ArrayList<View_teachingtask> getView_teachingtask( String condition) { // 生成查找“View_teachingtask”视图的select查询语句 String sql = "SELECT * FROM view_teachingtask"; // 如果传入的条件字符串不为空,则根据条件生成sql语句 if (!condition.equals("")) sql += " WHERE " + condition; // 初始化“View_teachingtask”类的数组列表对象 ArrayList<View_teachingtask> View_teachingtasklist = new ArrayList<View_teachingtask>(); // 取得数据库的连接 Connection con = null; ResultSet rs = null; try { con = Databaseconnection.getconnection(); // 如果数据库的连接为空,则返回空 if (con == null) return null; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 rs = st.executeQuery(sql); // 如果结果集有数据 while (rs.next()) { // 取出结果集对应字段数据 int tt_id = rs.getInt("tt_id"); String cou_id = rs.getString("cou_id"); String cou_category = rs.getString("cou_category"); String cou_name = rs.getString("cou_name"); float cou_credit = rs.getFloat("cou_credit"); int cou_theoryhour = rs.getInt("cou_theoryhour"); int cou_experimentalhours = rs.getInt("cou_experimentalhours"); int cou_practicehour = rs.getInt("cou_practicehour"); int cou_semester = rs.getInt("cou_semester"); int cou_type = rs.getInt("cou_type"); String cla_name = rs.getString("cla_name"); int cla_number = rs.getInt("cla_number"); String t_id = rs.getString("t_id"); String t_name = rs.getString("t_name"); String t_tel = rs.getString("t_tel"); int sy_id = rs.getInt("sy_id"); String sy_name = rs.getString("sy_name"); String multimedia = rs.getString("multimedia"); String m_id = rs.getString("m_id"); String tt_grade = rs.getString("tt_grade"); String Practicescheduling = rs.getString("Practicescheduling"); int tt_state = rs.getInt("tt_state"); // 根据结果集的数据生成“View_teachingtask”类对象 View_teachingtask vt = new View_teachingtask(tt_id, cou_id, cou_category, cou_name, cou_credit, cou_theoryhour, cou_experimentalhours, cou_practicehour, cou_semester, cou_type, cla_name, cla_number, t_id, t_name, t_tel, sy_id, sy_name, multimedia, m_id, tt_grade, Practicescheduling, tt_state); // 将“View_teachingtask”类对象添加到“View_teachingtask”类的数组列表对象中 View_teachingtasklist.add(vt); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 返回“View_teachingtask”类的数组列表对象 return View_teachingtasklist; } /** * 根据条件取得teachingtask表中数据 * * @author czy * @param condition * :查询条件 * @return 满足条件的Teachingtask类的数组列表 * */ public static ArrayList<Teachingtask> getTeachingtask(String condition) { // 生成查找“teachingtask”表的select查询语句 String sql = "SELECT * FROM teachingtask"; // 如果传入的条件字符串不为空,则根据条件生成sql语句 if (!condition.equals("")) sql += " WHERE " + condition; // 初始化“teachingtask”类的数组列表对象 ArrayList<Teachingtask> teachingtasklist = new ArrayList<Teachingtask>(); // 取得数据库的连接 Connection con = null; ResultSet rs = null; try { con = Databaseconnection.getconnection(); // 如果数据库的连接为空,则返回空 if (con == null) return null; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 rs = st.executeQuery(sql); // 如果结果集有数据 while (rs.next()) { // 取出结果集对应字段数据 int tt_id = rs.getInt("tt_id"); String cou_id = rs.getString("cou_id"); int cou_theoryhour = rs.getInt("cou_theoryhour"); int cou_experimentalhours = rs.getInt("cou_experimentalhours"); int cou_practicehour = rs.getInt("cou_practicehour"); String t_id = rs.getString("t_id"); int sy_id = rs.getInt("sy_id"); String multimedia = rs.getString("multimedia"); String m_id = rs.getString("m_id"); String tt_grade = rs.getString("tt_grade"); String practicescheduling = rs.getString("Practicescheduling"); int tt_state = rs.getInt("tt_state"); // 根据结果集的数据生成“View_teachingtask”类对象 Teachingtask tt = new Teachingtask(tt_id, cou_id, cou_theoryhour, cou_experimentalhours, cou_practicehour, t_id, sy_id, multimedia, m_id, tt_grade, practicescheduling, tt_state); // 将“View_teachingtask”类对象添加到“View_teachingtask”类的数组列表对象中 teachingtasklist.add(tt); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 返回“View_teachingtask”类的数组列表对象 return teachingtasklist; } /** * 在教学任务表中删除教学任务 * * @param con * :数据库的连接 * @param tt_id * :拟删除的教学任务编号 * @return 删除的记录数 * @throws SQLException */ public static int delete(Connection con, int tt_id) throws SQLException { // 取得数据库的连接 int r; // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; String sql; // 生成数据库声明对象 Statement st = con.createStatement(); // 生成删除教学任务的sql语句 sql = "DELETE FROM teachingtask WHERE tt_id=" + tt_id; // 执行sql语句,返回记录集 r = st.executeUpdate(sql); return r; } /** * * @param con * :数据库的连接 * @param vt * :修改的教学任务信息 * @return 修改成功的记录数 * @throws SQLException */ public static int update(Connection con, View_teachingtask vt) throws SQLException { int r = -1; // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; // 生成插入的sql语句 String sql = "UPDATE teachingtask SET t_id='" + vt.getT_id() + "', multimedia='" + vt.getMultimedia() + "', Practicescheduling='" + vt.getPracticescheduling() + "' WHERE `tt_id`=" + vt.getTt_id(); // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 r = st.executeUpdate(sql); return r; } /** * * @param con * :数据库的连接 * @param tt_id * :要修改的教学任务编号 * @param tt_state * :要修改的教学任务状态 * @return 修改成功的记录数 * @throws SQLException */ public static int updatestate(Connection con, int tt_id, int tt_state) throws SQLException { int r = -1; // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; // 生成插入的sql语句 String sql = "UPDATE teachingtask SET tt_state=" + tt_state + " WHERE `tt_id`=" + tt_id; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 r = st.executeUpdate(sql); return r; } /** * * @param con * :数据库的连接 * @param tt_id * :要修改的教学任务编号 * @param cou_experimentalhours * :要修改的实验课时 * @return 修改成功的记录数 * @throws SQLException */ public static int updateexperimentalhours(Connection con, int tt_id, int cou_experimentalhours) throws SQLException { int r = -1; // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; // 生成插入的sql语句 String sql = "UPDATE teachingtask SET cou_experimentalhours=" + cou_experimentalhours + " WHERE `tt_id`=" + tt_id; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 r = st.executeUpdate(sql); return r; } /** * * @param con * :数据库的连接 * @param tt_id * :要修改的教学任务编号 * @param cou_practicehour * :要修改的实践课时 * @return 修改成功的记录数 * @throws SQLException */ public static int updatepracticehour(Connection con, int tt_id, int cou_practicehour) throws SQLException { int r = -1; // 如果数据库的连接为空或已关闭,则返回空 if (con == null || con.isClosed()) return -1; // 生成插入的sql语句 String sql = "UPDATE teachingtask SET cou_practicehour=" + cou_practicehour + " WHERE `tt_id`=" + tt_id; // 生成数据库声明对象 Statement st = con.createStatement(); // 声明对象执行SQL语句,返回满足条件的结果集 r = st.executeUpdate(sql); return r; } }
package qdu.java.recruit.renwu.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import qdu.java.recruit.renwu.entity.Paper; import qdu.java.recruit.renwu.entity.SuperUser; import qdu.java.recruit.renwu.entity.User; @Mapper public interface SuperUserDaoMapper { //登录 public SuperUser getUser(String username)throws Exception; //获取所有普通用户列表 public List<User> getuserlist(@Param("begin") int begin,@Param("end") int end)throws Exception; //获取所有问卷列表 public List<Paper> getpaperList(@Param("begin") int begin,@Param("end") int end) throws Exception; //删除用户 public void deleteUser(int id) throws Exception; //特定查询一个用户 public User getTheUser(int id) throws Exception; }
package DataStructures.arrays; /** * Created by sydgsk9 on 8/22/2017. */ public class SubsetSummationWithNumberConstraint { }
package com.evan.demo.yizhu.shouye; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TextView; import com.evan.demo.yizhu.R; public class shouye_zhihuixiyi extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shouye_zhihuixiyi); ImageButton back = (ImageButton)findViewById(R.id.xiyi_back); Button btn_paidui1 = (Button)findViewById(R.id.xiyifang_paidui1); Button btn_paidui2 = (Button)findViewById(R.id.xiyifang_paidui2); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { shouye_zhihuixiyi.this.finish(); } }); btn_paidui1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(shouye_zhihuixiyi.this,com.evan.demo.yizhu.shouye.zhihuixiyi_yipaidui.class); startActivity(i); } }); btn_paidui2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(shouye_zhihuixiyi.this,com.evan.demo.yizhu.shouye.zhihuixiyi_yipaidui.class); startActivity(i); } }); } }
/* ==================================================================== * * Copyright (c) Atos Origin INFORMATION TECHNOLOGY All rights reserved. * * ==================================================================== * */ package com.aof.webapp.action; import java.util.*; /** * @author xxp * @version 2003-12-16 * */ public class SiteDefs { static private Hashtable registry = new Hashtable(); public static void Register(String name, Object aInstance) { registry.put(name, aInstance); } public static Object GetInstance(String name) { return LookUp(name); } protected static Object LookUp(String name) { if(registry.get(name)==null){ registry.put(name,new ArrayList()); } return registry.get(name); } }
package com.atguigu.gmall0105.gmall0105publisher.service; import java.util.Map; /** * Created by jxy on 2020/12/22 0022 20:46 */ public interface EsService { public Long getDauTotal(String date); public Map getDauHour(String date); }
package service; public class BrokerService { }
package ch.epfl.moocprog; import static ch.epfl.moocprog.app.Context.getConfig; import static ch.epfl.moocprog.config.Config.ANT_WORKER_HP; import static ch.epfl.moocprog.config.Config.ANT_WORKER_LIFESPAN; import static ch.epfl.moocprog.config.Config.ANT_WORKER_SPEED; import static ch.epfl.moocprog.config.Config.ANT_MAX_FOOD; import static ch.epfl.moocprog.config.Config.ANT_WORKER_ATTACK_DURATION; import static ch.epfl.moocprog.config.Config.ANT_WORKER_MAX_STRENGTH; import static ch.epfl.moocprog.config.Config.ANT_WORKER_MIN_STRENGTH; import ch.epfl.moocprog.utils.Time; public final class AntWorker extends Ant { private double foodQuantity = 0; public AntWorker(ToricPosition tp, Uid hillId) { super(tp, getConfig().getInt(ANT_WORKER_HP), getConfig().getTime(ANT_WORKER_LIFESPAN), hillId); } public AntWorker(ToricPosition tp, Uid hillId, AntRotationProbabilityModel antWRotMod) { super(tp, getConfig().getInt(ANT_WORKER_HP), getConfig().getTime(ANT_WORKER_LIFESPAN), hillId, antWRotMod); } public void accept(AnimalVisitor v, RenderingMedia s) { v.visit(this, s); } public double getFoodQuantity() { return this.foodQuantity; } public void setFoodQuantity(double a) { this.foodQuantity = a; } @Override public double getSpeed() { return getConfig().getDouble(ANT_WORKER_SPEED); } @Override protected int getMinAttackStrength() { return getConfig().getInt(ANT_WORKER_MIN_STRENGTH); } @Override protected int getMaxAttackStrength() { return getConfig().getInt(ANT_WORKER_MAX_STRENGTH); } @Override protected Time getMaxAttackDuration() { return getConfig().getTime(ANT_WORKER_ATTACK_DURATION); } private void uTurn() { this.setDirection(this.getDirection() + Math.PI); /*double nextAngle = this.getDirection() + Math.PI; if (nextAngle > (2*Math.PI)) this.setDirection(this.getDirection()-(2*Math.PI)); else this.setDirection(nextAngle);*/ } public void seekForFood(AntWorkerEnvironmentView env, Time dt) { super.move(env, dt); super.spreadPheromones(env); if (getFoodQuantity() <= 0) { //no food load Food closeSource = env.getClosestFoodForAnt(this); if (closeSource != null) { double foodTaken = closeSource.takeQuantity(getConfig().getDouble(ANT_MAX_FOOD)); setFoodQuantity(foodTaken); uTurn(); } } if (getFoodQuantity() > 0) { //with food load if (env.dropFood(this)) { setFoodQuantity(0); uTurn(); } } } @Override protected void specificBehaviorDispatch(AnimalEnvironmentView env, Time dt) { env.selectSpecificBehaviorDispatch(this, dt); } public String toString() { return super.toString() + String.format("Quantity : %.2f\n", getFoodQuantity()); } }
package com.example.demo.moduls.Systerm.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.example.demo.moduls.Systerm.entity.SystemUser; import org.apache.ibatis.annotations.Mapper; @Mapper public interface SystemUserMapper extends BaseMapper<SystemUser> { }
package com.sapl.retailerorderingmsdpharma.ServerCall; import android.content.Context; import android.util.Log; import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.JsonRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.sapl.retailerorderingmsdpharma.activities.MyApplication; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; /** * Created by JARVIS on 10/31/2017. */ public class HTTPVollyRequest { private String auth; Context mContext; HashMap<String, String> map; MyListener listener; //LTFoodApp app; JSONObject jsonRequest; private RequestQueue mRequestQueue; String requestUrl; int showMessage = 0; // 0 = show Progress Dialog,// 1 = dont show; private final int initTimeout = 300 * 1000; String strMessage = ""; JSONObject jsonObject; static String LOG_TAG = "HTTPVollyRequest"; HashMap<String, String> hashMap = null; int flag = 0; //1 = String Request, 2 = JsonObject Request public HTTPVollyRequest(int flag, JSONObject jsonObject, int showMessage, String strMessage, Context context, String req_url, MyListener listener, HashMap<String,String> hashMap) { Log.i(LOG_TAG, "in HTTPVollyRequest"); this.mContext = context; MyApplication.logi("HTTPVollyRequest","conntext->"+context); MyApplication.logi("HTTPVollyRequest","mContext->"+mContext); this.requestUrl = req_url; this.strMessage = strMessage; this.listener = listener; this.jsonObject = jsonObject; this.flag = flag; this.hashMap = hashMap; this.showMessage = showMessage; doPostOperation(showMessage, strMessage); /* if(showMessage == 0){ doPostOperation(); }else if(showMessage == 1) { doPostOperation(); }*/ } public void doPostOperation(int showMessage, String message) { if (showMessage == 0) { MyApplication.showDialog(mContext, message); } MyApplication.logi("JARVIS doPostOperation 2", ""); MyApplication.logi(LOG_TAG,"requestUrl"+requestUrl); MyApplication.logi(LOG_TAG,"listenerSuccess"+listenerSuccess); MyApplication.logi(LOG_TAG,"listenerError"+listenerError); if (flag == 1) { //FOR GET MyApplication.logi(LOG_TAG,"IN FLAG == 1"); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, requestUrl, null, listenerSuccessJson, listenerError) { @Override protected Map<String, String> getParams() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //Log.e("Auth", auth); headers.put("Content-Type", "application/json; charset=utf-8"); // MyApplication.logi("JARVIS"," parameters:--->"+hashMap.toString()); // if(hashMap != null) return headers; } }; request.setTag("get"); request.setRetryPolicy(new DefaultRetryPolicy(initTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); getRequestQueue().add(request); } else if (flag == 2) { //FOR POST MyApplication.logi(LOG_TAG,"IN FLAG == 2"); MyApplication.logi(LOG_TAG, "MRUNAL obj is" + jsonObject.toString()); MyApplication.logi("MRUNAL","URL ISS-->"+requestUrl); JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, requestUrl, jsonObject, listenerSuccessJson, listenerError); MyApplication.logi(LOG_TAG, "request is" + request.toString()); //HttpsTrustManager.allowAllSSL(); request.setTag("post"); request.setRetryPolicy(new DefaultRetryPolicy(initTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); getRequestQueue().add(request); } } public RequestQueue getRequestQueue() { Log.i(LOG_TAG, "in after getRequestQueue"); if (mRequestQueue == null) { MyApplication.logi("HTTPVollyRequest","getRequestQueue()->"+mContext); Log.i(LOG_TAG, "in after getRequestQueue in if"); // getApplicationContext() is key, it keeps you from leaking the // Activity or BroadcastReceiver if someone passes one in. mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext()); } Log.i(LOG_TAG, "in after getRequestQueue mRequestQueue " + mRequestQueue); return mRequestQueue; } Response.Listener<String> listenerSuccess = new Response.Listener<String>() { @Override public void onResponse(String response) { MyApplication.stopLoading(); listener.success(response); } }; Response.Listener<JSONObject> listenerSuccessJson = new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { MyApplication.stopLoading(); listener.success(response); } }; Response.ErrorListener listenerError = new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError e) { MyApplication.stopLoading(); MyApplication.logi(LOG_TAG,"ERROR OF VOLLEY------>>"+e.networkResponse+" E IS---->"+e.toString()); listener.failure(e.networkResponse); } }; }
package com.javasampleapproach.mysql.association.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "secratary" ) public class Secratary implements Serializable { private static final long serialVersionUID = -3009157732242241606L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name = "name_of_secratary") private String name_of_secratary; @Column(name = "contact_info") private String contact_info; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName_of_secratary() { return name_of_secratary; } public void setName_of_secratary(String name_of_secratary) { this.name_of_secratary = name_of_secratary; } public String getContact_info() { return contact_info; } public void setContact_info(String contact_info) { this.contact_info = contact_info; } @Override public String toString() { return "Secratary [id=" + id + ", name_of_secratary=" + name_of_secratary + ", contact_info=" + contact_info + "]"; } }
package com.webserver.shoppingmall.item.service.impl; import com.webserver.shoppingmall.ShoppingMallApplicationTests; import com.webserver.shoppingmall.item.model.Category; import com.webserver.shoppingmall.item.model.Item; import com.webserver.shoppingmall.item.repository.ItemRepository; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import static org.junit.jupiter.api.Assertions.*; class ItemServiceImplTest extends ShoppingMallApplicationTests { @Autowired ItemRepository itemRepository; @AfterEach void deleteAll() { itemRepository.deleteAll(); System.out.println("아이템 다삭제됨"); } @Test void 아이템등록() { //when String name = "aaa"; int price = 10000; int stockQuantity = 5; String pictureURL = "??"; //when Item item = Item.builder() .name(name) .price(price) .stockQuantity(stockQuantity) .category(Category.BAGS) .pictureURL(pictureURL) .build(); Item result = itemRepository.save(item); //then assertNotNull(result); assertEquals(name, result.getName()); assertEquals(price, result.getPrice()); } }
package org.carpark.barrier; /** * Class to display a sign at an Entry Barrier. * * @author Sian Turner * @version 12/04/05 */ public class EntryBarrierSign { private String message; /** * Constructor for objects of class EntryBarrierSign * @param newMessage the message to be displayed on the sign */ public EntryBarrierSign(String newMessage) { message = newMessage; } /** * Procedure to set the message the sign displays. * @param newMessage the message to be displayed on the sign */ public void setMessage(Object newMessage) { message = newMessage.toString(); } /** * Accessor to return the message currently held by the sign; * @return message */ public String getMessage() { return message; } /** * Procedure to illuminate the sign. * Prints a message. */ public void illuminate() { System.out.println(message); } }
package edu.ncsu.csc563.velocity.actors.components; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import edu.ncsu.csc563.velocity.rendering.GLES20Shader; import android.opengl.GLES20; public class Mesh extends Component { /** Array of handles that identify the buffers associated with this object */ private int[] mBufferHandles; /** FloatBuffer containing the formatted vertex data (position and normals) */ private FloatBuffer mVertices; /** IntBuffer containing the formatted element data */ private IntBuffer mElements; public Mesh(float[] rawVertices, int[] rawElements) { //Order the data in the vertex array and store it in a float buffer ByteBuffer vertexBB = ByteBuffer.allocateDirect(rawVertices.length * 4); vertexBB.order(ByteOrder.nativeOrder()); this.mVertices = vertexBB.asFloatBuffer(); this.mVertices.put(rawVertices); this.mVertices.position(0); //Order the data in the mElements array and store it in a int buffer ByteBuffer elementBB = ByteBuffer.allocateDirect(rawElements.length * 4); elementBB.order(ByteOrder.nativeOrder()); this.mElements = elementBB.asIntBuffer(); this.mElements.put(rawElements); this.mElements.position(0); //Generate handles for buffers to store data on the graphics card this.mBufferHandles = new int[2]; this.setOGLResources(); } public void setOGLResources() { //mBufferHandles[0] is the handle to the vertex buffer //mBufferHandles[1] is the handle to the element buffer GLES20.glGenBuffers(2, this.mBufferHandles, 0); //Bind the vertex buffer generated earlier, and put the buffered vertex data on the graphics card GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.mBufferHandles[0]); GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, 4 * this.mVertices.capacity(), this.mVertices, GLES20.GL_STATIC_DRAW); //Bind the element buffer generated earlier and put the buffered data on the graphics card GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, this.mBufferHandles[1]); GLES20.glBufferData(GLES20.GL_ELEMENT_ARRAY_BUFFER, 4 * this.mElements.capacity(), this.mElements, GLES20.GL_STATIC_DRAW); } public void draw() { //Bind the array buffer using the handle we generated for the vertex buffer earlier, //to tell the graphics card which buffer we're talking about when we issue the next few //commands GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, this.mBufferHandles[0]); //Tell the graphics card how position data is stored in our vertex buffer, so the shader knows //where to get the data for the "position" attribute value in the shader GLES20.glEnableVertexAttribArray(GLES20Shader.ATTRIB_POSITION); GLES20.glVertexAttribPointer(GLES20Shader.ATTRIB_POSITION, 3, GLES20.GL_FLOAT, false, 8 * 4, 0); //Tell the graphics card how normal data is stored in our vertex buffer, so the shader knows //where to get the data for the "normal" attribute value in the shader GLES20.glEnableVertexAttribArray(GLES20Shader.ATTRIB_NORMAL); GLES20.glVertexAttribPointer(GLES20Shader.ATTRIB_NORMAL, 3, GLES20.GL_FLOAT, false, 8 * 4, 12); GLES20.glEnableVertexAttribArray(GLES20Shader.ATTRIB_TEXCOORD); GLES20.glVertexAttribPointer(GLES20Shader.ATTRIB_TEXCOORD, 2, GLES20.GL_FLOAT, false, 8 * 4, 24); //Bind the element buffer using the handle we generated for the element buffer earlier, //to tell the graphics card which buffer we're talking about when we issue the next few //commands GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, this.mBufferHandles[1]); //Issue a command to the graphics card, telling it to draw triangles using the provided data, of which //there are mElements.capacity() total vertices, with the element data provided as unsigned ints (4 bytes //per element value), and starting at offset 0 into the bound element array buffer GLES20.glDrawElements(GLES20.GL_TRIANGLES, this.mElements.capacity(), GLES20.GL_UNSIGNED_INT, 0); } }
package com.git.cloud.resmgt.network.model.vo; import java.util.HashMap; //网络地址区间信息 public class NetIPInfo { /** * 网络地址类型编码,主要取值范围: * HP 物理机生产地址 * HM 物理机管理地址 * HV 物理机管理-vMontion地址 * HL 物理机管理-ILO地址 * HF1 物理机管理-FSP1地址 * HF2 物理机管理-FSP2地址 * NP NAS存储生产地址 * NM NAS存储管理地址 * VP 虚拟机生产地址 * VM 虚拟机管理地址 * VR 虚拟机RAC心跳地址 */ private String ipType; /** * 网络C段用途编码,主要取值范围: * XHP X86物理机生产 * XHM X86物理机管理 * XHV X86物理机管理-vMotion * XHL X86物理机管理-ILO * XVP X86虚拟机生产 * XVM X86虚拟机管理 * PHP Power物理机生产 * PHM Power物理机管理 * PHF1 Power物理机管理-FSP1 * PHF2 Power物理机管理-FSP2 * PVP Power虚拟机生产 * PVM Power虚拟机管理 * PVR Power虚拟机RAC心跳 * BHM X86非虚拟化物理机管理 * WHM Power非虚拟化物理机管理 * HHM 惠普非虚拟化物理机管理 */ private String ipClassType; // 网络C段名称 private String className; // 安全区域编码 private String secureArea; /** * 安全分层编码,主要取值范围: * 1 互联网DMZ服务区 * 2 外联网DMZ服务区 * 3 开放服务区 * 4 运行管理服务区(管理支撑区) * 5 主机平台服务区 * 6 广域网区 * 7 托管服务区 */ private String secureTier; // VLAN ID private String vlanID; // 子网掩码 private String ipMask; // 网关 private String gateWay; // 分配的地址 private String ip; private String id; // //20140108增加 设备ID // private Long deviceId; // // public Long getDeviceId() { // return deviceId; // } // // public void setDeviceId(Long deviceId) { // this.deviceId = deviceId; // } /** * 扩展信息,包括端口组/SEA信息等 * HashMap Key主要取值范围: * VMware: * VMWARE_VS : 虚拟交换机名称 * VMWARE_PGTYP : 端口组类型 * VMWARE_PGNAM : 端口组名称 * Power: * POWER_SEA : Power VIOS SEA名称 * POWER_NIC : Power VIOC NIC名称 */ private HashMap<String, String> extendInfo = new HashMap<String, String>(); /** * @return ipType 网络地址类型编码 */ public String getIpType() { return ipType; } /** * @param ipType 设置的网络地址类型编码值 */ public void setIpType(String ipType) { this.ipType = ipType; } /** * @return ipClassType 网络C段用途编码 */ public String getIpClassType() { return ipClassType; } /** * @param ipClassType 设置的网络C段用途编码值 */ public void setIpClassType(String ipClassType) { this.ipClassType = ipClassType; } /** * @return className 网络C段名称 */ public String getClassName() { return className; } /** * @param className 设置的网络C段名称值 */ public void setClassName(String className) { this.className = className; } /** * @return secureArea 安全区域编码 */ public String getSecureArea() { return secureArea; } /** * @param secureArea 设置的安全区域编码值 */ public void setSecureArea(String secureArea) { this.secureArea = secureArea; } /** * @return secureTier 安全分区编码 */ public String getSecureTier() { return secureTier; } /** * @param secureTier 设置的安全分区编码值 */ public void setSecureTier(String secureTier) { this.secureTier = secureTier; } /** * @return VLAN ID */ public String getVlanID() { return vlanID; } /** * @param vlanID 设置的VLAN ID值 */ public void setVlanID(String vlanID) { this.vlanID = vlanID; } /** * @return ipMask 子网掩码 */ public String getIpMask() { return ipMask; } /** * @param ipMask 设置的子网掩码值 */ public void setIpMask(String ipMask) { this.ipMask = ipMask; } /** * @return ipMask 网关 */ public String getGateWay() { return gateWay; } /** * @param gateWay 设置的网关值 */ public void setGateWay(String gateWay) { this.gateWay = gateWay; } /** * @return ip 分配的地址 */ public String getIp() { return ip; } /** * @param ip 设置的分配的地址值 */ public void setIp(String ip) { this.ip = ip; } /** * @return extendInfo 分配地址的扩展信息 */ public HashMap<String, String> getExtendInfo() { return extendInfo; } /** * @param extendInfo 设置的分配地址的扩展信息 */ public void setExtendInfo(HashMap<String, String> extendInfo) { this.extendInfo = extendInfo; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
package edu.gatech.oad.fullhouse.findmystuff.test; import java.util.List; import edu.gatech.oad.fullhouse.findmystuff.R; import edu.gatech.oad.fullhouse.findmystuff.dao.UserAccessor; import edu.gatech.oad.fullhouse.findmystuff.model.User; import edu.gatech.oad.fullhouse.findmystuff.pres.RegisterPresenter; import edu.gatech.oad.fullhouse.findmystuff.view.RegisterActivity; import android.test.ActivityInstrumentationTestCase2; import android.view.View; public class RegisterPresenterTest extends ActivityInstrumentationTestCase2<RegisterActivity> { public RegisterPresenterTest() { super(RegisterActivity.class); } private class TestUserAccessor implements UserAccessor { private User testUser; private boolean userCreated = false; public TestUserAccessor(User testUser) { this.testUser = testUser; } public void addUser(User user) { userCreated= true; } public User getUserByUsername(String username) { if (this.testUser.getUsername().equals(username)) { return this.testUser; } else { return null; } } public User getUserByEmail(String email) { if (this.testUser.getEmail().equals(email)) { return this.testUser; } else { return null; } } public List<User> getUsers() { fail("getUsers should not be called"); return null; } public void updateUser(User user) { fail("updateUser should not be called"); } public void deleteUser(User user) { fail("deleteUser should not be called"); } } private User getTestUser() { User testUser = new User(); testUser.setUsername("test"); testUser.setEmail("test@email.com"); testUser.setName("Test User"); testUser.setAdmin(false); return testUser; } private void assertUsernameErrorVisibility(int vis) { assertEquals(vis, getActivity().findViewById(R.id.registerUsernameError).getVisibility()); } private void assertEmailErrorVisibility(int vis) { assertEquals(vis, getActivity().findViewById(R.id.registerEmailError).getVisibility()); } private void assertEmailFormatErrorVisibility(int vis) { assertEquals(vis, getActivity().findViewById(R.id.registerEmailFormatError).getVisibility()); } private void assertPasswordMismatchErrorVisibility(int vis) { assertEquals(vis, getActivity().findViewById(R.id.registerPasswordMismatchError).getVisibility()); } private void assertUserCreated(TestUserAccessor accessor) { assertTrue(accessor.userCreated); } private void assertUserNotCreated(TestUserAccessor accessor) { assertFalse(accessor.userCreated); } /** * Tests if registerUsernameError is displayed when user enters a duplicate username * * @throws Throwable */ public void testRegisterUsernameError() throws Throwable { RegisterActivity activity = getActivity(); assertNotNull(activity); final User testUser = getTestUser(); TestUserAccessor accessor = new TestUserAccessor(testUser); final RegisterPresenter presenter = new RegisterPresenter(activity, accessor); runTestOnUiThread(new Runnable() { public void run() { presenter.checkRegInfo(testUser.getUsername(), "myPassword", "myPassword", "myName", "myLocation", "myEmail@email.com", "myPhone"); } }); Thread.sleep(1000); assertUsernameErrorVisibility(View.VISIBLE); assertUserNotCreated(accessor); } /** * Tests if registerEmailError is displayed when user enters a duplicate email address * * @throws Throwable */ public void testRegisterEmailError() throws Throwable { RegisterActivity activity = getActivity(); assertNotNull(activity); final User testUser = getTestUser(); TestUserAccessor accessor = new TestUserAccessor(testUser); final RegisterPresenter presenter = new RegisterPresenter(activity, accessor); runTestOnUiThread(new Runnable() { public void run() { presenter.checkRegInfo("myUsername", "myPassword", "myPassword", "myName", "myLocation", testUser.getEmail(), "myPhone"); } }); Thread.sleep(1000); assertEmailErrorVisibility(View.VISIBLE); assertUserNotCreated(accessor); } /** * Tests if registerEmailFormatError is displayed when user enters an invalid email address * * @throws Throwable */ public void testRegisterEmailFormatError() throws Throwable { RegisterActivity activity = getActivity(); assertNotNull(activity); final User testUser = getTestUser(); TestUserAccessor accessor = new TestUserAccessor(testUser); final RegisterPresenter presenter = new RegisterPresenter(activity, accessor); runTestOnUiThread(new Runnable() { public void run() { presenter.checkRegInfo("myUsername", "myPassword", "myPassword", "myName", "myLocation", "myEmail", "myPhone"); } }); Thread.sleep(1000); assertEmailFormatErrorVisibility(View.VISIBLE); assertUserNotCreated(accessor); } /** * Tests if registerPasswordMismatchError is displayed when user enters two different passwords * * @throws Throwable */ public void testRegisterPasswordMismatchError() throws Throwable { RegisterActivity activity = getActivity(); assertNotNull(activity); final User testUser = getTestUser(); TestUserAccessor accessor = new TestUserAccessor(testUser); final RegisterPresenter presenter = new RegisterPresenter(activity, accessor); runTestOnUiThread(new Runnable() { public void run() { presenter.checkRegInfo("myUsername", "myPassword", "differentPassword", "myName", "myLocation", "myEmail@email.com", "myPhone"); } }); Thread.sleep(1000); assertPasswordMismatchErrorVisibility(View.VISIBLE); assertUserNotCreated(accessor); } /** * Tests if User is created successfully when user enters valid information * * @throws Throwable */ public void testRegisterUserSuccess() throws Throwable { RegisterActivity activity = getActivity(); assertNotNull(activity); final User testUser = getTestUser(); TestUserAccessor accessor = new TestUserAccessor(testUser); final RegisterPresenter presenter = new RegisterPresenter(activity, accessor); runTestOnUiThread(new Runnable() { public void run() { presenter.checkRegInfo("myUsername", "myPassword", "myPassword", "myName", "myLocation", "myEmail@email.com", "myPhone"); } }); Thread.sleep(1000); assertUserCreated(accessor); } }
// ********************************************************** // 1. 제 목: PROPOSE STATUS DATA // 2. 프로그램명: ProposeStatusData.java // 3. 개 요: 신청 현황 data bean // 4. 환 경: JDK 1.3 // 5. 버 젼: 1.0 // 6. 작 성: 박진희 2003. 8. 20. // 7. 수 정: // ********************************************************** package com.ziaan.propose; public class ProposeStatusData { private String grseq; private String grseqnm; private String course; private String cyear; private String courseseq; private String coursenm; private String subj; private String year; private String subjseq; private String subjseqgr; private String subjnm; private String companynm; /* 회사명 */ private String compnm; /* 소속명 */ private String jikwinm; /* 직위명 */ private String jikunnm; /* 직군명 */ private String jikupnm; /* 직급명 */ private String userid ; /* ID */ private String cono; /* 사번 */ private String name; /* 이름 */ private String position_nm; /* 부서 */ private String lvl_nm; /* 직급 */ private String appdate; /* 신청일 */ private String biyong; private String goyongpricemajor; private String goyongpriceminor; private String edustart; /* 교육 시작일시 */ private String eduend; /* 교육 종료일시 */ private String isproposeapproval; /* 현업팀장결재 승인 여부 */ private String chkfirst; /* 1차 승인 여부 */ private String chkfinal; /* 최종 승인 여부 */ private String email; private String ismailing; private String isnewcourse; private String canceldate; /* 취소일 */ private String cancelkind; /* 취소구분 */ private String reason; /* 취소사유 */ private String propstart; /* 수강신청 시작일시 */ private String propend; /* 수강신청 시작일시 */ private String isonoff; private int studentlimit; /* 정원 */ private int procnt; /* 수강신청 인원 */ private int cancnt; /* 수강신청취소 인원 */ private int rowspan; private int dispnum; private int totalpagecount; private int rowcount; private String amount; private String order_id; private String paycd; private String paynm; public String getPaynm() { return paynm; } public void setPaynm(String paynm) { this.paynm = paynm; } private String enter_dt; private String enter_yn; private String repay_dt; public String getOrder_id() { return order_id; } public void setOrder_id(String order_id) { this.order_id = order_id; } public String getPaycd() { return paycd; } public void setPaycd(String paycd) { this.paycd = paycd; } public String getEnter_dt() { return enter_dt; } public void setEnter_dt(String enter_dt) { this.enter_dt = enter_dt; } public String getEnter_yn() { return enter_yn; } public void setEnter_yn(String enter_yn) { this.enter_yn = enter_yn; } public String getRepay_dt() { return repay_dt; } public void setRepay_dt(String repay_dt) { this.repay_dt = repay_dt; } public String getRepay_yn() { return repay_yn; } public void setRepay_yn(String repay_yn) { this.repay_yn = repay_yn; } private String repay_yn; public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public ProposeStatusData() { }; /** * @return */ public String getAppdate() { return appdate; } public void setBiyong(String string) { biyong = string; } /** * @return */ public String getBiyong() { return biyong; } public void setGoyongpricemajor(String string) { goyongpricemajor = string; } /** * @return */ public String getGoyongpricemajor() { return goyongpricemajor; } public void setGoyongpriceminor(String string) { goyongpriceminor = string; } /** * @return */ public String getGoyongpriceminor() { return goyongpriceminor; } /** * @return */ public String getChkfinal() { return chkfinal; } /** * @return */ public String getChkfirst() { return chkfirst; } /** * @return */ public String getIsproposeapproval() { return isproposeapproval; } /** * @return */ public String getCompnm() { return compnm; } /** * @return */ public String getCono() { return cono; } /** * @return */ public String getCourse() { return course; } /** * @return */ public String getCoursenm() { return coursenm; } /** * @return */ public String getCourseseq() { return courseseq; } /** * @return */ public String getCyear() { return cyear; } /** * @return */ public String getEduend() { return eduend; } /** * @return */ public String getEdustart() { return edustart; } /** * @return */ public String getEmail() { return email; } /** * @return */ public String getGrseq() { return grseq; } /** * @return */ public String getGrseqnm() { return grseqnm; } /** * @return */ public String getIsmailing() { return ismailing; } /** * @return */ public String getIsnewcourse() { return isnewcourse; } /** * @return */ public String getJikwinm() { return jikwinm; } /** * @return */ public String getJikupnm() { return jikupnm; } /** * @return */ public String getName() { return name; } public String getPosition_nm() { return position_nm; } public String getLvl_nm() { return lvl_nm; } /** * @return */ public int getRowspan() { return rowspan; } /** * @return */ public String getSubj() { return subj; } /** * @return */ public String getSubjnm() { return subjnm; } /** * @return */ public String getSubjseq() { return subjseq; } /** * @return */ public String getSubjseqgr() { return subjseqgr; } /** * @return */ public String getUserid() { return userid; } /** * @return */ public String getYear() { return year; } /** * @return */ public String getCanceldate() { return canceldate; } /** * @return */ public String getCancelkind() { return cancelkind; } /** * @return */ public String getReason() { return reason; } /** * @return */ public String getPropstart() { return propstart; } /** * @return */ public String getPropend() { return propend; } /** * @return */ public int getStudentlimit() { return studentlimit; } /** * @return */ public int getProcnt() { return procnt; } /** * @return */ public int getCancnt() { return cancnt; } /** * @param string */ public void setAppdate(String string) { appdate = string; } /** * @param string */ public void setChkfinal(String string) { chkfinal = string; } /** * @param string */ public void setChkfirst(String string) { chkfirst = string; } /** * @param string */ public void setIsproposeapproval(String string) { isproposeapproval = string; } /** * @param string */ public void setCompnm(String string) { compnm = string; } /** * @param string */ public void setCono(String string) { cono = string; } /** * @param string */ public void setCourse(String string) { course = string; } /** * @param string */ public void setCoursenm(String string) { coursenm = string; } /** * @param string */ public void setCourseseq(String string) { courseseq = string; } /** * @param string */ public void setCyear(String string) { cyear = string; } /** * @param string */ public void setEduend(String string) { eduend = string; } /** * @param string */ public void setEdustart(String string) { edustart = string; } /** * @param string */ public void setEmail(String string) { email = string; } /** * @param string */ public void setGrseq(String string) { grseq = string; } /** * @param string */ public void setGrseqnm(String string) { grseqnm = string; } /** * @param string */ public void setIsmailing(String string) { ismailing = string; } /** * @param string */ public void setIsnewcourse(String string) { isnewcourse = string; } /** * @param string */ public void setJikwinm(String string) { jikwinm = string; } /** * @param string */ public void setJikupnm(String string) { jikupnm = string; } /** * @param string */ public void setName(String string) { name = string; } public void setPosition_nm(String string) { position_nm = string; } public void setLvl_nm(String string) { lvl_nm = string; } /** * @param i */ public void setRowspan(int i) { rowspan = i; } /** * @param string */ public void setSubj(String string) { subj = string; } /** * @param string */ public void setSubjnm(String string) { subjnm = string; } /** * @param string */ public void setSubjseq(String string) { subjseq = string; } /** * @param string */ public void setSubjseqgr(String string) { subjseqgr = string; } /** * @param string */ public void setUserid(String string) { userid = string; } /** * @param string */ public void setYear(String string) { year = string; } /** * @param string */ public void setCanceldate(String string) { canceldate = string; } /** * @param string */ public void setCancelkind(String string) { cancelkind = string; } /** * @param string */ public void setReason(String string) { reason = string; } /** * @param string */ public void setPropstart(String string) { propstart = string; } /** * @param string */ public void setPropend(String string) { propend = string; } /** * @param string */ public void setStudentlimit(int string) { studentlimit = string; } /** * @param string */ public void setProcnt(int string) { procnt = string; } /** * @param string */ public void setCancnt(int string) { cancnt = string; } public void setDispnum (int dispnum) { this.dispnum = dispnum; } public int getDispnum() { return dispnum; } public void setTotalPageCount(int totalpagecount) { this.totalpagecount = totalpagecount; } public int getTotalPageCount() { return totalpagecount; } public void setRowCount(int rowcount) { this.rowcount = rowcount; } public int getRowCount() { return rowcount; } public void setJikunnm(String jikunnm) { this.jikunnm = jikunnm; } public String getJikunnm() { return jikunnm; } public void setCompanynm(String companynm) { this.companynm = companynm; } public String getCompanynm() { return companynm; } /** * @param string */ public void setIsonoff(String string) { isonoff = string; } /** * @return */ public String getIsonoff() { return isonoff; } }
package com.qiyewan.crm_joint.service; import com.qiyewan.crm_joint.domain.ContractService; import com.qiyewan.crm_joint.domain.ContractServiceRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ContractServiceServiceImpl implements ContractServiceService { @Autowired private ContractServiceRepository contractServiceRepository; @Override public List<ContractService> getContractServices(String contractSno) { return contractServiceRepository.findByContractSno(contractSno); } }
package com.esum.web.monitor.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.esum.appetizer.config.Configurer; import com.esum.appetizer.controller.AbstractController; import com.esum.web.apps.nodeinfo.service.NodeInfoService; @Controller public class MonitorController extends AbstractController { @Autowired private NodeInfoService nodeInfoService; @RequestMapping(value = "/monitor/dashboard") public String main(HttpServletRequest request, Model model) { List<String> nodeIdList = nodeInfoService.getNodeIdList(); model.addAttribute("nodeIdList", nodeIdList); model.addAttribute("LICENSE_NODE_ID", Configurer.getProperty("Common.LICENSE_NODE.ID")); return "/monitor/dashboard"; } }
public class singleton3 {//饿汉式的 //直接进行实例化就不会产生线程不安全的,但是这样也就没有了之前的延迟实例化的好处 //基于classloader机制 private static singleton3 uniqueistance =new singleton3(); private singleton3(){} public static singleton3 getuniqueinstance(){ return uniqueistance; } }
package Gerente; import java.io.IOException; import java.util.List; import Controle.*; import Exception.*; public class Gerente { private ControleAluno aluno; private ControleExercicios exercicios; private ControleArquivo arquivo; private ControleProfessor professor; public Gerente(){ this.arquivo = new ControleArquivo(); try { this.aluno = this.arquivo.lerControleAluno(); } catch (IOException e) { this.aluno = new ControleAluno(); } try { this.exercicios = this.arquivo.lerControleExercicio(); } catch (IOException e) { this.exercicios = new ControleExercicios(); } try { this.professor = this.arquivo.lerControleProfessor(); } catch (IOException e) { this.professor = new ControleProfessor(); } } public void cadastrarQuestao(String nomeProfessor, String nomeExercicio, String tipoQuestao, String pergunta, String resposta){ this.exercicios.cadastrarQuestao(nomeProfessor, nomeExercicio, tipoQuestao, pergunta, resposta); } public void removerQuestao(String nomeProfessor, String nomeExercicio, String pergunta) throws ProfessorInexistenteException, QuestaoInexistenteException{ this.exercicios.removerQuestao(nomeProfessor, nomeExercicio, pergunta); } public boolean existeQuestaoDeExercicio(String nomeProfessor, String nomeExercicio, String pergunta) throws ProfessorInexistenteException{ return this.exercicios.existeQuestaoDeExercicio(nomeProfessor, nomeExercicio, pergunta); } public void setResposta(String nomeProfessor, String nomeExercicio, String novaResposta, String resposta) throws ProfessorInexistenteException, QuestaoInexistenteException{ this.exercicios.setResposta(nomeProfessor, nomeExercicio, novaResposta, resposta); } public String getResposta(String nomeProfessor, String nomeExercicio, String pergunta) throws ProfessorInexistenteException, QuestaoInexistenteException{ return this.exercicios.getResposta(nomeProfessor, nomeExercicio, pergunta); } public void setPergunta(String nomeProfessor, String nomeExercicio, String NovaPergunta, String pergunta) throws ProfessorInexistenteException, QuestaoInexistenteException{ this.exercicios.setPergunta(nomeProfessor, nomeExercicio, NovaPergunta, pergunta); } public String getPergunta(String nomeProfessor, String nomeExercicio, String resposta) throws ProfessorInexistenteException, QuestaoInexistenteException{ return this.exercicios.getPergunta(nomeProfessor, nomeExercicio, resposta); } public String getListaExercicio(String nomeProfessor, String nomeExercicio) throws ProfessorInexistenteException{ return this.exercicios.getListaExercicio(nomeProfessor, nomeExercicio); } public String getListaTodosExercicio() { return this.exercicios.getListExerciciosCadastrado(); } public List<List<String>> getSortearExercicio() throws ListaVaziaExeception{ return this.exercicios.getSortearExercicio(); } public String getListaDosNomesExerc(String nomeProfessor) throws ProfessorInexistenteException{ return this.exercicios.getListaDosNomesExerc(nomeProfessor); } public void cadastrarAluno(String nome, String matricula) throws AlunoJaExisteException{ this.aluno.cadastrarAluno(nome, matricula); } public String getCorrecaoExercicio(List<String> perguntas, List<String> resposta, List<String> respostaAluno) { return this.exercicios.getCorrecaoExercicio(perguntas, resposta, respostaAluno); } public String getProvaAluno(String matricula) throws AlunoNaoExisteException{ return this.aluno.getProvaAluno(matricula); } public void setProvaAluno(String matricula, String prova) throws AlunoNaoExisteException{ this.aluno.setProvaAluno(matricula, prova); } public void gravarAluno() throws IOException{ this.arquivo.gravarControleAluno(aluno); } public void gravarExercicio() throws IOException{ this.arquivo.gravaControleExercicio(exercicios); } public void gravarProfessor() throws IOException{ this.arquivo.gravaControleprofessor(this.professor); } public boolean isMatricula(String matricula) { return this.aluno.isMatricula(matricula); } public String getExercicioAtual(){ return this.exercicios.getExercicioAtual(); } public String getNomeAluno(String matricula){ return this.aluno.getNomeAluno(matricula); } public ControleProfessor getProfessor(){ return this.professor; } }
package dataFactory; import po.CreditInfoPO; import java.util.ArrayList; /** * Created by njulgh on 16-12-5. */ public interface CreditDataHelper { public ArrayList<CreditInfoPO> getCustomerCredits(String userName); public ArrayList<CreditInfoPO> insert(CreditInfoPO cipo); }
package Lec_02_SimpleOperationsAndCalculations; import java.util.Scanner; public class Lab08_YardGreening { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Въведете площа за озеленяване: "); double area = Double.parseDouble(scanner.nextLine()); double priceForArea = area * 7.61; double discount = priceForArea * 0.18; double finalPrice = priceForArea - discount; System.out.printf("The final price is: %.2f lv.%nThe discount is: %.2f lv.", finalPrice, discount); } }
package com.bupsolutions.polaritydetection.ml.rnn; import com.bupsolutions.polaritydetection.model.LabeledTextSet; import com.bupsolutions.polaritydetection.model.Polarity; public class RNNPolarityTrainer extends RNNTrainer<Polarity> { public RNNPolarityTrainer() { super(new RNNPolarityModel()); } public RNNPolarityTrainer(RNNModel<Polarity> model) { super(model); } @Override public RNNPolarityModel train(LabeledTextSet<Polarity> trainingSet) { return new RNNPolarityModel(fit(trainingSet)); } }
package com.gamzat; public class Main { public static void main(String[] args) { int Finger = 1; // Пальцы. while (Finger <= 10 ) { System.out.println("Палец номер " + Finger); ++Finger; } } }
package br.unb.poo.mh; public class Igual extends ExpressaoBinaria { public Igual(Expressao expDireita, Expressao expEsquerda) { super(expDireita, expEsquerda); } @Override public Valor avaliar() { if(expEsquerda.tipo() == Tipo.Booleano){ ValorBooleano v1 = (ValorBooleano) expEsquerda.avaliar(); ValorBooleano v2 = (ValorBooleano) expDireita.avaliar(); if(v2.getValor() == v1.getValor()){ return new ValorBooleano(true); } } else if(expEsquerda.tipo() == Tipo.Inteiro){ ValorInteiro v1 = (ValorInteiro) expEsquerda.avaliar(); ValorInteiro v2 = (ValorInteiro) expDireita.avaliar(); if(v2.getValor() == v1.getValor()){ return new ValorBooleano(true); } } return new ValorBooleano(false); } @Override public Tipo tipo() { return ((expEsquerda.tipo() == Tipo.Inteiro && expDireita.tipo() == Tipo.Inteiro) || (expEsquerda.tipo() == Tipo.Booleano && expDireita.tipo() == Tipo.Booleano)) ? Tipo.Booleano : Tipo.Error; } @Override public void aceitar(Visitor v) { v.visitar(this); } }
package 数据库.JDBC入门; import java.sql.*; import java.util.ResourceBundle; public class Demo1 { public static void main(String[] args) throws ClassNotFoundException, SQLException { ResourceBundle RD = ResourceBundle.getBundle("数据库.JDBC入门.data"); Class.forName(RD.getString("jdbc.Driver")); //com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver(); //DriverManager.registerDriver(driver); Connection con = DriverManager.getConnection(RD.getString("jdbc.url"), RD.getString("jdbc.username"), RD.getString("jdbc.password")); Statement state = con.createStatement(); String sql = "INSERT INTO tb_stu values (null , '杜甫',20,'男','1998-2-4')"; int change = state.executeUpdate(sql); ResultSet set = state.executeQuery("select * from emp"); //解析ResultSet while (set.next()) { //判断下一行是否存在 String name = set.getString("ename"); //通过名称来获取该列的值 String job = set.getString(4); //通过编号来获取该列的值 double sal = set.getDouble(5); System.out.println(name + "、" + job + "、" + sal); } //最后关闭资源 , 倒关 set.close(); state.close(); con.close(); } }
import java.io.FileNotFoundException; import java.io.IOException; import virtualdisk.DiskThread; import virtualdisk.VirtualDisk; import common.Constants; import dblockcache.DBufferCache; import dfs.DFS; public class TestLoad { public static void main(String[] args) throws FileNotFoundException, IOException { DFS deFiler = new DFS(); DBufferCache cache = new DBufferCache(Constants.NUM_OF_CACHE_BLOCKS); deFiler.myCache = cache; VirtualDisk disk = new VirtualDisk("Seans disk", false); cache.myVD = disk; DiskThread diskThread = new DiskThread(disk); diskThread.start(); ThreadLoad three = new ThreadLoad(deFiler); three.start(); } }
package com.tutorialspoint.collections; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("BeansCollections.xml"); JavaCollections bean = (JavaCollections) context.getBean("collections", JavaCollections.class); bean.getList(); bean.getMap(); bean.getProps(); bean.getSet(); } }
package cn.happy.spring1006aspectj; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; /** * Created by LY on 2017/10/6. */ @Aspect public class MyAspectj { //@Before(value = "execution(* *..spring1006aspectj.*.*(..))") public void myBefore(){ System.out.println("==============我是前置增强内容========="); } /*@After()最终增强*/ // @AfterReturning(value = "execution(* *..spring1006aspectj.*.*(..))") public void myAfter(){ System.out.println("==============我是后置增强内容========="); } @Around(value = "execution(* *..spring1006aspectj.*.*(..))" ) public Object myAround(ProceedingJoinPoint p) throws Throwable { System.out.println("我是环绕前"); Object result= p.proceed(); System.out.println("我是环绕后"); if(result!=null){ String str=(String)result; return str.toUpperCase(); }else{ return null; } } }
package com.ajhlp.app.integrationTools.services.impl; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ajhlp.app.integrationTools.model.DBType; import com.ajhlp.app.integrationTools.services.IDBTypeEditService; import com.ajhlp.app.integrationTools.util.CopyPropertiesUtil; @Service("dbTypeService") @Transactional public class DBTypeEditServiceImpl extends BasicServiceImpl implements IDBTypeEditService { public void saveDBType(DBType dbType) throws DataAccessException { // TODO Auto-generated method stub if(dbType.getId()==0){ save(dbType); }else{ DBType old = findByID(dbType.getId(), DBType.class); CopyPropertiesUtil.copy(dbType, old); update(old); } } }
package Veiculo; public class CarroPasseio extends Veiculo { private String cor; private String modelo; public String getCor() { return cor; } public void setCor(String cor) { this.cor = cor; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public void MostrPass() { System.out.println("O carro "+getModelo()+" na cor "+getCor()+" pesa "+getPesoKg()+"Kg, seu preço é de R$"+getPrecoRs()+" e sua velocidade máxima é de "+getVelocMaxKmH()+"Km/H."); } }
package strategy01; public class NormalFreight implements Freight { @Override public double calculate(Integer numKilometers) { return numKilometers * 1.2D; } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.data; import java.io.File; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import net.datacrow.core.DataCrow; import net.datacrow.core.DcRepository; import net.datacrow.core.db.DatabaseManager; import net.datacrow.core.db.SelectQuery; import net.datacrow.core.modules.DcModule; import net.datacrow.core.modules.DcModules; import net.datacrow.core.objects.DcAssociate; import net.datacrow.core.objects.DcField; import net.datacrow.core.objects.DcMapping; import net.datacrow.core.objects.DcObject; import net.datacrow.core.objects.DcProperty; import net.datacrow.core.objects.DcSimpleValue; import net.datacrow.core.objects.Loan; import net.datacrow.core.objects.Picture; import net.datacrow.core.objects.Tab; import net.datacrow.core.objects.helpers.ExternalReference; import net.datacrow.core.resources.DcResources; import net.datacrow.core.services.OnlineSearchHelper; import net.datacrow.core.services.SearchTask; import net.datacrow.core.wf.WorkFlow; import net.datacrow.settings.definitions.DcFieldDefinition; import net.datacrow.settings.definitions.WebFieldDefinition; import net.datacrow.util.DcImageIcon; import net.datacrow.util.DcSwingUtilities; import net.datacrow.util.StringUtils; import net.datacrow.util.Utilities; import org.apache.log4j.Logger; /** * @author Robert Jan van der Waals */ public class DataManager { private static Logger logger = Logger.getLogger(DataManager.class.getName()); private static Map<String, DcImageIcon> icons = new HashMap<String, DcImageIcon>(); static { for (String file : new File(DataCrow.iconsDir).list()) { icons.put(file.substring(0, file.length() - 4), new DcImageIcon(DataCrow.iconsDir + file)); } } public static DcImageIcon addIcon(String ID, String base64) { DcImageIcon icon = null; if (icons.containsKey(ID)) { icon = icons.get(ID); } else { if (base64 != null) { icon = Utilities.base64ToImage(base64); String filename = DataCrow.iconsDir + ID + ".png"; icon.setFilename(filename); icon.save(); } icons.put(ID, icon); } if (icon != null && !icon.exists()) icon.save(); // re-load image if necessary if (icon != null) icon.setImage(icon.getImage()); return icon; } public static DcImageIcon getIcon(DcObject dco) { DcImageIcon icon; if (icons.containsKey(dco.getID()) && icons.get(dco.getID()) != null) { icon = icons.get(dco.getID()); } else { icon = dco.createIcon(); if (icon != null) { String filename = DataCrow.iconsDir + dco.getID() + ".png"; icon.setFilename(filename); icon.save(); } icons.put(dco.getID(), icon); } if (icon != null && !icon.exists()) { // check if the file exists if (icon.getFile() == null && icon.getFilename() == null) { icon.setFilename(DataCrow.iconsDir + dco.getID() + ".png"); icons.put(dco.getID(), icon); } icon.save(); } if (icon != null) icon.setImage(icon.getImage()); return icon; } public static void removeIcon(String ID) { updateIcon(ID); } public static void updateIcon(String ID) { DcImageIcon icon = icons.remove(ID); if (icon != null && icon.getFilename() != null) { new File(icon.getFilename()).delete(); icon.flush(); } } public static void deleteIcons() { for (DcImageIcon icon : icons.values()) { if (icon != null && icon.getFilename() != null) new File(icon.getFilename()).delete(); } } public static int getCount(int module, int field, Object value) { int count = 0; ResultSet rs = null; PreparedStatement ps = null; try { DcModule m = DcModules.get(module); DcField f = field > 0 ? m.getField(field) : null; String sql; if (f == null) { sql = "select count(*) from " + m.getTableName(); } else if (f.getValueType() != DcRepository.ValueTypes._DCOBJECTCOLLECTION) { sql = "select count(*) from " + m.getTableName() + " where " + m.getField(field).getDatabaseFieldName() + (value == null ? " IS NULL " : " = ?"); } else { if (value != null) { m = DcModules.get(DcModules.getMappingModIdx(module, f.getReferenceIdx(), field)); sql = "select count(*) from " + m.getTableName() + " where " + m.getField(DcMapping._B_REFERENCED_ID).getDatabaseFieldName() + " = ?"; } else { DcModule mapping = DcModules.get(DcModules.getMappingModIdx(module, f.getReferenceIdx(), field)); sql = "select count(*) from " + m.getTableName() + " MAINTABLE where not exists (select " + mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName() + " from " + mapping.getTableName() + " where " + mapping.getField(DcMapping._A_PARENT_ID).getDatabaseFieldName() + " = MAINTABLE.ID)"; } } ps = DatabaseManager.getConnection().prepareStatement(sql); if (f != null && value != null) ps.setObject(1, value instanceof DcObject ? ((DcObject) value).getID() : value); rs = ps.executeQuery(); while (rs.next()) count = rs.getInt(1); } catch (Exception e) { logger.error(e, e); } finally { try { if (ps != null) ps.close(); if (rs != null) rs.close(); } catch (SQLException se) { logger.debug("Could not close database resources", se); } } return count; } /** * Specifically created for the web interface. * Returns the entire result set as a flat string structure. * * @param df * @param fields * @param definitions * @return */ public static List<List<String>> getWebValues(DataFilter df, int[] fields, List<WebFieldDefinition> definitions) { List<List<String>> result = new ArrayList<List<String>>(); ResultSet rs = null; DcField field; try { String sql = df.toSQLFlatStructure(fields); rs = DatabaseManager.executeSQL(sql); List<String> values; int maxLength; String ID; String value; String previousID = null; boolean concat = false; DcModule module = DcModules.get(df.getModule()); DcObject template = module.getItem(); boolean loanInfoSet = false; while(rs.next()) { values = new ArrayList<String>(); ID = rs.getString("ID"); template.setValueLowLevel(DcObject._ID, ID); // concatenate previous result set (needed for multiple references) if (ID.equals(previousID)) { values = result.get(result.size() - 1); concat = true; } else { loanInfoSet = false; } int columnIndex = 1; for (int i = 0; i < fields.length; i++) { field = module.getField(fields[i]); if (!field.isUiOnly() && field.getValueType() != DcRepository.ValueTypes._STRING && field.getValueType() != DcRepository.ValueTypes._DCOBJECTREFERENCE) { template.setValue(field.getIndex(), rs.getObject(columnIndex)); value = template.getDisplayString(field.getIndex()); columnIndex++; } else if (field.getIndex() == DcObject._SYS_AVAILABLE) { if (loanInfoSet) { template.setLoanInformation(); loanInfoSet = true; } value = ((Boolean) template.getValue(DcObject._SYS_AVAILABLE)).booleanValue() ? DcResources.getText("lblAvailable") : DcResources.getText("lblUnavailable"); } else if ( field.isLoanField()) { if (loanInfoSet) { template.setLoanInformation(); loanInfoSet = true; } value = template.getDisplayString(field.getIndex()); } else { value = rs.getString(columnIndex); columnIndex++; } if (!concat) { maxLength = fields[i] != DcObject._ID ? definitions.get(i).getMaxTextLength() : 0; value = value == null ? "" : StringUtils.concatUserFriendly(value, maxLength); values.add(value); } else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) { if (value != null) { if (!values.get(i).contains(value)) value = values.get(i) + ", " + value; else value = values.get(i); values.set(i, value); } } } if (!ID.equals(previousID)) result.add(values); previousID = ID; concat = false; } } catch (Exception e) { logger.error("An error occurred while building the String result set", e); } if (rs != null) { try { rs.close(); } catch (SQLException e) { logger.error("An error occurred while closing the result set", e); } } return result; } /** * Retrieves the children for the specified parent. * @param parentId The parent object ID. * @param childIdx The child module index. * @return The children or an empty collection. */ public static List<DcObject> getChildren(String parentID, int childIdx, int[] fields) { DataFilter df = new DataFilter(childIdx); DcModule module = DcModules.get(childIdx); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, childIdx, module.getParentReferenceFieldIndex(), Operator.EQUAL_TO, parentID)); return new SelectQuery(df, null, fields).run(); } /** * Retrieves the children for the specified parent. * @param parentId The parent object ID. * @param childIdx The child module index. * @return The children or an empty collection. */ public static Map<String, Integer> getChildrenKeys(String parentID, int childIdx) { DataFilter df = new DataFilter(childIdx); DcModule module = DcModules.get(childIdx); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, childIdx, module.getParentReferenceFieldIndex(), Operator.EQUAL_TO, parentID)); return getKeys(df); } /** * Creates a reference to the specified object. The provided value can either * be a DcObject or a display string. In the latter case the display string will * be used to retrieve the DcObject. If no object is found it will be created and * saved. The online search is used to retrieve additional information. * * @param dco The item to which the reference will be created. * @param fieldIdx The field index to set the reference on. * @param value The referenced value. * @return If an object has been created for the specified value this object will be * returned. Else null will be returned. */ public static DcObject createReference(DcObject dco, int fieldIdx, Object value) { String name = value != null ? value instanceof String ? (String) value : value.toString() : null; if (Utilities.isEmpty(name)) return null; // method 1: item is provided and exists int moduleIdx = DcModules.getReferencedModule(dco.getField(fieldIdx)).getIndex(); DcModule module = DcModules.get(moduleIdx); DcObject ref = value instanceof DcObject ? (DcObject) value : null; // check if we are dealing with an external reference if (ref == null && module.getType() == DcModule._TYPE_EXTERNALREFERENCE_MODULE) { ref = getItemByDisplayValue(moduleIdx, name); } else if (ref == null && module.getType() != DcModule._TYPE_EXTERNALREFERENCE_MODULE) { // method 2: simple external reference + display value comparison ref = DataManager.getItemByKeyword(moduleIdx, name); if (ref == null && fieldIdx != DcObject._SYS_EXTERNAL_REFERENCES) { ref = module.getItem(); boolean onlinesearch = false; if (module.getType() == DcModule._TYPE_ASSOCIATE_MODULE) { ref.setValue(DcAssociate._A_NAME, name); onlinesearch = ref.getModule().deliversOnlineService() && dco.getModule().getSettings().getBoolean(DcRepository.ModuleSettings.stOnlineSearchSubItems); } else { ref.setValue(ref.getSystemDisplayFieldIdx(), name); } if (onlinesearch) { OnlineSearchHelper osh = new OnlineSearchHelper(moduleIdx, SearchTask._ITEM_MODE_FULL); DcObject queried = osh.query(ref, name, new int[] {module.getSystemDisplayFieldIdx()}); ref = queried != null ? queried : ref; osh.clear(); } ref.setIDs(); } } if (ref != null) { if (dco.getField(fieldIdx).getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) DataManager.addMapping(dco, ref, fieldIdx); else dco.setValue(fieldIdx, ref); } return ref; } public static List<DcObject> getReferencingItems(DcObject item) { List<DcObject> items = new ArrayList<DcObject>(); DataFilter df; for (DcModule module : DcModules.getActualReferencingModules(item.getModule().getIndex())) { if ( module.getIndex() != item.getModule().getIndex() && module.getType() != DcModule._TYPE_MAPPING_MODULE && module.getType() != DcModule._TYPE_TEMPLATE_MODULE) { for (DcField field : module.getFields()) { if (field.getReferenceIdx() == item.getModule().getIndex()) { df = new DataFilter(module.getIndex()); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, module.getIndex(), field.getIndex(), Operator.EQUAL_TO, item)); try { for (DcObject dco : DataManager.get(df, module.getMinimalFields(null))) { if (!items.contains(dco)) items.add(dco); } } catch (Exception e) { e.printStackTrace(); } } } } } return items; } /** * Retrieves the tab. In case it does not yet exists the tab is created and stored * to the database. * * @param module * @param name * @param create * * @return Existing or newly created tab */ public static boolean checkTab(int module, String name) { boolean exists = true; DataFilter df = new DataFilter(DcModules._TAB); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, DcModules._TAB, Tab._D_MODULE, Operator.EQUAL_TO, Long.valueOf(module))); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, DcModules._TAB, Tab._A_NAME, Operator.EQUAL_TO, name)); Collection<String> tabs = getKeyList(df); if (tabs.size() == 0) { try { Tab tab = (Tab) DcModules.get(DcModules._TAB).getItem(); tab.setIDs(); tab.setValue(Tab._A_NAME, name); tab.setValue(Tab._D_MODULE, Long.valueOf(module)); int order = name.equals(DcResources.getText("lblInformation")) ? 1 : name.equals(DcResources.getText("lblSummary")) ? 0 : 2; tab.setValue(Tab._C_ORDER, Long.valueOf(order)); if (name.equalsIgnoreCase(DcResources.getText("lblInformation")) || name.equals(DcResources.getText("lblSummary"))) tab.setValue(Tab._B_ICON, new DcImageIcon(DataCrow.installationDir + "icons" + File.separator + "information.png")); else if (name.equalsIgnoreCase(DcResources.getText("lblTechnicalInfo"))) tab.setValue(Tab._B_ICON, new DcImageIcon(DataCrow.installationDir + "icons" + File.separator + "informationtechnical.png")); tab.saveNew(false); } catch (Exception e) { logger.error(e, e); exists = false; } } return exists; } public static DcObject getTab(int module, String name) { DataFilter df = new DataFilter(DcModules._TAB); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, DcModules._TAB, Tab._D_MODULE, Operator.EQUAL_TO, Long.valueOf(module))); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, DcModules._TAB, Tab._A_NAME, Operator.EQUAL_TO, name)); List<DcObject> tabs = get(df); return tabs != null && tabs.size() > 0 ? tabs.get(0) : null; } public static List<DcObject> getTabs(int module) { DataFilter df = new DataFilter(DcModules._TAB); df.addEntry(new DataFilterEntry(DataFilterEntry._AND, DcModules._TAB, Tab._D_MODULE, Operator.EQUAL_TO, Long.valueOf(module))); return get(df); } /** * Adds a referenced item to the specified parent object. * @param parent The item to which the reference will be added. * @param child The to be referenced item. * @param fieldIdx The field holding the reference. */ @SuppressWarnings("unchecked") public static void addMapping(DcObject parent, DcObject child, int fieldIdx) { DcMapping mapping = (DcMapping) DcModules.get(DcModules.getMappingModIdx(parent.getModule().getIndex(), child.getModule().getIndex(), fieldIdx)).getItem(); mapping.setValue(DcMapping._A_PARENT_ID, parent.getID()); mapping.setValue(DcMapping._B_REFERENCED_ID, child.getID()); mapping.setReference(child); Collection<DcMapping> mappings = (Collection<DcMapping>) parent.getValue(fieldIdx); mappings = mappings == null ? new ArrayList<DcMapping>() : mappings; // check if a mapping exists already for (DcMapping m : mappings) { if (m.getReferencedID().equals(child.getID()) || m.toString().equals(child.toString())) return; } mappings.add(mapping); parent.setValue(fieldIdx, mappings); } /** * Retrieves all the loans (actual and historic). * @param parentID The item ID for which the loans are retrieved. * @return A collection holding loans or an empty collection. */ public static Collection<Loan> getLoans(String parentID) { DataFilter df = new DataFilter(DcModules._LOAN); df.addEntry(new DataFilterEntry(DcModules._LOAN, Loan._D_OBJECTID, Operator.EQUAL_TO, parentID)); Collection<DcObject> items = get(df, DcModules.get(DcModules._LOAN).getMinimalFields(null)); Collection<Loan> loans = new ArrayList<Loan>(); for (DcObject item : items) loans.add((Loan) item); return loans; } /** * Retrieves the actual loan. * @param parentID The item ID for which the loan is retrieved. */ public static Loan getCurrentLoan(String parentID) { DataFilter df = new DataFilter(DcModules._LOAN); df.addEntry(new DataFilterEntry(DcModules._LOAN, Loan._B_ENDDATE, Operator.IS_EMPTY, null)); df.addEntry(new DataFilterEntry(DcModules._LOAN, Loan._D_OBJECTID, Operator.EQUAL_TO, parentID)); List<DcObject> items = get(df); return items.size() > 0 ? (Loan) items.get(0) : new Loan(); } @SuppressWarnings("resource") public static DcObject getObjectByExternalID(int moduleIdx, String type, String externalID) { DcModule module = DcModules.get(moduleIdx); if (module.getField(DcObject._SYS_EXTERNAL_REFERENCES) == null) return null; DcModule extRefModule = DcModules.get(moduleIdx + DcModules._EXTERNALREFERENCE); String sql = "SELECT ID FROM " + extRefModule.getTableName() + " WHERE " + "UPPER(" + extRefModule.getField(ExternalReference._EXTERNAL_ID).getDatabaseFieldName() + ") = UPPER(?) AND " + "UPPER(" + extRefModule.getField(ExternalReference._EXTERNAL_ID_TYPE).getDatabaseFieldName() + ") = UPPER(?)"; Connection conn = DatabaseManager.getConnection(); DcObject result = null; PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement(sql); ps.setString(1, externalID); ps.setString(2, type); rs = ps.executeQuery(); String referenceID; DcModule mappingMod; int idx; PreparedStatement ps2 = null; List<DcObject> items; while (rs.next()) { try { referenceID = rs.getString(1); idx = DcModules.getMappingModIdx(extRefModule.getIndex() - DcModules._EXTERNALREFERENCE, extRefModule.getIndex(), DcObject._SYS_EXTERNAL_REFERENCES); mappingMod = DcModules.get(idx); sql = "SELECT * FROM " + DcModules.get(moduleIdx) + " WHERE ID IN (" + "SELECT OBJECTID FROM " + mappingMod.getTableName() + " WHERE " + mappingMod.getField(DcMapping._B_REFERENCED_ID).getDatabaseFieldName() + " = ?)"; ps2 = conn.prepareStatement(sql); ps2.setString(1, referenceID); items = WorkFlow.getInstance().convert(ps2.executeQuery(), new int[] {DcObject._ID}); result = items.size() > 0 ? items.get(0) : null; if (result != null) break; } finally { ps2.close(); } } } catch (SQLException se) { logger.error(se, se); } finally { try { if (ps != null) ps.close(); if (rs != null) rs.close(); } catch (Exception e) { logger.debug("Failed to release database resources", e); } } return result; } /** * Retrieves a matching item based on the 'isKey' setting. * @return Returns one of the matching item or NULL if none found */ public static DcObject getItemByUniqueFields(DcObject o) { DcObject result = null; if (o.hasPrimaryKey() && !o.getModule().isChildModule()) { boolean hasUniqueFields = false; DcObject dco = o.getModule().getItem(); for (DcFieldDefinition def : o.getModule().getFieldDefinitions().getDefinitions()) { if (def.isUnique()) { dco.setValue(def.getIndex(), o.getValue(def.getIndex())); hasUniqueFields = true; } } if (hasUniqueFields) { DataFilter df = new DataFilter(dco); List<String> keys = DataManager.getKeyList(df); for (String key : keys) { result = o.isNew() || !key.equals(o.getID()) ? DataManager.getItem(dco.getModule().getIndex(), key) : null; } } } return result; } public static DcObject getItemByKeyword(int module, String reference) { // Establish the names on which we will check if the item already exists. // Skip multiple checks for the external references; this will results in errors. String[] names = new String[(reference.indexOf(" ") > -1 && reference.indexOf(", ") == -1 && DcModules.get(module).getType() != DcModule._TYPE_EXTERNALREFERENCE_MODULE ? 3 : 1)]; names[0] = reference; if (names.length > 1) { names[1] = reference.replaceFirst(" ", ", "); names[2] = reference.substring(reference.indexOf(" ") + 1) + ", " + reference.substring(0, reference.indexOf(" ")); } DcObject dco = null; for (String name : names) { dco = getObjectByExternalID(module, DcRepository.ExternalReferences._PDCR, name); if (dco != null) break; } if (dco == null) { for (String name : names) { dco = getItemByDisplayValue(module, name); if (dco != null) break; } } return dco; } /** * Retrieves an item based on its display value. * @param module * @param s The display value. * @return Either the item or null. */ private static DcObject getItemByDisplayValue(int moduleIdx, String s) { DcModule module = DcModules.get(moduleIdx); Collection<String> values = new ArrayList<String>(); values.add(s); try { String columns = module.getIndex() + " AS MODULEIDX"; for (DcField field : module.getFields()) { if (!field.isUiOnly()) columns += "," + field.getDatabaseFieldName(); } String query = "SELECT " + columns + " FROM " + module.getTableName() + " WHERE " + "RTRIM(LTRIM(UPPER(" + module.getField(module.getSystemDisplayFieldIdx()).getDatabaseFieldName() + "))) = UPPER(?)"; if (module.getType() == DcModule._TYPE_ASSOCIATE_MODULE) { query += " OR RTRIM(LTRIM(UPPER(" + module.getField(DcAssociate._A_NAME).getDatabaseFieldName() + "))) LIKE ?"; String firstname = Utilities.getFirstName(s); String lastname = Utilities.getLastName(s); values.add("%" + Utilities.getName(firstname, lastname) + "%"); } if (module.getType() == DcModule._TYPE_PROPERTY_MODULE) { query += " OR RTRIM(LTRIM(UPPER(" + module.getField(DcProperty._C_ALTERNATIVE_NAMES).getDatabaseFieldName() + "))) LIKE ?"; values.add(";%" + s + "%;"); } if (module.getType() == DcModule._TYPE_EXTERNALREFERENCE_MODULE) { // external references have a display value that consist of the type and the key. query += " OR (RTRIM(LTRIM(UPPER(" + module.getField(ExternalReference._EXTERNAL_ID_TYPE).getDatabaseFieldName() + "))) = ? " + " AND RTRIM(LTRIM(UPPER(" + module.getField(ExternalReference._EXTERNAL_ID).getDatabaseFieldName() + "))) = ?)"; values.add(s.indexOf(":") > -1 ?s.substring(0, s.indexOf(":")) : s); values.add(s.indexOf(":") > -1 ? s.substring(s.indexOf(":") + 2) : s); } PreparedStatement ps = DatabaseManager.getConnection().prepareStatement(query); int idx = 1; for (String value : values) ps.setString(idx++, value.toUpperCase()); List<DcObject> items = WorkFlow.getInstance().convert(ps.executeQuery(), new int[] {DcObject._ID}); ps.close(); return items.size() > 0 ? items.get(0) : null; } catch (SQLException e) { logger.error(e, e); } return null; } public static DcObject getItem(int module, String ID) { return getItem(module, ID, null); } /** * Retrieve the item based on its ID. * @param module * @param ID * @return null or the item if found. */ public static DcObject getItem(int module, String ID, int[] fields) { DataFilter df = new DataFilter(module); df.addEntry(new DataFilterEntry(module, DcObject._ID, Operator.EQUAL_TO, ID)); List<DcObject> items = get(df, fields); DcObject item = items != null && items.size() > 0 ? items.get(0) : null; if (item != null) item.markAsUnchanged(); return item; } /** * Retrieve all referenced items for the given parent ID. * @param module * @param parentId */ public static List<DcObject> getReferences(int modIdx, String parentID, boolean full) { DataFilter df = new DataFilter(modIdx); df.addEntry(new DataFilterEntry(modIdx, DcMapping._A_PARENT_ID, Operator.EQUAL_TO, parentID)); return get(df, full ? null : DcModules.get(modIdx).getMinimalFields(null)); } /** * Retrieves all pictures for the given parent ID. * @param parentId * @return Either the pictures or an empty collection. */ public static Collection<DcObject> getPictures(String parentID) { DataFilter df = new DataFilter(DcModules._PICTURE); df.addEntry(new DataFilterEntry(DcModules._PICTURE, Picture._A_OBJECTID, Operator.EQUAL_TO, parentID)); return new SelectQuery(df, null, null).run(); } public static List<String> getKeyList(DataFilter filter) { return new ArrayList<String>(DatabaseManager.getKeys(filter).keySet()); } public static Map<String, Integer> getKeys(DataFilter filter) { return DatabaseManager.getKeys(filter); } /** * Retrieve items using the specified data filter. * @see DataFilter * @param filter * @param fields */ public static List<DcSimpleValue> getSimpleValues(int module, boolean icons) { DcModule m = DcModules.get(module); boolean useIcons = icons && m.getIconField() != null; String sql = "select ID, " + m.getField(m.getDisplayFieldIdx()).getDatabaseFieldName() + (useIcons ? ", " + m.getIconField().getDatabaseFieldName() : " ") + " from " + m.getTableName() + " order by 2"; List<DcSimpleValue> values = new ArrayList<DcSimpleValue>(); ResultSet rs = null; try { rs = DatabaseManager.executeSQL(sql); DcImageIcon icon; DcSimpleValue sv; String s; while (rs.next()) { sv = new DcSimpleValue(rs.getString(1), rs.getString(2)); if (useIcons) { s = rs.getString(3); if (!Utilities.isEmpty(s)) { icon = Utilities.base64ToImage(s); sv.setIcon(icon); } } values.add(sv); } } catch (SQLException se) { DcSwingUtilities.displayErrorMessage(se.getMessage()); logger.error(se, se); } finally { try { if (rs != null) rs.close(); } catch (SQLException e) {} } return values; } /** * Retrieve items using the specified data filter. * @see DataFilter * @param filter * @param fields */ public static List<DcObject> get(DataFilter filter, int[] fields) { return new SelectQuery(filter, null, fields).run(); } /** * Overloaded * @see #get(DataFilter, int[]) */ public static List<DcObject> get(int modIdx, int[] fields) { return get(new DataFilter(modIdx), fields); } /** * Overloaded * @see #get(DataFilter, int[]) */ public static List<DcObject> get(DataFilter filter) { return get(filter, null); } }
package com.my.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * @author:ljn * @Description: * @Date:2021/02/09 19:28 */ @RestController public class HelleConfroller { private static final Logger log = LoggerFactory.getLogger(HelleConfroller.class); @GetMapping("hello") public String hello(){ log.info("Hello !"); return "Hello ?"; } }
package org.asynchttpclient.proxy; public enum ProxyType { HTTP, SOCKS_V4 { @Override public boolean isSocks() { return true; } }, SOCKS_V5 { @Override public boolean isSocks() { return true; } }; public boolean isSocks() { return false; } }
package gui; import dao.ClienteDAO; import java.util.ArrayList; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import models.Cliente; public class MenuPrincipal extends javax.swing.JFrame { ArrayList<Cliente> todosClientes; ArrayList<Cliente> clientesNaTabela; Cliente clienteSelecionado; public MenuPrincipal() { initComponents(); this.todosClientes = ClienteDAO.selectTodosClientes(); updateTabelaComBanco(); tabelaClientes.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { int row = tabelaClientes.rowAtPoint(evt.getPoint()); if (row >= 0) { selecionarCliente(clientesNaTabela.get(row)); } } }); } public void updateTabelaComBanco() { this.todosClientes = ClienteDAO.selectTodosClientes(); clientesNaTabela = todosClientes; DefaultTableModel tableModel = (DefaultTableModel) tabelaClientes.getModel(); tableModel.setRowCount(0); clientesNaTabela.forEach((cliente) -> { tableModel.addRow(cliente.getObjectArray()); }); } public void preencherTabela(){ DefaultTableModel tableModel = (DefaultTableModel) tabelaClientes.getModel(); tableModel.setRowCount(0); clientesNaTabela.forEach((cliente) -> { tableModel.addRow(cliente.getObjectArray()); }); } private void selecionarCliente(Cliente cliente) { clienteSelecionado = cliente; botaoDeselecionarCliente.setEnabled(true); labelClienteSelecionado.setText("<html>" + cliente.getNome() + "</html>"); botaoNovaEntrega.setEnabled(true); botaoMaisInformacoes.setEnabled(true); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroupBuscar = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabelaClientes = new javax.swing.JTable(); idRadioButton = new javax.swing.JRadioButton(); nomeRadioButton = new javax.swing.JRadioButton(); campoBusca = new javax.swing.JTextField(); botaoBuscar = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); botaoNovoCliente = new javax.swing.JButton(); botaoMaisInformacoes = new javax.swing.JButton(); botaoNovaEntrega = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); labelClienteSelecionado = new javax.swing.JLabel(); botaoDeselecionarCliente = new javax.swing.JButton(); botaoLimparBusca = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Entregas"); setIconImage(new javax.swing.ImageIcon(getClass().getResource("/icons/motorcycle-48.png")).getImage()); setResizable(false); tabelaClientes.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N tabelaClientes.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Nome" } ) { boolean[] canEdit = new boolean [] { false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(tabelaClientes); if (tabelaClientes.getColumnModel().getColumnCount() > 0) { tabelaClientes.getColumnModel().getColumn(0).setPreferredWidth(50); tabelaClientes.getColumnModel().getColumn(1).setPreferredWidth(610); } buttonGroupBuscar.add(idRadioButton); idRadioButton.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N idRadioButton.setText("ID"); buttonGroupBuscar.add(nomeRadioButton); nomeRadioButton.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N nomeRadioButton.setSelected(true); nomeRadioButton.setText("Nome"); campoBusca.setFont(new java.awt.Font("Noto Sans", 0, 14)); // NOI18N botaoBuscar.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N botaoBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/search.png"))); // NOI18N botaoBuscar.setText("Buscar"); botaoBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoBuscarActionPerformed(evt); } }); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); botaoNovoCliente.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N botaoNovoCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/new-customer.png"))); // NOI18N botaoNovoCliente.setText("Novo Cliente"); botaoNovoCliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoNovoClienteActionPerformed(evt); } }); botaoMaisInformacoes.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N botaoMaisInformacoes.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/more-info.png"))); // NOI18N botaoMaisInformacoes.setText("Mais Informações"); botaoMaisInformacoes.setEnabled(false); botaoMaisInformacoes.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoMaisInformacoesActionPerformed(evt); } }); botaoNovaEntrega.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N botaoNovaEntrega.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/delivery-32.png"))); // NOI18N botaoNovaEntrega.setText("Nova Entrega"); botaoNovaEntrega.setEnabled(false); botaoNovaEntrega.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoNovaEntregaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(botaoNovoCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoMaisInformacoes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoNovaEntrega, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoNovaEntrega) .addGap(18, 18, 18) .addComponent(botaoMaisInformacoes) .addGap(18, 18, 18) .addComponent(botaoNovoCliente) .addContainerGap()) ); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel1.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/customer-red.png"))); // NOI18N jLabel1.setText("Cliente selecionado:"); labelClienteSelecionado.setFont(new java.awt.Font("Noto Sans", 1, 18)); // NOI18N labelClienteSelecionado.setText(" "); botaoDeselecionarCliente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/close-cross.png"))); // NOI18N botaoDeselecionarCliente.setEnabled(false); botaoDeselecionarCliente.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoDeselecionarClienteActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE) .addComponent(botaoDeselecionarCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(labelClienteSelecionado, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(botaoDeselecionarCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(labelClienteSelecionado) .addContainerGap()) ); botaoLimparBusca.setFont(new java.awt.Font("Noto Sans", 1, 14)); // NOI18N botaoLimparBusca.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/eraser.png"))); // NOI18N botaoLimparBusca.setText("Limpar"); botaoLimparBusca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { botaoLimparBuscaActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 600, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(nomeRadioButton) .addGap(18, 18, 18) .addComponent(idRadioButton) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(campoBusca) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addComponent(botaoLimparBusca) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(botaoBuscar)) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(idRadioButton) .addComponent(nomeRadioButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(campoBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(botaoBuscar) .addComponent(botaoLimparBusca)) .addGap(51, 51, 51) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 95, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void botaoNovoClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovoClienteActionPerformed new NovoCliente(this).setVisible(true); }//GEN-LAST:event_botaoNovoClienteActionPerformed private void botaoNovaEntregaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoNovaEntregaActionPerformed new NovaEntrega(clienteSelecionado).setVisible(true); }//GEN-LAST:event_botaoNovaEntregaActionPerformed private void botaoDeselecionarClienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoDeselecionarClienteActionPerformed clienteSelecionado = null; botaoDeselecionarCliente.setEnabled(false); labelClienteSelecionado.setText(" "); botaoNovaEntrega.setEnabled(false); botaoMaisInformacoes.setEnabled(false); tabelaClientes.getSelectionModel().clearSelection(); }//GEN-LAST:event_botaoDeselecionarClienteActionPerformed private void botaoMaisInformacoesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoMaisInformacoesActionPerformed new MaisInformacoes(clienteSelecionado, this).setVisible(true); }//GEN-LAST:event_botaoMaisInformacoesActionPerformed private void botaoBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoBuscarActionPerformed String searchParam = campoBusca.getText(); if (!searchParam.isEmpty()) { if (idRadioButton.isSelected()) { try { int idBusca = Integer.parseInt(searchParam); clientesNaTabela = new ArrayList<>(); boolean flag = false; for (Cliente c : todosClientes) { if (c.getIdCliente() == idBusca) { clientesNaTabela.add(c); flag = true; break; } } preencherTabela(); if (!flag) { JOptionPane.showMessageDialog(null, "Não foi possível achar um resultado", "Atenção", JOptionPane.INFORMATION_MESSAGE); } } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null, "Favor inserir somente números no campo de busca por ID", "Atenção", JOptionPane.WARNING_MESSAGE); } } else { searchParam = searchParam.toUpperCase(); clientesNaTabela = new ArrayList<>(); boolean flag = false; for (Cliente c : todosClientes) { if (c.getNome().contains(searchParam)) { clientesNaTabela.add(c); flag = true; } } preencherTabela(); if (!flag) { JOptionPane.showMessageDialog(null, "Não foi possível achar um resultado", "Atenção", JOptionPane.INFORMATION_MESSAGE); } } } else { clientesNaTabela = todosClientes; preencherTabela(); } botaoDeselecionarCliente.doClick(); }//GEN-LAST:event_botaoBuscarActionPerformed private void botaoLimparBuscaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoLimparBuscaActionPerformed campoBusca.setText(""); clientesNaTabela = todosClientes; preencherTabela(); }//GEN-LAST:event_botaoLimparBuscaActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton botaoBuscar; private javax.swing.JButton botaoDeselecionarCliente; private javax.swing.JButton botaoLimparBusca; private javax.swing.JButton botaoMaisInformacoes; private javax.swing.JButton botaoNovaEntrega; private javax.swing.JButton botaoNovoCliente; private javax.swing.ButtonGroup buttonGroupBuscar; private javax.swing.JTextField campoBusca; private javax.swing.JRadioButton idRadioButton; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel labelClienteSelecionado; private javax.swing.JRadioButton nomeRadioButton; private javax.swing.JTable tabelaClientes; // End of variables declaration//GEN-END:variables }
/* * Copyright (C) 2018 Instituto Nacional de Telecomunicações * * All rights are reserved. Reproduction in whole or part is * prohibited without the written consent of the copyright owner. * */ package inatel.br.nfccontrol.di.module; import android.content.Context; import android.content.SharedPreferences; import dagger.Module; import dagger.Provides; import inatel.br.nfccontrol.R; import inatel.br.nfccontrol.di.preference.BooleanPreference; import inatel.br.nfccontrol.di.preference.StringPreference; import inatel.br.nfccontrol.di.qualifier.ApiTokenPreference; import inatel.br.nfccontrol.di.qualifier.FirstTimeOnAppPreference; import inatel.br.nfccontrol.di.qualifier.IsAuthenticatedPreference; import inatel.br.nfccontrol.di.qualifier.RefreshTokenPreference; import inatel.br.nfccontrol.di.qualifier.SecretKeyPreference; import javax.inject.Singleton; /** * {@link Module} to provide all application {@link SharedPreferences}. * * @author Everton Takashi Nishiyama <evertontn@inatel.br> * @since 23/01/2018. */ @Module(includes = DataModule.class) public class SharedPreferenceModule { @Provides @Singleton @SecretKeyPreference StringPreference provideSecretKeyPreference(Context context, SharedPreferences prefs) { final String key = context.getString(R.string.shared_preferences_secret_key); return new StringPreference(prefs, key, null); } @Provides @Singleton @ApiTokenPreference StringPreference provideApiTokenPreference(Context context, SharedPreferences prefs) { final String key = context.getString(R.string.shared_preferences_api_token); return new StringPreference(prefs, key, null); } @Provides @Singleton @RefreshTokenPreference StringPreference provideRefreshTokenPreference(Context context, SharedPreferences prefs) { final String key = context.getString(R.string.shared_preferences_refresh_token); return new StringPreference(prefs, key, null); } @Provides @Singleton @IsAuthenticatedPreference BooleanPreference provideIsAuthenticatedPreference(Context context, SharedPreferences prefs) { final String key = context.getString(R.string.shared_preferences_is_authenticated); return new BooleanPreference(prefs, key, false); } @Provides @Singleton @FirstTimeOnAppPreference BooleanPreference provideFirstTimeOnAppPreference(Context context, SharedPreferences prefs) { final String key = context.getString(R.string.shared_preferences_agreed_with_terms_of_use); return new BooleanPreference(prefs, key, true); } }
/* * Copyright 2017 Goldman Sachs. * 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.gs.tablasco; import com.gs.tablasco.files.MavenStyleDirectoryStrategy; import org.junit.Rule; import org.junit.Test; public class MavenStyleDirectoryStrategyTest { @Rule public final TableVerifier tableVerifier = new TableVerifier() .withFilePerClass() .withDirectoryStrategy( new MavenStyleDirectoryStrategy() .withAnchorFile("pom.xml") .withExpectedSubDir("maven_input") .withOutputSubDir("maven_output")); @Test public void testMavenStyleDirectoryStrategy() { this.tableVerifier.verify("maven", new TestTable("h1", "h2").withRow("r11", "r12").withRow("r21", "r22")); } }
package br.com.zup.treinocasadocodigo.controllers; import br.com.zup.treinocasadocodigo.entities.pais.Pais; import br.com.zup.treinocasadocodigo.entities.pais.PaisNovoRequest; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.*; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.transaction.Transactional; import javax.validation.Valid; /** * Contagem de carga intrínseca da classe: 2 */ @RestController @RequestMapping("/paises") public class PaisController { @PersistenceContext private EntityManager manager; @PostMapping @Transactional @ResponseStatus(HttpStatus.CREATED) //1 public String cadastroPais(@RequestBody @Valid PaisNovoRequest novoPais) { //1 Pais pais = novoPais.toModel(); manager.persist(pais); return pais.toString(); } }
package core.order; import core.AppConfig; import core.member.Grade; import core.member.Member; import core.member.MemberService; import core.member.MemberServiceImpl; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; public class OrderServiceTest { MemberService memberService; OrderService orderService; @BeforeEach public void beforeEach() { AppConfig appConfig = new AppConfig(); memberService = appConfig.memberService(); orderService = appConfig.orderService(); } @Test public void createOrder() throws Exception { // given // 깨알상식 : primitive long의 경우 null이 안들어감. // 단위테스트 만드는게 정말 중요하다 ! (SpringBootTest 없이 순수 자바 코드로 ㅇㅇ) Long memberId = 1L; Member member = new Member(memberId, "memberA", Grade.VIP); memberService.join(member); // when // then Order order = orderService.createOrder(memberId, "itemA", 10000); assertThat(order.getDiscountPrice()).isEqualTo(1000); } }
/* * 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.davivienda.sara.bean.page.diarioelectronico; import com.davivienda.sara.dto.DiarioElectronicoTransaccionDTO; import com.davivienda.sara.entitys.Cajero; import com.davivienda.sara.entitys.DiarioElectronico; import com.davivienda.sara.base.ComponenteAjaxObjectContextWeb; import com.davivienda.sara.bean.BaseBean; import com.davivienda.sara.bean.InitBean; import com.davivienda.sara.dto.CajerosSinTransmisionDTO; import com.davivienda.sara.dto.HistoricoCargueDTO; import com.davivienda.sara.dto.NumeroTransaccionesDTO; import com.davivienda.sara.dto.TransaccionDTO; import com.davivienda.sara.entitys.EdcCargue; import com.davivienda.sara.entitys.TransaccionTemp; import com.davivienda.sara.entitys.transaccion.CantidadTransaccionesBean; import com.davivienda.sara.entitys.transaccion.Transaccion; import com.davivienda.sara.estadisticas.EstadisticasGeneralesSessionLocal; import com.davivienda.sara.tablas.cajero.session.CajeroSessionLocal; import com.davivienda.sara.tablas.diarioelectronico.session.DiarioElectronicoSessionLocal; import com.davivienda.sara.tablas.edccargue.session.EdcCargueSessionLocal; import com.davivienda.sara.tablas.transaccion.session.TransaccionSessionLocal; import com.davivienda.sara.tablas.transacciontemp.session.TransaccionTempSessionLocal; import com.davivienda.utilidades.Constantes; import com.davivienda.utilidades.archivoxls.ArchivoXLS; import com.davivienda.utilidades.archivoxls.Celda; import com.davivienda.utilidades.archivoxls.ProcesadorArchivoXLS; import com.davivienda.utilidades.archivoxls.Registro; import com.davivienda.utilidades.archivoxls.TipoDatoCelda; import com.davivienda.utilidades.conversion.Fecha; import com.davivienda.utilidades.conversion.FormatoFecha; import com.davivienda.utilidades.edc.Edc; import java.io.IOException; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.PostConstruct; import javax.ejb.EJB; import javax.ejb.EJBException; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import javax.faces.context.FacesContext; import javax.faces.model.SelectItem; /** * * @author jmcastel */ @ManagedBean(name = "transaccionBean") @ViewScoped public class TransaccionBean extends BaseBean implements Serializable { @EJB DiarioElectronicoSessionLocal sessionDiarioElectronico; @EJB TransaccionSessionLocal sessionTransaccion; @EJB TransaccionTempSessionLocal transaccionTempSession; @EJB EdcCargueSessionLocal sessionHistoricoCargue; @EJB EstadisticasGeneralesSessionLocal sessionNumTransacciones; @EJB CajeroSessionLocal sessionSinTransmitir; public ComponenteAjaxObjectContextWeb objectContext; private String codigoCajero; private String fechaInicial; private String fechaFinal; private String horaInicial; private String horaFinal; private String talon; private String referencia; private String cuenta; private String tarjeta; public Date fechaInicialReporte = null; private boolean mostrarPanelGeneral; private boolean mostrarDiarioElect; private boolean mostrarTransacciones; private boolean mostrarHistorial; private boolean mostrarNumTrasaccioes; private boolean mostrarCajSinTransmision; private List<SelectItem> listaHora; private List<TransaccionDTO> transacciones; private List<HistoricoCargueDTO> historicosCargue; private List<NumeroTransaccionesDTO> numTransacciones; private List<CajerosSinTransmisionDTO> cajerosSinTransamision; private Collection<TransaccionTemp> itemsDTemp = null; private Logger loggerApp; private Collection<DiarioElectronicoTransaccionDTO> itemsFormateados = null; @PostConstruct public void TransaccionBean() { objectContext = cargarComponenteAjaxObjectContext(); listaHora = new ArrayList<SelectItem>(); this.transacciones = new ArrayList<TransaccionDTO>(); this.historicosCargue = new ArrayList<HistoricoCargueDTO>(); this.numTransacciones = new ArrayList<NumeroTransaccionesDTO>(); this.cajerosSinTransamision = new ArrayList<CajerosSinTransmisionDTO>(); dataInicial(); loggerApp = objectContext.getConfigApp().loggerApp; } public void dataInicial() { this.fechaInicial = ""; this.fechaFinal = ""; this.horaInicial = "00:00:00"; this.horaFinal = "23:59:59"; this.codigoCajero = "0"; this.cuenta = ""; this.tarjeta = ""; this.talon = ""; this.referencia = ""; this.listaHora = cargarListaHora(); this.setMostrarPanelGeneral(true); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(false); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(false); } public String generarDiarioElectronico() { loggerApp.info("TransaccionBean-generarDiarioElectronico"); String nombreArchivo = ""; Calendar clFechaInicial; boolean registrosExiste = false; Collection<DiarioElectronico> items = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { Date fechaInicial = null; Integer codigoCajero = 0; try { fechaInicial = formatter.parse(this.fechaInicial); } catch (IllegalArgumentException | ParseException ex) { //fechaInicial = com.davivienda.utilidades.conversion.Fecha.getDateAyer(); abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return null; } clFechaInicial = com.davivienda.utilidades.conversion.Fecha.getCalendar(fechaInicial); codigoCajero = Integer.parseInt(this.codigoCajero); if (codigoCajero == 0) { abrirModal("SARA", Constantes.MSJ_SELECCIONAR_CAJERO, null); return null; } try { loggerApp.info("TransaccionBean-fechaInicial " + fechaInicial + " codigoCajero: " + codigoCajero); if ((Fecha.getFechaInicioDia(clFechaInicial).equals( Fecha.getFechaInicioDia(Fecha.getCalendarAyer())))) { nombreArchivo = Edc.obtenerNombreArchivo(codigoCajero, Fecha.getCalendarHoy()); items = sessionDiarioElectronico.getDiarioElectronicoDia(codigoCajero, Fecha.getCalendarHoy(), nombreArchivo); } else { items = sessionDiarioElectronico.getDiarioElectronico(codigoCajero, fechaInicial); } if (null != items && !items.isEmpty()) { registrosExiste = true; } } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { //abrirModal("SARA", "Error Consultando Entitys", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { //abrirModal("SARA", "Error consultando Entitys", null); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("NoResultException")) { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, null); return null; } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //abrirModal("SARA", "Error consultando Entitys", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (registrosExiste) { this.setItemsFormateados(setColeccionRegistroDiarioElectronico(items)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(true); this.setMostrarTransacciones(false); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(false); } else { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, null); return null; } return ""; } public void generarTransacciones() { loggerApp.info("TransaccionBean-generarTransacciones"); Collection<Transaccion> items = null; this.transacciones = new ArrayList<TransaccionDTO>(0); items = generarTransaccionesData(); if (null != items && !items.isEmpty()) { loggerApp.info("TransaccionBean generarTransacciones items: " + items.size()); this.getTransacciones().addAll(convertItemsTransaccion(items)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(true); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(false); } else if (itemsDTemp != null) { loggerApp.info("TransaccionBean generarTransacciones itemsDTemp: " + this.itemsDTemp.size()); this.getTransacciones().addAll(convertItemsTransaccionTemp(itemsDTemp)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(true); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(false); } else { //abrirModal("SARA", "No hay registros para que cumplan con los criterios de la consulta",null); } } public Collection<Transaccion> generarTransaccionesData() { String error = ""; Collection<Transaccion> itemsTransaccion = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { Date fechaInicial = null; Date fechaFinal = null; Integer codigoCajero = 0; Integer numeroTransaccion = 0; Calendar clFechaInicial = null; Map<String, Object> criterios = new HashMap<String, Object>(); String strTmp = null; try { codigoCajero = Integer.parseInt(this.codigoCajero); } catch (IllegalArgumentException ex) { codigoCajero = 0; } try { fechaInicial = formatter.parse(this.fechaInicial); clFechaInicial = com.davivienda.utilidades.conversion.Fecha.getCalendar(fechaInicial); } catch (IllegalArgumentException ex) { abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return null; } catch (ParseException ex) { abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); Logger.getLogger(TransaccionBean.class.getName()).log(Level.SEVERE, null, ex); return null; } try { fechaFinal = formatter.parse(this.fechaFinal); } catch (IllegalArgumentException ex) { fechaFinal = fechaInicial; } catch (ParseException ex) { fechaFinal = fechaInicial; } loggerApp.info("TransaccionBean generarTransaccionesData - fechaInicial " + fechaInicial + " fechaFinal " + fechaFinal + " codigoCajero: " + codigoCajero); try { numeroTransaccion = Integer.parseInt(this.getTalon()); } catch (IllegalArgumentException ex) { numeroTransaccion = null; } try { strTmp = this.referencia; criterios.put("referencia", strTmp); } catch (IllegalArgumentException ex) { strTmp = ""; } try { strTmp = this.cuenta; criterios.put("productoOrigen", strTmp); } catch (IllegalArgumentException ex) { strTmp = ""; } try { strTmp = this.tarjeta; criterios.put("tarjeta", strTmp); } catch (IllegalArgumentException ex) { strTmp = ""; } try { itemsTransaccion = sessionTransaccion.getColeccionTransaccion(codigoCajero, fechaInicial, fechaFinal, numeroTransaccion, criterios); if (itemsTransaccion.isEmpty() && (Fecha.getFechaInicioDia(clFechaInicial).equals(Fecha.getFechaInicioDia(Fecha.getCalendarAyer())))) { setItemsDTemp(transaccionTempSession.getColeccionTransaccionTemp(codigoCajero, fechaInicial, fechaFinal, numeroTransaccion, criterios)); } if (itemsTransaccion.isEmpty() && null == itemsDTemp) { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, null); return null; } } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { //abrirModal("SARA", "Error consultando Entitys", null); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { //abrirModal("SARA", "Error Consultando Entitys", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("NoResultException")) { //abrirModal("SARA", "Registro no existe", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //abrirModal("SARA", "Error Consultando Entitys", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); //abrirModal("SARA", "Error Consultando Entitys", ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } return itemsTransaccion; } public void generarHistoricoCargue() { loggerApp.info("TransaccionBean-generarHistoricoCargue"); Collection<EdcCargue> items = null; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); this.historicosCargue = new ArrayList<HistoricoCargueDTO>(0); try { Date fechaInicial = null; Date fechaFinal = null; try { fechaInicial = formatter.parse(this.fechaInicial); } catch (IllegalArgumentException ex) { //fechaInicial = com.davivienda.utilidades.conversion.Fecha.getDateAyer(); abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return; } catch (ParseException ex) { //fechaInicial = com.davivienda.utilidades.conversion.Fecha.getDateAyer(); abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return; } try { fechaFinal = formatter.parse(this.fechaFinal); } catch (IllegalArgumentException ex) { fechaFinal = fechaInicial; } catch (ParseException ex) { fechaFinal = fechaInicial; } fechaFinal = com.davivienda.utilidades.conversion.Fecha.getFechaFinDia(fechaInicial); try { // Consulta los registros según los parámetros tomados del request items = sessionHistoricoCargue.getEDCCarguePorFecha(fechaInicial, fechaFinal); loggerApp.info("generarHistoricoCargue items " + items.size()); } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } if (ex.getLocalizedMessage().contains("NoResultException")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } if (items == null || items.isEmpty()) { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, null); return; } else { this.getHistoricosCargue().addAll(convertItemsHistorico(items)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(false); this.setMostrarHistorial(true); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(false); } loggerApp.info("generarHistoricoCargue Fin"); } public void generarNumTrasacciones() { loggerApp.info("TransaccionBean-generarNumTrasacciones"); String error = ""; String respuesta = ""; SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); Collection<CantidadTransaccionesBean> itemsNumeroTransacciones = null; try { Date fechaInicial = null; Date fechaFinal = null; Integer codigoCajero = 0; codigoCajero = Integer.parseInt(this.codigoCajero); if (codigoCajero == 0) { abrirModal("SARA", Constantes.MSJ_SELECCIONAR_CAJERO, null); return; } try { fechaInicial = this.getAtributoFechaHoraInicial().getTime(); } catch (IllegalArgumentException ex) { //fechaInicial = com.davivienda.utilidades.conversion.Fecha.getDateAyer(); abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return; } if(null == this.fechaFinal || this.fechaFinal.isEmpty()){ fechaFinal = this.getAtributoFechaInicialHoraFinal().getTime(); }else{ try { fechaFinal = this.getAtributoFechaHoraFinal().getTime(); } catch (IllegalArgumentException ex) { fechaFinal = this.getAtributoFechaHoraFinal().getTime(); } fechaFinal = com.davivienda.utilidades.conversion.Fecha.getFechaFinDia(fechaInicial); } try { // Consulta los registros según los parámetros tomados del request loggerApp.info("TransaccionBean generarNumTrasacciones - fechaInicial " + fechaInicial + " fechaFinal " + fechaFinal + " codigoCajero: " + codigoCajero); itemsNumeroTransacciones = sessionNumTransacciones.getTransaccionesRealizadasPorCajero(null, null, codigoCajero, 9999, fechaInicial, fechaFinal); this.getNumTransacciones().addAll(convertItemsNumTransacciones(itemsNumeroTransacciones)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(false); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(true); this.setMostrarCajSinTransmision(false); } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } if (ex.getLocalizedMessage().contains("NoResultException")) { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, ex); return; } } catch (Exception ex) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, ex); return; } } catch (IllegalArgumentException ex) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return; } } public Collection<Cajero> cajerosSinTransmision() { loggerApp.info("TransaccionBean-cajerosSinTransmision"); String error = ""; String respuesta = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); Collection<Cajero> itemsSinTransmision = null; try { Date fechaInicial = null; Date fechaFinal = null; Integer codigoCajero = 0; Calendar clrfechaInicial = null; Integer codigoCiclo; codigoCajero = Integer.parseInt(this.codigoCajero); if (codigoCajero == 0) { abrirModal("SARA", Constantes.MSJ_SELECCIONAR_CAJERO, null); return null; } try { fechaInicial = getAtributoFechaHoraInicial().getTime(); clrfechaInicial = getAtributoFechaHoraInicial(); } catch (IllegalArgumentException ex) { //fechaInicial = com.davivienda.utilidades.conversion.Fecha.getDateAyer(); abrirModal("SARA", Constantes.MSJ_SELECCIONAR_FECHA, null); return null; } if (null == clrfechaInicial) { clrfechaInicial = Fecha.getCalendarAyer(); } fechaInicialReporte = fechaInicial; fechaFinal = com.davivienda.utilidades.conversion.Fecha.getFechaFinDia(fechaInicial); String strCiclo = String.valueOf(clrfechaInicial.get(Calendar.DAY_OF_MONTH)) + String.valueOf(clrfechaInicial.get(Calendar.YEAR)).substring(2); codigoCiclo = Integer.parseInt(strCiclo); codigoCiclo = ((clrfechaInicial.get(Calendar.MONTH) + 1) * 10000) + codigoCiclo; try { // Consulta los registros según los parámetros tomados del request itemsSinTransmision = sessionSinTransmitir.getCajerosSnTransmitir(codigoCiclo); this.cajerosSinTransamision.clear(); this.cajerosSinTransamision.addAll(convertItemsCajerosSinTransmision(itemsSinTransmision)); this.setMostrarPanelGeneral(false); this.setMostrarDiarioElect(false); this.setMostrarTransacciones(false); this.setMostrarHistorial(false); this.setMostrarNumTrasaccioes(false); this.setMostrarCajSinTransmision(true); } catch (EJBException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); if (ex.getLocalizedMessage().contains("EntityServicioExcepcion")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("IllegalArgumentException")) { abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } if (ex.getLocalizedMessage().contains("NoResultException")) { abrirModal("SARA", Constantes.MSJ_QUERY_SIN_DATA, ex); return null; } } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_QUERY_ERROR, null); return null; } return itemsSinTransmision; } public void generarXLSTransaccion() { loggerApp.info("TransaccionBean-generarXLSTransaccion"); String respuesta = ""; Collection<Transaccion> regs = this.generarTransaccionesData(); Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap(); InitBean initBean = (InitBean) viewMap.get("initBean"); //Creo la hoja de cálculo String[] titulosHoja = TituloDiarioElectronicoGeneral.tituloHoja; String[] titulosColumna = TituloDiarioElectronicoGeneral.tituloColumnas; Collection<Registro> lineas = new ArrayList<Registro>(); Short numColumna; try { if (null != regs && !regs.isEmpty()) { for (Transaccion item : regs) { Registro reg = new Registro(); numColumna = 0; reg.addCelda(new Celda(numColumna++, item.getCajero().getCodigoCajero(), TipoDatoCelda.NUMERICO)); reg.addCelda(new Celda(numColumna++, item.getCajero().getNombre(), TipoDatoCelda.NORMAL)); if (item.getCajero().getTipoLecturaEDC() == 0) { reg.addCelda(new Celda(numColumna++, item.getTipoTransaccion() + "" + item.getCodigoTransaccion() + " " + com.davivienda.sara.procesos.diarioelectronico.filtro.edc.estructura.TipoTransaccion.getTipoTransaccion(item.getCodigoTransaccion()).nombre, TipoDatoCelda.NORMAL)); } else { reg.addCelda(new Celda(numColumna++, "", TipoDatoCelda.NORMAL)); } reg.addCelda(new Celda(numColumna++, com.davivienda.utilidades.conversion.Fecha.aCadena(item.getTransaccionPK().getFechaTransaccion(), FormatoFecha.FECHA_HORA), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getTransaccionPK().getNumeroTransaccion(), TipoDatoCelda.NUMERICO)); reg.addCelda(new Celda(numColumna++, item.getCuenta(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getTarjeta(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, com.davivienda.utilidades.conversion.Numero.aMoneda(item.getValorEntregado()), TipoDatoCelda.MONEDA)); if (item.getReferencia() != null) { reg.addCelda(new Celda(numColumna++, item.getReferencia(), TipoDatoCelda.NORMAL)); } else { reg.addCelda(new Celda(numColumna++, "0", TipoDatoCelda.NORMAL)); } reg.addCelda(new Celda(numColumna++, item.getErrorTransaccion(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getCodigoTerminacionTransaccion(), TipoDatoCelda.NORMAL)); lineas.add(reg); } } else if (itemsDTemp != null) { for (TransaccionTemp item : itemsDTemp) { Registro reg = new Registro(); numColumna = 0; reg.addCelda(new Celda(numColumna++, item.getTransaccionTempPK().getCodigocajero(), TipoDatoCelda.NUMERICO)); reg.addCelda(new Celda(numColumna++, item.getTransaccionTempPK().getCodigocajero(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getTipotransaccion() + "" + item.getCodigotransaccion() + " " + com.davivienda.sara.procesos.diarioelectronico.filtro.edc.estructura.TipoTransaccion.getTipoTransaccion(item.getCodigotransaccion()).nombre, TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, com.davivienda.utilidades.conversion.Fecha.aCadena(item.getTransaccionTempPK().getFechatransaccion(), FormatoFecha.FECHA_HORA), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getTransaccionTempPK().getNumerotransaccion(), TipoDatoCelda.NUMERICO)); reg.addCelda(new Celda(numColumna++, item.getCuenta(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getTarjeta(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, com.davivienda.utilidades.conversion.Numero.aMoneda(item.getValorentregado()), TipoDatoCelda.MONEDA)); if (item.getReferencia() != null) { reg.addCelda(new Celda(numColumna++, item.getReferencia(), TipoDatoCelda.NORMAL)); } else { reg.addCelda(new Celda(numColumna++, "0", TipoDatoCelda.NORMAL)); } reg.addCelda(new Celda(numColumna++, item.getErrortransaccion(), TipoDatoCelda.NORMAL)); reg.addCelda(new Celda(numColumna++, item.getCodigoterminaciontransaccion(), TipoDatoCelda.NORMAL)); lineas.add(reg); } } if (!lineas.isEmpty()) { ArchivoXLS archivo = ProcesadorArchivoXLS.crearLibro("DiarioElectronicoGeneral", titulosHoja, titulosColumna, lineas); objectContext.enviarArchivoXLS(archivo); this.mostrarPanelGeneral = true; this.mostrarDiarioElect = false; this.mostrarTransacciones = false; this.mostrarHistorial = false; this.mostrarNumTrasaccioes = false; this.mostrarCajSinTransmision = false; } } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_CREAR_ARCHIVO, null); } catch (IOException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_DESCARGAR_ARCHIVO, null); } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null); } } public void generarXLSSinTransmision() { loggerApp.info("TransaccionBean-generarXLSSinTransmision"); String respuesta = ""; Collection<Cajero> regs = this.cajerosSinTransmision(); //Creo la hoja de cálculo String[] tituloHoja; tituloHoja = new String[2]; tituloHoja[0] = "Cajeros sin Diario Electronico "; tituloHoja[1] = com.davivienda.utilidades.conversion.Fecha.aCadena(fechaInicialReporte, com.davivienda.utilidades.conversion.FormatoFecha.FECHA_HORA); String[] titulosHoja = tituloHoja; //TituloDiarioElectronicoGeneral.tituloHoja; String[] titulosColumna = TituloDiarioElectronicoGeneral.tituloColumnasCajero; Collection<Registro> lineas = new ArrayList<Registro>(); Short numColumna; try { for (Cajero item : regs) { Registro reg = new Registro(); numColumna = 0; reg.addCelda(new Celda(numColumna++, item.getCodigoCajero(), TipoDatoCelda.NUMERICO)); reg.addCelda(new Celda(numColumna++, item.getNombre(), TipoDatoCelda.NORMAL)); lineas.add(reg); } ArchivoXLS archivo = ProcesadorArchivoXLS.crearLibro("Cajeros Sin Transmitir", titulosHoja, titulosColumna, lineas); objectContext.enviarArchivoXLS(archivo); this.mostrarPanelGeneral = true; this.mostrarDiarioElect = false; this.mostrarTransacciones = false; this.mostrarHistorial = false; this.mostrarNumTrasaccioes = false; this.mostrarCajSinTransmision = false; } catch (IllegalArgumentException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_CREAR_ARCHIVO, null); } catch (IOException ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_DESCARGAR_ARCHIVO, null); } catch (Exception ex) { objectContext.getConfigApp().loggerApp.log(Level.SEVERE, ex.getMessage(), ex); abrirModal("SARA", Constantes.MSJ_ERROR_INTERNO, null); } } public Collection<DiarioElectronicoTransaccionDTO> setColeccionRegistroDiarioElectronico(Collection<DiarioElectronico> registros) { Collection<DiarioElectronicoTransaccionDTO> coleccionDiarioElectronicoBean = new ArrayList<DiarioElectronicoTransaccionDTO>(); for (DiarioElectronico edcRegistro : registros) { DiarioElectronicoTransaccionDTO bean = convertDiarioDTO(edcRegistro); coleccionDiarioElectronicoBean.add(bean); } return coleccionDiarioElectronicoBean; } private DiarioElectronicoTransaccionDTO convertDiarioDTO(DiarioElectronico edcRegistro) { DiarioElectronicoTransaccionDTO bean = new DiarioElectronicoTransaccionDTO(); bean.tipoRegistro = String.valueOf(edcRegistro.getTipoRegistro()); bean.secuencia = new Integer(edcRegistro.getDiarioElectronicoPK().getSecuencia()); bean.datos = com.davivienda.utilidades.edc.Edc.aCadena(edcRegistro.getTipoRegistro(), edcRegistro.getInformacion()); return bean; } public List<TransaccionDTO> convertItemsTransaccion(Collection<Transaccion> items) { Integer idRegistro = 0; List<TransaccionDTO> transacciones = new ArrayList<TransaccionDTO>(); for (Transaccion tra : items) { TransaccionDTO transaccion = new TransaccionDTO(); transaccion.setIdRegistro(++idRegistro); transaccion.setNombreCajero(tra.getCajero().getNombre()); transaccion.setCodigoCajero(String.valueOf(tra.getTransaccionPK().getCodigoCajero())); transaccion.setNumeroSerial(String.valueOf(tra.getTransaccionPK().getNumeroTransaccion())); transaccion.setFecha(com.davivienda.utilidades.conversion.Fecha.aCadena(tra.getTransaccionPK().getFechaTransaccion(), FormatoFecha.FECHA_HORA)); transaccion.setTipoTransaccion(String.valueOf(tra.getTipoTransaccion())); transaccion.setCodigoTransaccion(String.valueOf(tra.getCodigoTransaccion())); if (tra.getCajero().getTipoLecturaEDC() == 0) { transaccion.setDescripcionTransaccion(tra.getTipoTransaccion() + "" + tra.getCodigoTransaccion() + " " + com.davivienda.sara.procesos.diarioelectronico.filtro.edc.estructura.TipoTransaccion.getTipoTransaccion(tra.getCodigoTransaccion()).nombre); } transaccion.setCodigoTerminacion(tra.getCodigoTerminacionTransaccion()); transaccion.setCodigoError(tra.getErrorTransaccion()); transaccion.setCuenta(tra.getCuenta()); transaccion.setReferencia(tra.getReferencia()); transaccion.setTarjeta(tra.getTarjeta()); transaccion.setValorEntregado(com.davivienda.utilidades.conversion.Numero.aMoneda(tra.getValorEntregado())); transaccion.setValorSolicitado(com.davivienda.utilidades.conversion.Numero.aMoneda(tra.getValorSolicitado())); transacciones.add(transaccion); } return transacciones; } public List<TransaccionDTO> convertItemsTransaccionTemp(Collection<TransaccionTemp> items) { Integer idRegistro = 0; List<TransaccionDTO> transacciones = new ArrayList<TransaccionDTO>(); for (TransaccionTemp tra : items) { TransaccionDTO transaccion = new TransaccionDTO(); transaccion.setIdRegistro(++idRegistro); transaccion.setNombreCajero(String.valueOf(tra.getTransaccionTempPK().getCodigocajero())); transaccion.setCodigoCajero(String.valueOf(tra.getTransaccionTempPK().getCodigocajero())); transaccion.setNumeroSerial(String.valueOf(tra.getTransaccionTempPK().getNumerotransaccion())); transaccion.setFecha(com.davivienda.utilidades.conversion.Fecha.aCadena(tra.getTransaccionTempPK().getFechatransaccion(), FormatoFecha.FECHA_HORA)); transaccion.setTipoTransaccion(String.valueOf(tra.getTipotransaccion())); transaccion.setCodigoTransaccion(String.valueOf(tra.getCodigotransaccion())); transaccion.setDescripcionTransaccion(tra.getTipotransaccion() + "" + tra.getCodigotransaccion() + " " + com.davivienda.sara.procesos.diarioelectronico.filtro.edc.estructura.TipoTransaccion.getTipoTransaccion(tra.getCodigotransaccion()).nombre); transaccion.setCodigoTerminacion(tra.getCodigoterminaciontransaccion()); transaccion.setCodigoError(tra.getErrortransaccion()); transaccion.setCuenta(tra.getCuenta()); transaccion.setReferencia(tra.getReferencia()); transaccion.setTarjeta(tra.getTarjeta()); transaccion.setValorEntregado(com.davivienda.utilidades.conversion.Numero.aMoneda(tra.getValorentregado())); transaccion.setValorSolicitado(com.davivienda.utilidades.conversion.Numero.aMoneda(tra.getValorsolicitado())); transacciones.add(transaccion); } return transacciones; } public List<HistoricoCargueDTO> convertItemsHistorico(Collection<EdcCargue> items) { Integer idRegistro = 0; List<HistoricoCargueDTO> historicos = new ArrayList<HistoricoCargueDTO>(); for (EdcCargue item : items) { HistoricoCargueDTO historico = new HistoricoCargueDTO(); historico.setIdRegistro(++idRegistro); historico.setCodigoCajero(String.valueOf(item.getCodigoCajero())); historico.setNombreArchivo(item.getNombrearchivo()); historico.setCiclo(String.valueOf(item.getCiclo())); historico.setFecha(String.valueOf(item.getFechaEdcCargue())); historico.setEstadoProceso(com.davivienda.sara.constantes.EstadoProceso.getEstadoProceso(item.getEstadoproceso())); historico.setError(String.valueOf(item.getError())); historico.setDescripcionError(com.davivienda.sara.constantes.CodigoError.getCodigoError(item.getError())); historico.setTamanoBytes(String.valueOf(item.getTamano())); historico.setPrueba(true); historicos.add(historico); } loggerApp.info("generarHistoricoCargue historicos " + historicos.size()); return historicos; } public List<NumeroTransaccionesDTO> convertItemsNumTransacciones(Collection<CantidadTransaccionesBean> items) { Integer idRegistro = 0; List<NumeroTransaccionesDTO> numeroTransacciones = new ArrayList<NumeroTransaccionesDTO>(); for (CantidadTransaccionesBean item : items) { NumeroTransaccionesDTO numTransaccion = new NumeroTransaccionesDTO(); numTransaccion.setIdRegistro(++idRegistro); numTransaccion.setCodigoCajero(String.valueOf(item.getCodigoCajero())); numTransaccion.setNombreCajero(item.getNombreCajero()); numTransaccion.setFecha(item.getFecha()); numTransaccion.setDescripcionTransaccion(com.davivienda.sara.procesos.diarioelectronico.filtro.edc.estructura.TipoTransaccion.getTipoTransaccion(item.getTipoTransacion()).nombre); numTransaccion.setCantidad(com.davivienda.utilidades.conversion.Numero.aFormatoDecimal(item.getCantidad())); numeroTransacciones.add(numTransaccion); } return numeroTransacciones; } public List<CajerosSinTransmisionDTO> convertItemsCajerosSinTransmision(Collection<Cajero> items) { Integer idRegistro = 0; List<CajerosSinTransmisionDTO> cajerosSinTransaccion = new ArrayList<CajerosSinTransmisionDTO>(); for (Cajero item : items) { CajerosSinTransmisionDTO cajeroSinTransmision = new CajerosSinTransmisionDTO(); cajeroSinTransmision.setIdRegistro(++idRegistro); cajeroSinTransmision.setCodigoCajero(String.valueOf(item.getCodigoCajero())); cajeroSinTransmision.setNombreCajero(item.getNombre()); cajerosSinTransaccion.add(cajeroSinTransmision); } return cajerosSinTransaccion; } public Calendar getAtributoFechaHoraInicial() throws IllegalArgumentException { String fechaStr = this.fechaInicial; String horaStr = this.horaInicial; fechaStr = fechaStr.concat(horaStr); Calendar calendar = null; try { calendar = com.davivienda.utilidades.conversion.Cadena.aCalendar(fechaStr, FormatoFecha.FECHA_HORA_DOJO); } catch (IllegalArgumentException ex) { throw ex; } return calendar; } public Calendar getAtributoFechaHoraFinal() throws IllegalArgumentException { String fechaStr = this.fechaFinal; String horaStr = this.horaFinal; fechaStr = fechaStr.concat(horaStr); Calendar calendar = null; try { calendar = com.davivienda.utilidades.conversion.Cadena.aCalendar(fechaStr, FormatoFecha.FECHA_HORA_DOJO); } catch (IllegalArgumentException ex) { throw ex; } return calendar; } public Calendar getAtributoFechaInicialHoraFinal() throws IllegalArgumentException { String fechaStr = this.fechaInicial; String horaStr = this.horaFinal; fechaStr = fechaStr.concat(horaStr); Calendar calendar = null; try { calendar = com.davivienda.utilidades.conversion.Cadena.aCalendar(fechaStr, FormatoFecha.FECHA_HORA_DOJO); } catch (IllegalArgumentException ex) { throw ex; } return calendar; } private List<SelectItem> cargarListaHora() { List<SelectItem> lista = new ArrayList<SelectItem>(); boolean iniciar = true; int mn = 0; int hr = 0; while (iniciar) { SelectItem item = null; if (hr < 24) { if (mn == 0) { if (hr < 10) { item = new SelectItem("0" + hr + ":00:00", "0" + hr + ":00:00"); } else { item = new SelectItem(+hr + ":00:00", +hr + ":00:00"); } mn += 15; } else if (mn < 60) { if (hr < 10) { item = new SelectItem("0" + hr + ":" + mn + ":00", "0" + hr + ":" + mn + ":00"); } else { item = new SelectItem(+hr + ":" + mn + ":00", +hr + ":" + mn + ":00"); } mn += 15; } else { hr++; mn = 0; if (hr < 24) { if (hr < 10) { item = new SelectItem("0" + hr + ":00:00", "0" + hr + ":00:00"); } else { item = new SelectItem(+hr + ":00:00", +hr + ":00:00"); } } mn += 15; } if (item != null) { lista.add(item); } } else { iniciar = false; } } return lista; } /** * @return the codigoCajero */ public String getCodigoCajero() { return codigoCajero; } /** * @param codigoCajero the codigoCajero to set */ public void setCodigoCajero(String codigoCajero) { this.codigoCajero = codigoCajero; } public String getFechaInicial() { return fechaInicial; } public void setFechaInicial(String fechaInicial) { this.fechaInicial = fechaInicial; } public String getFechaFinal() { return fechaFinal; } public void setFechaFinal(String fechaFinal) { this.fechaFinal = fechaFinal; } /** * @return the horaInicial */ public String getHoraInicial() { return horaInicial; } /** * @param horaInicial the horaInicial to set */ public void setHoraInicial(String horaInicial) { this.horaInicial = horaInicial; } /** * @return the horaFinal */ public String getHoraFinal() { return horaFinal; } /** * @param horaFinal the horaFinal to set */ public void setHoraFinal(String horaFinal) { this.horaFinal = horaFinal; } /** * @return the mostrarDiarioElect */ public boolean isMostrarDiarioElect() { return mostrarDiarioElect; } /** * @param mostrarDiarioElect the mostrarDiarioElect to set */ public void setMostrarDiarioElect(boolean mostrarDiarioElect) { this.mostrarDiarioElect = mostrarDiarioElect; } /** * @return the itemsFormateados */ public Collection<DiarioElectronicoTransaccionDTO> getItemsFormateados() { return itemsFormateados; } /** * @param itemsFormateados the itemsFormateados to set */ public void setItemsFormateados(Collection<DiarioElectronicoTransaccionDTO> itemsFormateados) { this.itemsFormateados = itemsFormateados; } /** * @return the mostrarTransacciones */ public boolean isMostrarTransacciones() { return mostrarTransacciones; } /** * @param mostrarTransacciones the mostrarTransacciones to set */ public void setMostrarTransacciones(boolean mostrarTransacciones) { this.mostrarTransacciones = mostrarTransacciones; } /** * @return the itemsDTemp */ public Collection<TransaccionTemp> getItemsDTemp() { return itemsDTemp; } /** * @param itemsDTemp the itemsDTemp to set */ public void setItemsDTemp(Collection<TransaccionTemp> itemsDTemp) { this.itemsDTemp = itemsDTemp; } /** * @return the talon */ public String getTalon() { return talon; } /** * @param talon the talon to set */ public void setTalon(String talon) { this.talon = talon; } /** * @return the referencia */ public String getReferencia() { return referencia; } /** * @param referencia the referencia to set */ public void setReferencia(String referencia) { this.referencia = referencia; } /** * @return the cuenta */ public String getCuenta() { return cuenta; } /** * @param cuenta the cuenta to set */ public void setCuenta(String cuenta) { this.cuenta = cuenta; } /** * @return the tarjeta */ public String getTarjeta() { return tarjeta; } /** * @param tarjeta the tarjeta to set */ public void setTarjeta(String tarjeta) { this.tarjeta = tarjeta; } /** * @return the mostrarPanelGeneral */ public boolean isMostrarPanelGeneral() { return mostrarPanelGeneral; } /** * @param mostrarPanelGeneral the mostrarPanelGeneral to set */ public void setMostrarPanelGeneral(boolean mostrarPanelGeneral) { this.mostrarPanelGeneral = mostrarPanelGeneral; } /** * @return the transacciones */ public List<TransaccionDTO> getTransacciones() { return transacciones; } /** * @param transacciones the transacciones to set */ public void setTransacciones(List<TransaccionDTO> transacciones) { this.transacciones = transacciones; } /** * @return the mostrarHistorial */ public boolean isMostrarHistorial() { return mostrarHistorial; } /** * @param mostrarHistorial the mostrarHistorial to set */ public void setMostrarHistorial(boolean mostrarHistorial) { this.mostrarHistorial = mostrarHistorial; } /** * @return the historicosCargue */ public List<HistoricoCargueDTO> getHistoricosCargue() { return historicosCargue; } /** * @param historicosCargue the historicosCargue to set */ public void setHistoricosCargue(List<HistoricoCargueDTO> historicosCargue) { this.historicosCargue = historicosCargue; } /** * @return the numTransacciones */ public List<NumeroTransaccionesDTO> getNumTransacciones() { return numTransacciones; } /** * @param numTransacciones the numTransacciones to set */ public void setNumTransacciones(List<NumeroTransaccionesDTO> numTransacciones) { this.numTransacciones = numTransacciones; } /** * @return the cajerosSinTransamision */ public List<CajerosSinTransmisionDTO> getCajerosSinTransamision() { return cajerosSinTransamision; } /** * @param cajerosSinTransamision the cajerosSinTransamision to set */ public void setCajerosSinTransamision(List<CajerosSinTransmisionDTO> cajerosSinTransamision) { this.cajerosSinTransamision = cajerosSinTransamision; } /** * @return the mostrarNumTrasaccioes */ public boolean isMostrarNumTrasaccioes() { return mostrarNumTrasaccioes; } /** * @param mostrarNumTrasaccioes the mostrarNumTrasaccioes to set */ public void setMostrarNumTrasaccioes(boolean mostrarNumTrasaccioes) { this.mostrarNumTrasaccioes = mostrarNumTrasaccioes; } /** * @return the mostrarCajSinTransmision */ public boolean isMostrarCajSinTransmision() { return mostrarCajSinTransmision; } /** * @param mostrarCajSinTransmision the mostrarCajSinTransmision to set */ public void setMostrarCajSinTransmision(boolean mostrarCajSinTransmision) { this.mostrarCajSinTransmision = mostrarCajSinTransmision; } public List<SelectItem> getListaHora() { return listaHora; } public void setListaHora(List<SelectItem> listaHora) { this.listaHora = listaHora; } }
/* Author: Arkadiusz Galas Date: 7 JUL 2016 ID: 27307 Name: Alternating Sequences */ /** * AlternatingSequences class is a solution of Alternating Sequences problem * on http://www.spoj.com/problems/ALTSEQ/ */ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.StringTokenizer; public class AlternatingSequences { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer token1 = new StringTokenizer(br.readLine()); int n = Integer.parseInt(token1.nextToken()); int [] inputs = new int [n]; int [] longestend = new int [n]; //length of longest sequence ending with i-th position StringTokenizer token2 = new StringTokenizer(br.readLine()); for (int i = 0; i<n; i++) { inputs [i] = Integer.parseInt(token2.nextToken()); } int longestEver = 0; for (int i=0; i<n; i++) { longestend [i] = 1; for (int j=0; j<i; j++) { if (Math.abs(inputs [j]) < Math.abs(inputs [i]) && (long) inputs [j] * (long) inputs [i] < 0) { longestend [i] = Math.max(longestend [i], longestend [j] + 1); } } longestEver = Math.max(longestEver, longestend [i]); } System.out.println(longestEver); } }
import java.io.*; import java.util.*; public class Solution { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); int[] a=new int[6]; int fine; for(int i=0;i<6;i++){ a[i]=sc.nextInt(); } if(a[2]-a[5]<=0){ if(a[1]-a[4]<=0 || a[2]-a[5]<0){ if(a[0]-a[3]<=0 || a[2]-a[5]<0 || a[1]-a[4]<0){ fine=0; } else fine=(a[0]-a[3])*15; } else fine=(a[1]-a[4])*500; } else fine=10000; System.out.println(fine); } }
package com.saasxx.core.module.account.vo; public class VPreUser { String email; String tel; String realName; String advice; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } @Override public String toString() { return "VPreUser [email=" + email + ", tel=" + tel + ", realName=" + realName + ", advice=" + advice + "]"; } }
package com.lti.Collections.Set; import java.util.Set; import java.util.StringTokenizer; /** * Created by busis on 2020-12-03. */ public class TreeSet { public String removeDups(String input){ StringTokenizer stringTokenizer = new StringTokenizer(input,","); Set fruits = new java.util.TreeSet(); while (stringTokenizer.hasMoreTokens()){ String fruit = stringTokenizer.nextToken(); if(!fruits.contains(fruit)){ fruits.add(fruit); } } String ret=""; for(Object fruit:fruits){ ret+=","+fruit; } return ret.substring(1); } public int[] removeDupsarr(int[] input){ //If this was TreeSet, it doesnt accept as it clashes with the class in here Set s = new java.util.TreeSet(); int n=input.length; for(int i=0;i<n;i++) s.add(input[i]); n=s.size(); int[] ret=new int[n]; int c=0; for(Object i:s){ ret[c++]= Integer.parseInt(i.toString()); //Object should be converted to String to be able to parseInt } return ret; } public static void main(String[] args) { //It is same as Hashset but arranges in ascending order Set s = new java.util.TreeSet(); s.add("B"); s.add("G"); s.add("A"); //prints abg System.out.println(s); String fruits="apple,lichi,apple,mango,lemon,guava,banana,mango"; System.out.println(new TreeSet().removeDups(fruits)); int[] arr={12,32,3,1,212,2,3,1,3,8}; int res[] = new TreeSet().removeDupsarr(arr); for(int i=0;i<res.length-1;i++){ System.out.print(res[i] + ","); } System.out.println(res[res.length-1]); } }
package com.vaccination.app.services; import java.util.ArrayList; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.vaccination.app.models.User; import com.vaccination.app.repositories.UserRepository; @Service public class UserService { @Autowired UserRepository userRepository; public User registerUser(User user) { user.setStatus("WAITING"); return userRepository.registerUser(user); } public User loginUser(User user) { return userRepository.loginUser(user); } public ArrayList<User> getAllUsers() { return userRepository.getAllUsers(); } public User getUserByAadhaar(String aadhaar) { return userRepository.getUserByAadhaar(aadhaar); } }
package com.jixin.factory.method; public class TeslaCarFactory implements CarFactory { public Car getCar() { return new TeslaCar(); } }
package com.company.project.system.es; import com.thunisoft.elasticsearch.ElasticReader; import com.thunisoft.elasticsearch.ElasticWriter; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkRequestBuilder; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.join.query.HasParentQueryBuilder; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHits; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Title: BatchInsert * Description: * Company: 北京华宇元典信息服务有限公司 * * @author lyf * @version 1.0 * @date 2017年3月31日 上午9:21:07 */ @Component public class BatchDeal { private static Logger logger = LoggerFactory.getLogger(BatchDeal.class); /** * 以下是es相关配置 */ private static ElasticWriter esWriter = null; private static ElasticReader esReader = null; private static String cluster; private static String ip; private static int port; @Value("${es.cluster}") public void setCluster(String cluster) { BatchDeal.cluster = cluster; } @Value("${es.ip}") public void setIp(String ip) { BatchDeal.ip = ip; } @Value("${es.port}") public void setPort(int port) { BatchDeal.port = port; } public void init() { esWriter = new ElasticWriter(cluster, ip, port); esReader = new ElasticReader(cluster, ip, port); } public static ElasticWriter getESWriter() { try { if (esWriter == null) { esWriter = new ElasticWriter(cluster, ip, port); } } catch (Throwable e) { logger.error("失败!", e); } return esWriter; } public static ElasticReader getESReader() { if (esReader == null) { esReader = new ElasticReader(cluster, ip, port); } return esReader; } /** * 之前的elasticsearch性能问题可能是结构化数据中的长的base64编码导致,不是批量导致,恢复批量尝试 * @param esWriter * @param list */ // public static void batchExecute(ElasticWriter esWriter, List<BatchBean> list) { // if (esWriter == null) { // esWriter = getESWriter(); // } // BulkRequestBuilder builder = esWriter.getBulkRequestBuilder(); // for (BatchBean bean : list) { // try { // if (bean.getFlag().equals(TypeEnum.DELETE)) { // esWriter.delete(bean.getIndex(), bean.getType(), bean.getId()); // } else if (bean.getFlag().equals(TypeEnum.UPDATE)) { // // } else { // esWriter.index(bean.getIndex(), bean.getType(), bean.getFid(), bean.getId(), bean.getJson()); // } // } catch (Exception e) { // logger.error(bean.getFlag().name() + " id: " + bean.getId() + " failed. index: " + bean.getIndex() // + "type: " + bean.getType()); // logger.error("cause by:" + e.getMessage()); // } // } // } /** * batch deal:insert/update/delete * 批量操作 */ public static void batchExecute(ElasticWriter esWriter, List<BatchBean> list) { if (esWriter == null) { esWriter = getESWriter(); } BulkRequestBuilder builder = esWriter.getBulkRequestBuilder(); for (BatchBean bean : list) { try { if (bean.getFlag().equals(BatchBean.TypeEnum.DELETE)) { builder.add(esWriter.getDeleteRequestBuilder(bean.getIndex(), bean.getType(), bean.getId())); } else if (bean.getFlag().equals(BatchBean.TypeEnum.UPDATE)) { builder.add(esWriter.getUpdateRequestBuilder(bean.getIndex(), bean.getType(), bean.getId(), bean.getJson())); } else { builder.add(esWriter.getIndexRequestBuilder(bean.getIndex(), bean.getType(), bean.getFid(), bean.getId(), bean.getJson())); } } catch (Exception e) { logger.error(bean.getFlag().name() + " id: " + bean.getId() + " failed. index: " + bean.getIndex() + " type: " + bean.getType()); logger.error("cause by:" + e.getMessage()); } } BulkResponse resp = builder.execute().actionGet(); if (resp.hasFailures()) { Iterator<BulkItemResponse> iter = resp.iterator(); while (iter.hasNext()) { BulkItemResponse r = iter.next(); if (r != null && r.isFailed()) { logger.error("deal id: " + r.getId() + " failed. index: " + r.getIndex() + " type: " + r.getType()); //slf4j如果需要输出error信息请使用{},不然信息不打印 logger.error("cause by:{}", r.getFailure().getMessage() + "|" + r.getFailureMessage()); } } } } /** * batch deal:insert/update/delete */ public static void batchExecute(List<BatchBean> list) { batchExecute(null, list); } public static List<String> searchAllYsId(ElasticReader esReader, String index, String type, String caseid) { List<String> resultIds = new ArrayList<String>(); if (esReader == null) { esReader = getESReader(); } //es的查询构造 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.size(20); builder.storedField("_id"); QueryBuilder queryBuilder = QueryBuilders.queryStringQuery("caseId:" + caseid); builder.query(queryBuilder); //es的查询 SearchRequest searchRequest = esReader.getSearchRequest(index); searchRequest.scroll(new TimeValue(300000L)); searchRequest.source(builder); SearchResponse response = esReader.search(searchRequest); String scrollId = response.getScrollId(); while (scrollId != null) { response = esReader.searchScroll(scrollId, 300000L); scrollId = response.getScrollId(); SearchHits results = response.getHits(); if (results.getHits().length > 0) { for (SearchHit hit : results.getHits()) { String ysId = hit.getId(); resultIds.add(ysId); } } else { break; } } return resultIds; } public static List<String> searchAllYsId(String index, String type, String caseid) { return searchAllYsId(null, index, type, caseid); } /** * 查询index里面的id的所有子文档 */ public static void searchAllChild(ElasticReader esReader, Long timeout, int size, String index, String parentType, String id, List<String> types, List<String> ids) { if (esReader == null) { esReader = getESReader(); } if (timeout == null) { timeout = 300000L; } if (size == 0) { size = 20; } //es的查询构造 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.size(size); builder.storedField("_id"); QueryBuilder innerQuery = QueryBuilders.termQuery("_id", id); QueryBuilder queryBuilder = new HasParentQueryBuilder(parentType, innerQuery, false); builder.query(queryBuilder); //es的查询 SearchRequest searchRequest = esReader.getSearchRequest(index); searchRequest.scroll(new TimeValue(timeout)); searchRequest.source(builder); SearchResponse response = esReader.search(searchRequest); //es的结果获取 //logger.warn("{} id has {} childDoc", id, response.getHits().getTotalHits()); String scrollId = response.getScrollId(); while (scrollId != null) { response = esReader.searchScroll(scrollId, timeout); scrollId = response.getScrollId(); SearchHits results = response.getHits(); if (results.getHits().length > 0) { for (SearchHit hit : results.getHits()) { String childId = hit.getId(); String childType = hit.getType(); types.add(childType); ids.add(childId); } } else { break; } } } /** * 查询index里面的id的所有子文档 */ public static void searchAllChild(Long timeout, int size, String index, String parentType, String id, List<String> types, List<String> ids) { searchAllChild(null, timeout, size, index, parentType, id, types, ids); } /** * 查询index里面的id的所有子文档 */ public static void searchAllChild(String index, String parentType, String id, List<String> types, List<String> ids) { searchAllChild(null, null, 0, index, parentType, id, types, ids); } /** * 查询index里面的id的所有子文档 */ public static void searchAllChild(ElasticReader esReader, String index, String parentType, String id, List<String> types, List<String> ids) { searchAllChild(esReader, null, 0, index, parentType, id, types, ids); } public static void main(String[] args) { BatchDeal da = new BatchDeal(); ElasticWriter esWriter = da.getESWriter(); } }
package com.xianzaishi.wms.tmscore.dto; import com.xianzaishi.wms.tmscore.vo.PickingBasketStatuDO; public class PickingBasketStatuDTO extends PickingBasketStatuDO { }
package com.dqm.msg; import com.dqm.annotations.Index; import com.dqm.msg.common.MsgPack; import lombok.Getter; import lombok.Setter; import java.math.BigInteger; /** * Created by dqm on 2018/9/14. */ @Getter @Setter public class Pong implements MsgPack { @Index(val = 0, specialType = Index.SpecialType.UINT64) private BigInteger nonce; }
class Solution { public int lengthLongestPath(String input) { if(input == null || input == "") return 0; String[] items = input.split("\n"); Stack<Integer> stack = new Stack<>(); stack.push(0); int maxLen = 0; for(String item : items){ int level = item.lastIndexOf("\t") + 1; while(level + 1 < stack.size()){ stack.pop(); } int len = stack.peek() + item.length() - level + 1; stack.push(len); if(item.contains(".")){ maxLen = Math.max(len-1, maxLen); } } return maxLen; } }
package com.example.vijaygarg.delagain.Model; /** * Created by vijaygarg on 03/04/18. */ public class SchemeModel { String imageurl; String description; String date; String title; Boolean is_active; public Boolean getIs_active() { return is_active; } public void setIs_active(Boolean is_active) { this.is_active = is_active; } public SchemeModel() { } public SchemeModel(String imageurl, String description, String date,String title,Boolean is_active) { this.imageurl = imageurl; this.description = description; this.date = date; this.title=title; this.is_active=is_active; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImageurl() { return imageurl; } public void setImageurl(String imageurl) { this.imageurl = imageurl; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } }
package com.qa.hubspot.test; import org.testng.Assert; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import com.qa.hubspot.base.BaseTest; import com.qa.hubspot.listeners.ExtentReportListener; import com.qa.hubspot.utils.Constants; import com.qa.hubspot.utils.JavaScriptUtil; //@Listeners(ExtentReportListener.class) public class LoginPageTest extends BaseTest { @Test(priority = 2) public void verifyLoginPageTitleTest() { String title = loginPage.getLoginPageTitle(); System.out.println("This is my LoginPage Title :: " + title); Assert.assertEquals(title, Constants.LOGIN_PAGE_TITLE, "login page title is not matched"); } @Test(priority = 1) public void verifySignUpLinkTest() { Assert.assertTrue(loginPage.verifySignUpLink(), "SignUp link is not displayed. . ."); } @Test(priority = 3) public void verifyloginTest() { loginPage.doLogin(prop.getProperty("username"), prop.getProperty("password")); } }
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Servlet3 */ public class Servlet3 extends HttpServlet { private static final long serialVersionUID = 1L; String name; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); name=request.getParameter("username"); HttpSession session=request.getSession(); session.setAttribute("User",name); out.println("<a href='servlet2'>Click</a>"); } }
package com.cai.seckill.config; import com.cai.seckill.access.UserContext; import com.cai.seckill.pojo.User; import com.cai.seckill.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.MethodParameter; import org.springframework.stereotype.Service; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; /* 自定义参数解析器 */ @Service public class UserArgumentResolver implements HandlerMethodArgumentResolver { @Autowired UserService userService; public boolean supportsParameter(MethodParameter parameter) { // 指定参数如果参数类型是User,则使用该解析器。 // 如果直接返回true,则代表将此解析器用于所有参数 Class<?> clazz = parameter.getParameterType(); return clazz==User.class; } /** * 将request中的请求参数解析到当前Controller参数上 * @param parameter 需要被解析的Controller参数,此参数必须首先传给{@link #supportsParameter}并返回true * @param mavContainer 当前request的ModelAndViewContainer * @param webRequest 当前request * @param binderFactory 生成{@link WebDataBinder}实例的工厂 * @return 解析后的Controller参数 */ public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { return UserContext.getUser(); } }
package com.beadhouse.domen; public class Advertising { private int id; private String background; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getBackground() { return background; } public void setBackground(String background) { this.background = background; } }