text
stringlengths
10
2.72M
/* * Copyright 2016 TeddySoft Technology. All rights reserved. * */ package tw.teddysoft.gof.Adapter; import java.util.List; public interface AgentModelContext { void setAgent(Agent agent); Agent getAgent(); void addAcceport(Acceptor acceptor); Acceptor getAcceptor(String key); List<Acceptor> getAcceptors(); }
package com.huffingtonpost.chronos.model; import java.util.ArrayList; import java.util.List; import java.util.Objects; import org.apache.log4j.Logger; import org.joda.time.DateTime; public class JobSpec { static final long serialVersionUID = 2L; public static Logger LOG = Logger.getLogger(JobSpec.class); public enum Interval { Hourly("hourly"), Daily("daily"), Weekly("weekly"), Monthly("monthly"); public final String name; Interval(String name) { this.name = name; } } public enum JobType { Query("query"), Script("script"); public final String name; JobType(String name) { this.name = name; } } private JobType jobType; private long id; private String user; private String password; private String name; private String description; private String code; private String resultTable; private Interval interval; private int startMinute; private int startHour; private int startDay; private String driver; private boolean enabled; private boolean shouldRerun = true; private String resultQuery; private List<String> resultEmail = new ArrayList<>(); private List<String> statusEmail = new ArrayList<>(); private DateTime lastModified; public JobSpec(){ } public String makeResultQuery(int limit, String resultQuery) { return String.format(resultQuery, this.resultTable, limit); } @Override public String toString() { String rq = null; if (resultQuery != null) { rq = resultQuery.substring(0, resultQuery.length() > 100 ? 100 : resultQuery.length()); } String c = null; if (code != null) { c = code.substring(0, code.length() > 100 ? 100 : code.length()); } return new String("<JobSpec - id:" + id + ", name:" + name + ", description:" + description + ", code:" + c + ", jobType:" + jobType + ", resultQuery:" + rq + ", resultTable:" + resultTable + ", interval:" + interval + ", startDay:" + startDay + ", startHour:" + startHour + ", startMinute:" + startMinute + ", driver:" + driver + ", enabled:" + enabled + ", shouldRerun:" + shouldRerun + ", statusEmail:" + statusEmail + ", lastModified:" + lastModified + ">"); } @Override public int hashCode() { return Objects.hash(name, description, code, resultTable, interval, startMinute, startHour, startDay, driver, enabled, shouldRerun, resultQuery, resultEmail, statusEmail, jobType); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof JobSpec) { JobSpec other = (JobSpec) obj; return Objects.equals(id, other.id) && Objects.equals(name, other.name) && Objects.equals(description, other.description) && Objects.equals(code, other.code) && Objects.equals(resultTable, other.resultTable) && Objects.equals(interval, other.interval) && Objects.equals(startMinute, other.startMinute) && Objects.equals(startHour, other.startHour) && Objects.equals(startDay, other.startDay) && Objects.equals(driver, other.driver) && Objects.equals(enabled, other.enabled) && Objects.equals(shouldRerun, other.shouldRerun) && Objects.equals(resultQuery, other.resultQuery) && Objects.equals(resultEmail, other.resultEmail) && Objects.equals(statusEmail, other.statusEmail) && Objects.equals(jobType, other.jobType) ; } return false; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getResultTable() { return resultTable; } public void setResultTable(String resultTable) { this.resultTable = resultTable; } public Interval getInterval() { return interval; } public void setInterval(Interval interval) { this.interval = interval; } public int getStartMinute() { return startMinute; } public void setStartMinute(int startMinute) { this.startMinute = startMinute; } public int getStartHour() { return startHour; } public void setStartHour(int startHour) { this.startHour = startHour; } public int getStartDay() { return startDay; } public void setStartDay(int startDay) { this.startDay = startDay; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean getShouldRerun() { return shouldRerun; } public void setShouldRerun(boolean shouldRerun) { this.shouldRerun = shouldRerun; } public String getResultQuery() { return resultQuery; } public void setResultQuery(String resultQuery) { this.resultQuery = resultQuery; } public List<String> getResultEmail() { return resultEmail; } public void setResultEmail(List<String> resultEmail) { if (resultEmail == null) { LOG.debug("Setting resultEmail to [] since null was provided"); resultEmail = new ArrayList<String>(); } this.resultEmail = resultEmail; } public List<String> getStatusEmail() { return statusEmail; } public void setStatusEmail(List<String> statusEmail) { if (statusEmail == null) { LOG.debug("Setting statusEmail to [] since null was provided"); statusEmail = new ArrayList<String>(); } this.statusEmail = statusEmail; } public DateTime getLastModified() { return lastModified; } public void setLastModified(DateTime lastModified) { this.lastModified = lastModified; } public String getUser() { return user; } public void setUser(String user) { if (user == null) { LOG.debug("Setting user to \"\" since null was provided"); user = ""; } this.user = user; } public String getPassword() { return password; } public void setPassword(String password) { if (password == null) { LOG.debug("Setting password to \"\" since null was provided"); password = ""; } this.password = password; } public void setType(JobType jobType) { this.jobType = jobType; } public JobType getType() { return jobType; } }
package src.server_main; /*import java.io.InputStream; import java.io.OutputStream;*/ public interface Public_Element { public final int L_ERROR = 0; public final int L_INFO = 1; public final int L_DEBUG = 2; public final int S_WRITE = 3; public final int S_READ = 4; public final int E_READ = -5; public final int E_WRITE = -6; public Debug Logd = new Debug(); public Public_Stream pStream = new Public_Stream(); public Buf_Handler buf_handler = new Buf_Handler(); public Client_Connector client_connector = new Client_Connector(); }
import java.util.Scanner; public class CalculateBattingStatistics { public static void main(String[] args) { Scanner scan = new Scanner(System.in); char idLoop = 'y'; while((idLoop == 'y')){ int numBatters = Validator.getInt(scan, "Enter number of batters: ", 1, Integer.MAX_VALUE); int[][] statChart = new int[numBatters][]; getAtBats(scan, statChart); for (int i = 0; i < statChart.length; i++) { System.out.printf("Batter %d batting average: %.3f slugging percentage: %.3f\n", i + 1, batAvg(statChart[i]), slugPercentage(statChart[i])); } System.out.println("Would you like find more stats?(Y/N)"); while (!scan.hasNext("[yYnN]")) { System.out.println("Enter y to find more stats or n to quit"); scan.next(); } idLoop = scan.next().charAt(0); } System.out.println("Goodbye!"); } private static void getAtBats(Scanner scan, int[][] statChart) { for (int i = 0; i < statChart.length; i++) { int atBats = Validator.getInt(scan, "Enter number of at bats for batter " + (i) + ": ", 1, Integer.MAX_VALUE); statChart[i] = new int[atBats]; System.out.println(); System.out.println("0=out, 1=single, 2=double, 3=triple, 4=home run"); for (int j = 0; j < statChart[i].length; j++) { statChart[i][j] = Validator.getInt(scan, "Result for at-bat " + j + ": ", 0, 4); } } } public static double batAvg(int[] atBats) { int count = 0; for (int bat : atBats) { if (bat > 0) { count++; } } return (double) count / atBats.length; } public static double slugPercentage(int[] atBats) { int sum = 0; for (int bat : atBats) { sum += bat; } return (double) sum / atBats.length; } }
/** * */ package com.wordpress.gertonscorner.todo.dto; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; /** * Todo sort transfer object. Contains the sorted list of todos * * @author Gerton * */ public class TodoSortDTO implements Serializable { /** * */ private static final long serialVersionUID = 3110872060364853835L; private Collection<String> sortedIds = new ArrayList<String>(0); /** * @param sortedIds the sortedIds to set */ public void setSortedIds(Collection<String> sortedIds) { this.sortedIds = sortedIds; } /** * @return the sortedIds */ public Collection<String> getSortedIds() { return sortedIds; } }
package com.logzc.common.util; import org.junit.Test; /** * Created by lishuang on 2016/9/28. */ public class PropertyUtilTest { @Test public void testGet(){ String url = PropertyUtil.getProperty("/com.logzc.webzic/logzc/webzic/config.properties","jdbc.url"); System.out.println(url); } }
package com.ai.platform.agent.ssh; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /** * This program will demonstrate the sftp protocol support. * $ CLASSPATH=.:../build javac Sftp.java * $ CLASSPATH=.:../build java Sftp * You will be asked username, host and passwd. * If everything works fine, you will get a prompt 'sftp>'. * 'help' command will show available command. * In current implementation, the destination path for 'get' and 'put' * commands must be a file, not a directory. * */ import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class SftpNoAsk { public static void main(String[] arg) { try { JSch jsch = new JSch(); long startTime = System.currentTimeMillis(); String host = "10.1.235.197"; String user = "swuser01"; final Session session = jsch.getSession(user, host, 22); String passwd = "swuser01@123"; session.setPassword(passwd); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftp = (ChannelSftp) channel; sftp.cd("/aifs01/users/zkpusr01"); InputStream instream = sftp.get("zookeeper.001.tgz"); OutputStream outstream = new FileOutputStream(new File("E://zookeeper.001.tgz")); byte b[] = new byte[1024 * 1024]; int n; while ((n = instream.read(b)) != -1) { outstream.write(b, 0, n); } outstream.flush(); outstream.close(); instream.close(); long endTime = System.currentTimeMillis(); System.out.println("use " + (endTime - startTime)); channel.disconnect(); session.disconnect(); } catch (Exception e) { e.printStackTrace(); } } }
// // Decompiled by Procyon v0.5.36 // package com.ideabus.contec_sdk.code.bean; public class e extends PieceData { }
package com.stackroute.service; import com.mongodb.*; import com.mongodb.client.MongoCollection; import com.stackroute.domain.Questions; import com.stackroute.exceptions.QuestionAlreadyExistsException; import com.stackroute.repository.QuestionRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; @Service public class QuestionServiceImpl implements QuestionService { @Autowired private QuestionRepository questionRepository; @Override public Questions saveQuestion(Questions question) throws QuestionAlreadyExistsException{ BasicDBObject document = new BasicDBObject(); document.put("_id", getNextSequence("questionId")); question.setQuestionId((int)document.get("_id")+1); if(questionRepository.existsById((int)(question.getQuestionId()))) { throw new QuestionAlreadyExistsException("This Question already exists"); } Questions question1 = questionRepository.save(question); return question1; } public static Object getNextSequence(String name){ MongoClient mongoClient = new MongoClient( "localhost" , 27017 ); DB db = mongoClient.getDB("mashup"); DBCollection collection = db.getCollection("counters"); BasicDBObject find = new BasicDBObject(); BasicDBObject update = new BasicDBObject(); update.put("$inc", new BasicDBObject("seq", 1)); DBObject obj = collection.findAndModify(find, update); return obj.get("seq"); } }
import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author lichi */ public class Test { public static void main(String[] args) throws IOException { String msg = Test.check("00930811111"); System.out.print(msg); FileWriter fw = new FileWriter("test.txt"); fw.write(msg); fw.flush(); fw.close(); } private static String check(String input) { String insertCommaToInput = Test.insertCommaToInput(input); int[] intArrayToAccount = Arrays.stream(insertCommaToInput.split(",")).mapToInt(Integer::parseInt).toArray(); String msg = "正確"; String account = input; String[] stringArrayAccount = new String[] {account}; List<String> integerList = new ArrayList<>(); StringBuilder stringBuilder = new StringBuilder(); if ("20".equals(input.substring(3, 5)) || "001".equals(input.substring(0, 3)) || "002".equals(input.substring(0, 3)) || "003".equals(input.substring(0, 3)) || "004".equals(input.substring(0, 3)) || "005".equals(input.substring(0, 3)) || "006".equals(input.substring(0, 3)) || "007".equals(input.substring(0, 3)) || "008".equals(input.substring(0, 3))) { if ("30".equals((input.substring(3, 5))) || "40".equals(input.substring(3, 5)) || "66".equals(input.substring(3, 5))) { account = addZeroForNum(input.substring(5, 11), 11); System.out.println("補0測試" + Test.addZeroForNum(account, 11)); } } else { List<Integer> list = new ArrayList<>(); for (int i = 0; i < intArrayToAccount.length-1; i++) { switch(i) { case 10: case 3: list.add(intArrayToAccount[i] * 2); break; case 9: case 2: list.add(intArrayToAccount[i] * 3); break; case 8: case 1: list.add(intArrayToAccount[i] * 4); break; case 7: case 0: list.add(intArrayToAccount[i] * 5); break; case 6: list.add(intArrayToAccount[i] * 6); break; case 5: list.add(intArrayToAccount[i] * 7); break; case 4: list.add(intArrayToAccount[i] * 8); break; default: System.out.println(list); } } System.out.println(list); } //1. 輸入起始帳號7長度需為11碼。若不是回覆"起始帳號長度錯誤"。 if (input.length() != 11) { msg = "起始帳號長度錯誤"; return msg; } //2. 輸入起始帳號需為數字。若不是回覆"起始帳號需為數字"。 for (int i = input.length(); --i >= 0; ) { if (!Character.isDigit(input.charAt(0))) { msg = "起始帳號需為數字"; return msg; } } //3. 分行別需為001-099,不得為019。若錯誤回覆”分行別錯誤”。 if ("19".equals(input.substring(1, 3)) || !"0".equals(input.substring(0, 1))) { msg = "分行別錯誤"; return msg; } //4. 科目需為10 20 30 40 50 51 66 77。若不是回覆"科目別錯誤”。 if (!"10".equals(input.substring(3, 5)) && !"20".equals(input.substring(3, 5)) && !"30".equals(input.substring(3, 5)) && !"40".equals(input.substring(3, 5)) && !"50".equals(input.substring(3, 5)) && !"51".equals(input.substring(3, 5)) && !"66".equals(input.substring(3, 5)) && !"77".equals(input.substring(3, 5))) { msg = "科目別錯誤"; return msg; } //5. 帳號數為01-9999組。若不是回覆"帳號數錯誤"。 return msg; } /** * 補零 * @param str * @param strLength * @return */ private static String addZeroForNum (String str,int strLength){ int strLen = str.length(); if (strLen < strLength) { while (strLen < strLength) { StringBuffer sb = new StringBuffer(); sb.append("0").append(str); str = sb.toString(); strLen = str.length(); } } return str; } /** * 插入逗號 * @param input * @return */ public static String insertCommaToInput(String input) { StringBuffer sb = new StringBuffer(input); sb.insert(1,","); sb.insert(3,","); sb.insert(5,","); sb.insert(7,","); sb.insert(9,","); sb.insert(11,","); sb.insert(13,","); sb.insert(15,","); sb.insert(17,","); sb.insert(19,","); return sb.toString(); } }
package seven; /** * <li>1. Koncept klase/objekat</li> * <p>OOP -> kreirajući objekte i relacije između </p> * <li>2. Koncepti OOP jezika * <li>2.1 Enkapsulacija</li> * <li>2.2 Apstrakcija</li> * <li>2.3 Nasljeđivanje</li> * <li>2.4 Polimorfizma</li> * </li> */ public class SevenExecutor { public static void main(String[] args) { //p1 -> p1.name = "Adi" Person p1 = new Person("Adi"); p1.setName("Djevojačko Adi"); p1.name = "Djevojačko Adi";//public p1.surname = "Djevojačko Prezime";//paketno p1.weight = 23.0;//protected p1.setAge(17); int godine = p1.getAge(); } }
package Service; import Model.Staff; import Repository.StaffRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import java.util.List; public class StaffServiceIplm implements StaffService { @Autowired StaffRepo staffRepo; @Override public List<Staff> findAll() { return (List<Staff>) staffRepo.findAll(); } @Override public void save(Staff staff) { staffRepo.save(staff); } @Override public void edit(Staff staff) { staffRepo.save(staff); } @Override public void delete(Staff staff) { staffRepo.delete(staff); } @Override public List<Staff> findAllByName(String name) { return staffRepo.fillByName(name); } @Override public Page<Staff> findAllPage(Pageable pageable) { return staffRepo.findAll(pageable); } @Override public Staff findById(long id) { return staffRepo.findById(id).get(); } }
package practico17.PageObject; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.Select; import com.github.javafaker.Faker; public class RegistrationPage extends BasePage{ public RegistrationPage(WebDriver remoteDriver){ driver = remoteDriver; } public void fillRegistrationFields(){ Faker faker = new Faker(); driver.findElement(By.name("UserFirstName")).sendKeys(faker.name().firstName()); driver.findElement(By.name("UserLastName")).sendKeys(faker.name().lastName()); driver.findElement(By.name("UserTitle")).sendKeys(faker.job().title()); driver.findElement(By.name("UserEmail")).sendKeys(faker.internet().emailAddress()); driver.findElement(By.name("UserPhone")).sendKeys(faker.phoneNumber().cellPhone()); driver.findElement(By.name("CompanyName")).sendKeys("Salesforce"); WebElement industryElement = driver.findElement(By.name("Lead.Industry")); Select industrySelect = new Select(industryElement); industrySelect.selectByVisibleText("Otro"); } }
package pl.lodz.uni.math.contactapp; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.net.Uri; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import java.util.HashMap; public class EditContactImage extends AppCompatActivity { private HashMap<String, String> personDataWithIM; private DBTools dbTools = new DBTools(this); private static final int SELECT_PICTURE = 1; private String selectedImagePath = ""; private ImageButton img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_contact_image); personDataWithIM = (HashMap<String, String>) getIntent().getSerializableExtra("personDataWithIM"); String imagePatch = dbTools.getContactImagePatch(personDataWithIM.get("contactId")); img = (ImageButton)findViewById(R.id.editImageButton); if(imagePatch.length() != 0) { img.setImageURI(Uri.parse(imagePatch)); } else { Drawable drawable = getResources().getDrawable(R.drawable.ic_wallpaper_black_48dp); img.setImageDrawable(drawable); } img.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); img.setImageDrawable(null); img.setImageURI(selectedImageUri); } } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } public void editContactSave(View view) { personDataWithIM.put("imageUri", selectedImagePath); dbTools.updateContact(personDataWithIM); startActivity(new Intent(this, Contacts.class)); } public void editContactImageCancel(View view) { final Context context = this; new AlertDialog.Builder(this) .setTitle("Cancel") .setMessage("Are you sure you want to cancel without saving data?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startActivity(new Intent(context, Contacts.class)); } }) .setNegativeButton("No", null) .show(); } }
package lk.egreen.booking.server.dao.impl; import lk.egreen.booking.server.dao.AccountDAOController; import lk.egreen.booking.server.entity.Account; import org.springframework.stereotype.Repository; /** * Created by dew on 2/28/16. */ @Repository public class AccountDAOControllerImpl extends AbstractDAOController<Account, String> implements AccountDAOController { public AccountDAOControllerImpl() { super(Account.class, String.class); } }
package StellarisDK.FileClasses.Helper; import com.sun.javafx.scene.control.skin.LabeledText; import javafx.scene.Node; import javafx.scene.control.*; import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.TransferMode; public class DataCell<T> extends TreeCell<T> { private TextField textField; private Node editor; private static TreeItem cellContent; public DataCell() { super(); setGraphic(new TextField()); this.setOnDragDetected(event -> { TreeItem item = this.getTreeItem(); if (item != null && item.getParent() != null) { Dragboard db = this.startDragAndDrop(TransferMode.MOVE); ClipboardContent clipboard = new ClipboardContent(); clipboard.putString(Integer.toString(item.getParent().getChildren().indexOf(item))); db.setContent(clipboard); event.consume(); } }); this.setOnDragOver(event -> { if (event.getGestureSource() != this) { TreeItem source; TreeItem item = this.getTreeItem(); if (event.getGestureSource() instanceof LabeledText) { source = ((TreeCell) ((Node) event.getGestureSource()).getParent()).getTreeItem(); } else { source = ((TreeCell) event.getGestureSource()).getTreeItem(); } if (source.getParent().equals(item.getParent())) { event.acceptTransferModes(TransferMode.MOVE); } } event.consume(); }); this.setOnDragEntered(event -> { if (event.getGestureSource() != this) { this.updateSelected(true); } event.consume(); }); this.setOnDragExited(event -> { this.updateSelected(false); event.consume(); }); this.setOnDragDropped(event -> { System.out.println("FROM: " + event.getGestureSource()); System.out.println("TO: " + this); TreeItem target = this.getTreeItem(); TreeItem source; if (event.getGestureSource() instanceof LabeledText) { source = ((TreeCell) ((Node) event.getGestureSource()).getParent()).getTreeItem(); } else { source = ((TreeCell) event.getGestureSource()).getTreeItem(); } int index = target.getParent().getChildren().indexOf(target); source.getParent().getChildren().remove(source); if (index == target.getParent().getChildren().size()) { target.getParent().getChildren().add(source); } else { target.getParent().getChildren().add(index, source); } event.setDropCompleted(true); event.consume(); }); this.setOnDragDone(event -> { if (event.getTransferMode() == TransferMode.MOVE) { System.out.println("Done"); } event.consume(); }); setCM(); } @Override public void startEdit() { if ((getItem() instanceof DataEntry)) { if (((DataEntry) getItem()).isEditable()) { startTestEditor(); } } else { startEditor(); } } private void startTestEditor(){ super.startEdit(); if (getItem() instanceof DataEntry && ((DataEntry) getItem()).editor != null) { editor = ((DataEntry) getItem()).editor; setText(((DataEntry) getItem()).getKey() + ": "); setGraphic(editor); setContentDisplay(ContentDisplay.RIGHT); editor.setOnKeyReleased(event -> { if (event.getCode() == KeyCode.ENTER) { commitEdit((T) "test"); } else if (event.getCode() == KeyCode.ESCAPE) { cancelEdit(); } }); } else { if (getItem() instanceof DataEntry && ((DataEntry) getItem()).getValue() != null) { textField = new TextField(((DataEntry) getItem()).getValue().toString()); setText(((DataEntry) getItem()).getKey() + ": "); setContentDisplay(ContentDisplay.RIGHT); } else { textField = new TextField(getItem().toString()); setText(null); } textField.setOnKeyReleased(event -> { if (event.getCode() == KeyCode.ENTER) { commitEdit((T) textField.getText()); } else if (event.getCode() == KeyCode.ESCAPE) { cancelEdit(); } }); setGraphic(textField); } } private void startEditor() { super.startEdit(); if (getItem() instanceof DataEntry && ((DataEntry) getItem()).getValue() != null) { textField = new TextField(((DataEntry) getItem()).getValue().toString()); setText(((DataEntry) getItem()).getKey() + ": "); setContentDisplay(ContentDisplay.RIGHT); } else { textField = new TextField(getItem().toString()); setText(null); } textField.setOnKeyReleased(event -> { if (event.getCode() == KeyCode.ENTER) { commitEdit((T) textField.getText()); } else if (event.getCode() == KeyCode.ESCAPE) { cancelEdit(); } }); setGraphic(textField); textField.selectAll(); } @Override public void commitEdit(T newValue) { System.out.println(getItem().getClass()); if (getItem() instanceof DataEntry && ((DataEntry) getItem()).getValue() != null) { ((DataEntry) getItem()).setValue(newValue); super.commitEdit(getTreeItem().getValue()); } else { super.commitEdit(newValue); } } @Override public void cancelEdit() { super.cancelEdit(); setText(getItem().toString().replaceAll("#tabs", "")); setGraphic(getTreeItem().getGraphic()); } @Override protected void updateItem(T item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); } else { if (isEditing()) { if (textField != null) { textField.setText(getItem().toString().replaceAll("#tabs", "")); } setText(null); setGraphic(textField); } else { if (getItem() == null) { setText("New Item"); } else { setText(getItem().toString().replaceAll("#tabs", "")); } setGraphic(getTreeItem().getGraphic()); } } } public static TreeItem clone(TreeItem items) { TreeItem copy; if (items.getValue() instanceof DataEntry) { copy = new TreeItem<>(((DataEntry) items.getValue()).copy()); } else { copy = new TreeItem<>(items.getValue()); } for (Object item : items.getChildren()) { copy.getChildren().add(clone((TreeItem) item)); } return copy; } private void setCM() { ContextMenu contextMenu = new ContextMenu(); MenuItem createNew = new MenuItem("New.."); createNew.setOnAction(event -> { if (getItem() instanceof DataEntry) { if (!((DataEntry) getItem()).isSingleEntry()) { getTreeItem().getChildren().add(new TreeItem("Click_to_Edit")); } else { getTreeItem().getParent().getChildren().add(new TreeItem("Click_to_Edit")); } } else { getTreeItem().getChildren().add(new TreeItem("Click_to_Edit")); } }); MenuItem edit = new MenuItem("Rename"); edit.setOnAction(event -> { if (((DataEntry) getItem()).isEditable()) { startEdit(); } }); MenuItem delete = new MenuItem("Delete"); delete.setOnAction(event -> { if (getTreeItem().getParent() != null || !((DataEntry) getItem()).isRequired()) getTreeItem().getParent().getChildren().remove(getTreeItem()); }); MenuItem cut = new MenuItem("Cut"); cut.setOnAction(event -> { if(!((DataEntry) getItem()).isRequired()){ cellContent = getTreeItem(); getTreeItem().getParent().getChildren().remove(getTreeItem()); } }); MenuItem copy = new MenuItem("Copy"); copy.setOnAction(event -> { cellContent = clone(getTreeItem()); }); MenuItem paste = new MenuItem("Paste"); paste.setOnAction(event -> { if (getTreeItem().getParent() != null || ((DataEntry) getItem()).isSingleEntry()) getTreeItem().getParent().getChildren().add(clone(cellContent)); else getTreeItem().getChildren().add(clone(cellContent)); }); contextMenu.getItems().addAll(createNew, edit, cut, copy, paste, delete); this.setContextMenu(contextMenu); this.setOnContextMenuRequested(event -> { contextMenu.getItems().clear(); contextMenu.getItems().addAll(createNew, edit, cut, copy, paste, delete); if (this.getTreeItem().getParent() == null) { contextMenu.getItems().removeAll(cut, copy, delete); } if ((getItem() instanceof DataEntry)) { if (((DataEntry) getItem()).isRequired()) { contextMenu.getItems().removeAll(cut, delete); } if (!((DataEntry) getItem()).isEditable()) { contextMenu.getItems().removeAll(edit); } if (((DataEntry) getItem()).isSingleEntry()) { contextMenu.getItems().remove(createNew); } } if (cellContent == null) { paste.setDisable(true); } else { paste.setDisable(false); } }); } }
package cn.rongcapital.mc2.me.ewq.api.dto; public class CampaignQueuePullIn { private String flowId; private String nodeId; public CampaignQueuePullIn() {} public CampaignQueuePullIn(String flowId, String nodeId) { this.flowId = flowId; this.nodeId = nodeId; } public String getFlowId() { return flowId; } public void setFlowId(String flowId) { this.flowId = flowId; } public String getNodeId() { return nodeId; } public void setNodeId(String nodeId) { this.nodeId = nodeId; } }
package me.ivt.com.ui.floatingactionbutton; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.List; import me.ivt.com.ui.R; public class FloatingActionBarActivity extends AppCompatActivity { private ListView mListView; private FloatingActionButton mFloatingbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_floating_action_bar); mListView = (ListView) findViewById(R.id.lv); List<String> mStrings = new ArrayList<>(); for (int i = 'A'; i <= 'Z'; i++) { mStrings.add("当前是数据--------------->" + (char) i); } mListView = (ListView) this.findViewById(R.id.lv); mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings)); mFloatingbar = (FloatingActionButton) findViewById(R.id.floatingbar); } }
package br.com.mixfiscal.prodspedxnfe.services; import br.com.mixfiscal.prodspedxnfe.dao.own.EmpresaDAO; import br.com.mixfiscal.prodspedxnfe.dao.util.ConstroyerHibernateUtil; import br.com.mixfiscal.prodspedxnfe.domain.nfe.ICMS10; import br.com.mixfiscal.prodspedxnfe.domain.nfe.IPI; import br.com.mixfiscal.prodspedxnfe.domain.nfe.NFe; import br.com.mixfiscal.prodspedxnfe.domain.nfe.NFeItem; import br.com.mixfiscal.prodspedxnfe.domain.nfe.PessoaJuridica; import br.com.mixfiscal.prodspedxnfe.domain.own.Empresa; import br.com.mixfiscal.prodspedxnfe.domain.sped.SPEDC100; import br.com.mixfiscal.prodspedxnfe.domain.sped.SPEDC170; import br.com.mixfiscal.prodspedxnfe.domain.sped.SPEDC190; import br.com.mixfiscal.prodspedxnfe.services.MetodosUtil.idxSPEDC170; import java.math.BigDecimal; import java.math.MathContext; import java.util.AbstractList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import java.util.Set; import java.util.function.Predicate; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import static org.junit.Assert.*; public class ProcessadorSPEDTest { SPEDC100 c100 = null; public ProcessadorSPEDTest() {} @Test public void NESTOR_relacionamentoExistente(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\1_RELACIONAMENTO_EXISTENTE\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\1_RELACIONAMENTO_EXISTENTE"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170401132613000145550010003032741207924616"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170401132613000145550010003032741207924616")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,1); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_umParaUm(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\2_UM_PARA_UM\\SpedFiscal_LJ001_0104201707042017.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\2_UM_PARA_UM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170412592243000145550010000005231004000601"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170412592243000145550010000005231004000601")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,2); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_mesmaOrdem(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\3_MESMA_ORDEM\\SpedFiscal_LJ001_0104201707042017.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\3_MESMA_ORDEM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); instance.verificarSeItensEstaoEmOrdem(listaSpedC100, listaNFes); NFe nfe = listaNFes.get("35170308919204000132550010000434641000434643"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170308919204000132550010000434641000434643")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,3); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_ean(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\4_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\4_EAN"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,4); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_eanTrib(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\5_EANTRIB\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\5_EANTRIB"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,5); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_descricaoExata(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\6_DESCRICAO_EXATA\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\6_DESCRICAO_EXATA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,6); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_descricaoProxima(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\7_DESCRICAO_PROXIMA\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\7_DESCRICAO_PROXIMA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_descricaoProximaValor(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\8_DESCRICAO_PROXIMA_VALOR\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\8_DESCRICAO_PROXIMA_VALOR"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); //NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); NFe nfe = listaNFes.get("35170400635244000140550090000127471102534263"); listaSpedC100.stream().forEach((sc100)->{ //if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ if(sc100.getChaveNFe().equals("35170400635244000140550090000127471102534263")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_umParaMuitos(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\8_UM_PRA_MUITOS\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\8_UM_PRA_MUITOS"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NESTOR_lote(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\TESTE_EM_LOTE\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NESTOR\\TESTE_EM_LOTE"); instance.processar(); assertTrue(true); }catch(Exception ex){} } //-------------------------------------------------------------------------------------------- @Test public void NOGUEIRA_relacionamentoExistente(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\1_RELACIONAMENTO_EXISTENTE\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\1_RELACIONAMENTO_EXISTENTE"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170401132613000145550010003032741207924616"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170401132613000145550010003032741207924616")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,1); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_umParaUm(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\2_UM_PARA_UM\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\2_UM_PARA_UM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170396259643000123550010002163411999783650"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170396259643000123550010002163411999783650")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,2); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_mesmaOrdem(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\3_MESMA_ORDEM\\SpedFiscal_LJ001_0104201707042017.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\3_MESMA_ORDEM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); instance.verificarSeItensEstaoEmOrdem(listaSpedC100, listaNFes); NFe nfe = listaNFes.get("35170308919204000132550010000434641000434643"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170308919204000132550010000434641000434643")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,3); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_ean(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\4_EAN\\SPEDFISCAL-LOJA02-03-2017-11-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\4_EAN"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170362190574000127550010000036661000036669"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170362190574000127550010000036661000036669")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,4); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_eanUmParaMuitos(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\4_EAN_UM_PARA_MUITOS\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\4_EAN_UM_PARA_MUITOS"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170307824167000116550010001118961001118965"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170307824167000116550010001118961001118965")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,5); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_eanTrib(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\5_EANTRIB\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\5_EANTRIB"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,5); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_descricaoExata(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\6_DESCRICAO_EXATA\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\6_DESCRICAO_EXATA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,6); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_descricaoProxima(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\7_DESCRICAO_PROXIMA\\SpedFiscal_LJ001_0104201707042017.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\7_DESCRICAO_PROXIMA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_descricaoProximaValor(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\8_DESCRICAO_PROXIMA_VALOR\\SPEDFISCAL-LOJA02-05-2017-11-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\8_DESCRICAO_PROXIMA_VALOR"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); //NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); NFe nfe = listaNFes.get("35170556228356010366550320005911961989166020"); listaSpedC100.stream().forEach((sc100)->{ //if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ if(sc100.getChaveNFe().equals("35170556228356010366550320005911961989166020")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_umParaMuitos(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\10_UM_PRA_MUITOS\\SPEDFISCAL-LOJA02-05-2017-11-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\10_UM_PRA_MUITOS"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170556228356010366550320005911961989166020"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170556228356010366550320005911961989166020")){ c100 = sc100; return; } }); MetodosUtil asserts = new MetodosUtil(); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,10); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_testeUnitario(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("C:\\SPEDS\\TesteUni\\SPEDFISCAL020517.TXT"); instance.setCaminhoDiretorioXmlsNFes("C:\\SPEDS\\TesteUni"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170523444909000134550010000016381000016388"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170523444909000134550010000016381000016388")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,0); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_lote(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); //instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\EXEMPLOS_MAIO\\SPEDFISCAL-LOJA02-05-2017-11-A.TXT"); //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\EXEMPLOS_MAIO"); instance.setCaminhoArquivoSPED("C:\\SPEDS\\SPED\\SPEDFISCAL-LOJA02-05-2017-11-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("C:\\SPEDS\\NFE\\62190574000208\\55 - NF-e\\Autorizada\\Com ciencia"); instance.processar(); assertTrue(true); }catch(Exception ex){} } @Test public void NOGUEIRA_loteUnit(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.setCaminhoArquivoSPED("C:\\SPEDS\\M-Box\\SPED\\SPEDFISCAL020517.TXT"); instance.setCaminhoDiretorioXmlsNFes("C:\\SPEDS\\M-Box\\XML"); instance.processar(); assertTrue(true); }catch(Exception ex){} } //-------------------------------------------------------------------------- @Test public void AEJ_relacionamentoExistente(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\1_RELACIONAMENTO_EXISTENTE\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\1_RELACIONAMENTO_EXISTENTE"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,1); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_umParaUm(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\2_UM_PARA_UM\\SPEDFISCAL-LOJA02-05-2017-10-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\2_UM_PARA_UM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,2); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_mesmaOrdem(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\3_MESMA_ORDEM\\SPEDFISCAL-LOJA02-05-2017-10-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\3_MESMA_ORDEM"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); instance.verificarSeItensEstaoEmOrdem(listaSpedC100, listaNFes); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,3); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_ean(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\4_EAN\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\4_EAN"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,4); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_eanUmParaMuitos(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\4_EAN_UM_PARA_MUITOS\\SPEDFISCAL-LOJA02-05-2017-10-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\4_EAN_UM_PARA_MUITOS"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,5); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_eanTrib(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\5_EANTRIB\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\5_EANTRIB"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,5); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_descricaoExata(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\6_DESCRICAO_EXATA\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\6_DESCRICAO_EXATA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,6); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_descricaoProxima(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\7_DESCRICAO_PROXIMA\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\7_DESCRICAO_PROXIMA"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_descricaoProximaValor(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\8_DESCRICAO_PROXIMA_VALOR\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\8_DESCRICAO_PROXIMA_VALOR"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); //NFe nfe = listaNFes.get("35170331565104029400550010004208761184580814"); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ //if(sc100.getChaveNFe().equals("35170331565104029400550010004208761184580814")){ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,8); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_umParaMuitos(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\10_UM_PRA_MUITOS\\SPEDFISCAL-LOJA02-05-2017-10-A.txt"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\10_UM_PRA_MUITOS"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); MetodosUtil asserts = new MetodosUtil(); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,10); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_testeUnitario(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\9_TESTE_UNITARIO\\SPEDFISCAL-LOJA02-05-2017-10-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\9_TESTE_UNITARIO"); List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); List<NFeItem> itens = new ArrayList<>(); Map<String, NFe> listaNFes = instance.carregarNFes(); NFe nfe = listaNFes.get("35170520321387000195550010000023781052743503"); listaSpedC100.stream().forEach((sc100)->{ if(sc100.getChaveNFe().equals("35170520321387000195550010000023781052743503")){ c100 = sc100; return; } }); if(c100 != null){ try{ instance.identificarItensSpdNFe(c100, nfe,0); //metodo a ser testado }catch(Exception ex){ System.out.println("Erro: " + ex.getMessage()); } } assertTrue(true); }catch(Exception ex){} } @Test public void AEJ_lote(){ try{ ProcessadorSPED instance = new ProcessadorSPED(); //instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\EXEMPLOS_MAIO\\SPEDFISCAL-LOJA02-05-2017-11-A.TXT"); //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\NOGUEIRA\\EXEMPLOS_MAIO"); instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\TESTE_EM_LOTE\\SPEDFISCAL-LOJA02-05-2017-10-A.TXT"); instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\AEJ\\TESTE_EM_LOTE"); instance.processar(); assertTrue(true); }catch(Exception ex){} } //---------------------------------------------------------------------------------------------------------- // @Test // public void testarVinculoPorEAN(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste- Vinculo por EAN -----------------------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\TESTE_MARCELO\\vinculoPorEAN-SPED.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\TESTE_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN"); // // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("00000000000000000000000000000000000000000001"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("00000000000000000000000000000000000000000001")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // // // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testarVinculoPorEANTrib(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste- Vinculo por EAN Trib -----------------------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB\\SpedFiscal_LJ001_0104201707042017.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // // // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testarFiltrosSpedMesmaDecricao(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste POR DESCRIÇAO----------------------------------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\MESMA_DESCRICAO\\SpedFiscal_LJ001_0104201707042017.TXT"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\MESMA_DESCRICAO"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // // //verifica se os itens passado por parametro estao na lista dos que serão relacionados pelo usuario // if(instance.compararItensPreAssociados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens encontrados"); // }else{ // System.out.println("Itens nao encontrados"); // } // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testarFiltrosDescricaoAproximada(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste POR DESCRIÇAO----------------------------------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\MESMA_DESCRICAO\\SpedFiscal_LJ001_0104201707042017.TXT"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\MESMA_DESCRICAO"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // // instance.processar(); // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testarFiltrosRelacionamentoExistente(){ // try{ // ProcessadorSPED instance = new ProcessadorSPED(); // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\RELACIONAMENTO_EXISTENTE\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\RELACIONAMENTO_EXISTENTE"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170256228356010366550320005401501124864338"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170256228356010366550320005401501124864338")){ // c100 = sc100; // return; // } // }); // // if(c100 != null) // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // // // assertTrue(true); // // }catch(Exception ex){} // // } // // @Test // public void testarFiltrosPorValorQuantidade(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste VALOR E QUANTIDADE----------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_VALOR_QUANTIDADE\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_VALOR_QUANTIDADE"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170307824167000116550010001118961001118965"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170307824167000116550010001118961001118965")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // // //verifica se os itens passado por parametro estao na lista dos que serão relacionados pelo usuario // if(instance.compararItensPreAssociados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens encontrados"); // }else{ // System.out.println("Itens nao encontrados"); // } // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // } // // @Test // public void testarEmLote(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // log.info("Inicio do teste- Vinculo por Lote -----------------------------------------------------------"); // ProcessadorSPED instance = new ProcessadorSPED(); // //instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\OFERTAS\\MAJ_Cliente ate 31.TXT"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\OFERTAS"); // //instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\NOGUEIRA\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\NOGUEIRA"); // //instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\MM\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\MM"); // instance.setCaminhoArquivoSPED("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_FINAL_NOGUEIRA\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_FINAL_NOGUEIRA\\xml"); // // // instance.processar(); // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\NOGUEIRA\\SPEDFISCAL-LOJA02-03-2017-11-A.TXT"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\NOGUEIRA"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\MM\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_EM_LOTE\\MM"); // //// //// List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); //// List<NFeItem> itens = new ArrayList<>(); //// Map<String, NFe> listaNFes = instance.carregarNFes(); //// NFe nfe = listaNFes.get("00000000000000000000000000000000000000000001"); //// //// listaSpedC100.stream().forEach((sc100)->{ //// if(sc100.getChaveNFe().equals("00000000000000000000000000000000000000000001")){ //// c100 = sc100; //// System.out.println("Encontrou a nota no sped"); //// return; //// } //// }); //// //// if(c100 != null){ //// try{ //// instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado //// }catch(Exception ex){ //// System.out.println("Erro: " + ex.getMessage()); //// } //// } //// //verifica se os itens passado por parametro estao relacionados //// if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ //// System.out.println("Itens relacionados"); //// }else{ //// System.out.println("Itens não relacionados"); //// } //// // // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testarItensComDoisValoresOuMaisIdenticos(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_VALORES_IDENTICOS\\SpedFiscal_LJ001_0104201707042017.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\TESTE_VALORES_IDENTICOS"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN"); // // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // // } // // @Test // public void testeVaiVerificarPossivelAssociacaoSemPassarPorfiltroAlgum(){ // // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\CHECANDO_FILTRO_SEM_DESCRICAO\\SpedFiscal_LJ001_0104201707042017.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\CHECANDO_FILTRO_SEM_DESCRICAO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN"); // // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170343572270000180550010000058061370543508"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170343572270000180550010000058061370543508")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //verifica se os itens passado por parametro estao relacionados // if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // System.out.println("Itens relacionados"); // }else{ // System.out.println("Itens não relacionados"); // } // assertTrue(true); // log.info("fim do teste----------------------------------------------------------------------"); // }catch(Exception ex){} // } // // @Test // public void testeDescricaoAproximadaValoresIdenticos(){ // try{ // ProcessadorSPED instance = new ProcessadorSPED(); // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\DESCRICAO_APROXIMADA_COM_VALOR_IDENTICO\\SpedFiscal_LJ001_0104201707042017.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\DESCRICAO_APROXIMADA_COM_VALOR_IDENTICO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN"); // // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // System.out.println("Encontrou a nota no sped"); // return; // } // }); // // if(c100 != null){ // try{ // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // }catch(Exception ex){ // System.out.println("Erro: " + ex.getMessage()); // } // } // //instance.processar(); // assertTrue(true); // // }catch(Exception ex){} // } // // @Test // public void testeDescricaoAproximadaValoresST(){ // try{ // Logger log = LogManager.getLogger(ProcessadorSPED.class); // ProcessadorSPED instance = new ProcessadorSPED(); // // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\DESCRICAO_APROXIMADA_COM_VALOR_ST\\SpedFiscal_LJ001_0104201707042017.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\DESCRICAO_APROXIMADA_COM_VALOR_ST"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN_TRIB_MARCELO"); // // //instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN\\SpedFiscal_LJ001_0104201707042017.txt"); // //instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\POR_EAN"); // // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // NFe nfe = listaNFes.get("35170454505052000904550010013363121675825184"); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170454505052000904550010013363121675825184")){ // c100 = sc100; // return; // } // }); // // if(c100 != null) // instance.identificarItensSpdNFe(c100, nfe); //metodo a ser testado // // //verifica se os itens passado por parametro estao relacionados // //if(instance.compararItensRelacionados(c100.getListaSPEDC170().get(0), nfe.getItens().get(0))){ // // System.out.println("Itens relacionados"); // //}else{ // // System.out.println("Itens não relacionados"); // //} // assertTrue(true); // }catch(Exception ex){} // } // // @Test // public void testeAlgoritmoRelacionamentoUmMuitos(){ // try{ // ProcessadorSPED instance = new ProcessadorSPED(); // instance.getLeitorSped().lerArquivoSped("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\RELACIONAMENTO_UM_MUITOS\\SPEDFISCAL-LOJA02-03-2017-11-A.txt"); // instance.setCaminhoDiretorioXmlsNFes("D:\\LULU SOFTWARES\\MIX_FISCAL\\JUNIT_TESTE\\RELACIONAMENTO_UM_MUITOS"); // // List<SPEDC100> listaSpedC100 = instance.getLeitorSped().getListaSPEDC100(); // List<NFeItem> itens = new ArrayList<>(); // Map<String, NFe> listaNFes = instance.carregarNFes(); // // NFe nfe = listaNFes.get("35170307824167000116550010001114411001114412"); // itens = nfe.getItens(); // // listaSpedC100.stream().forEach((sc100)->{ // if(sc100.getChaveNFe().equals("35170307824167000116550010001114411001114412")){ // c100 = sc100; // return; // } // }); // // if(c100 != null){ // instance.identificarItensSpdNFe(c100, nfe); // //// MetodosUtil mUtil = new MetodosUtil(); //// for(SPEDC170 itensCs170 : c100.getListaSPEDC170()){ //// mUtil.identificarCombinacoesPossiveisDoSpedComNfe(itensCs170, itens); //// } //// Optional<Map.Entry<MetodosUtil.idxSPEDC170, List<NFeItem>>> gruposEncontrados = mUtil.getListaDeCombinacoesEncontrados().entrySet().stream().findFirst(); //// if(gruposEncontrados.isPresent()){ //// Map.Entry<MetodosUtil.idxSPEDC170, List<NFeItem>> grupo = gruposEncontrados.get(); //// SPEDC170 sc170 = grupo.getKey().getSped(); //// try{ //// NFeItem[] nfeItem =(NFeItem[]) grupo.getValue().toArray(new NFeItem[grupo.getValue().size()]); //// }catch(Exception ex){ //// System.out.println("---->"+ ex.getMessage()); //// } //// } //// //// System.out.println("---->"+ mUtil.getListaDeCombinacoesEncontrados().keySet().size()); //// mUtil.getListaDeCombinacoesEncontrados().forEach((key,val) ->{ //// //// BigDecimal idx = key.getIndex(); //// SPEDC170 newSped = key.getSped(); //// BigDecimal vBusca = new BigDecimal(8.40).setScale(2,BigDecimal.ROUND_HALF_EVEN); //// //// if(newSped.getValor().compareTo(vBusca)== 0){ //// System.out.println("idx[" + idx + "] produto" + newSped.getSPED0200().getDescrItem() +" a procurar ->" +newSped.getValor()); //// val.forEach(itemNfe ->{ //// System.out.println("--------------------> prod "+itemNfe.getDescricaoProduto() +" encontrados[" + itemNfe.getValorTotal() + "]"); //// }); //// } //// }); // } // // assertTrue(true); // }catch(Exception ex){} // } /* Luiz: Esboço de algoritmo que identifica relacionamento um pra muitos com SPED e XML */ @Test public void testeAlgoritimo(){ //ProcessadorSPED instance = new ProcessadorSPED(); // List<TesteBigDecimal> itensNfe = new ArrayList<>(); // // // itensNfe.add(new TesteBigDecimal(1)); // itensNfe.add(new TesteBigDecimal(4)); // itensNfe.add(new TesteBigDecimal(7)); // itensNfe.add(new TesteBigDecimal(3)); // itensNfe.add(new TesteBigDecimal(5)); // itensNfe.add(new TesteBigDecimal(8)); // itensNfe.add(new TesteBigDecimal(6)); // // algoritimoDeAproximacao(new TesteBigDecimal(4.9),itensNfe); assertTrue(true); } // public void algoritimoDeAproximacao(TesteBigDecimal valor, List<TesteBigDecimal>valores){ // MathContext mc = new MathContext(3); // List<TesteBigDecimal> provaveis = null; // Map<TesteBigDecimal, List<TesteBigDecimal>> ocorrencias = new HashMap<>(); // BigDecimal somatoria = null; // Collections.sort(valores);//ordenar os valores do array do menor para o maior // // for(int i = 0; i < valores.size(); i++){ // provaveis = new ArrayList<>(); // somatoria = valores.get(i); // provaveis.add(valores.get(i)); // // for(int j = 0;j < valores.size() ; j++){ // if(i == j)continue; // ignora a mesma posição do vetor impedindo que o valor do mesmo item seja somado // // somatoria = somatoria.add(valores.get(j)); //somo o valor de j, levando em conta aque ja foi inicializado com valor de i // // //System.out.println("i["+ valores.get(i).round(mc) +"] j[" + valores.get(j).round(mc)+"] = " + somatoria.round(mc)); // // if(somatoria.compareTo(valor) == 0) // { // //guarda os valores percorridos // ocorrencias.put(new TesteBigDecimal(i), provaveis); // break; // } // } // System.out.println("--------------//------------------"); // } // for(Map.Entry<BigDecimal, List<BigDecimal>> oc : ocorrencias.entrySet()){ // System.out.println("Ocorrencia ["+oc.getKey() +"]"); // for(BigDecimal e : oc.getValue()){ // System.out.println( " Itens ->" + e); // } // } // } // public void testOrden(TesteBigDecimal valor, List<TesteBigDecimal>valores){ // //ordenando os valor // // for(int i = 0; i < valores.size(); i++){ // System.out.println("antes -->" + valores.get(i)); // } // // try{ // Collections.sort(valores); // }catch(Exception ex){ // System.out.println("EX -->" + ex); // } // for(int i = 0; i < valores.size(); i++){ // System.out.println("depois -->" + valores.get(i)); // } // } // @Test public void testarArray (){ List<BigDecimal> valores = new ArrayList<>(); for(int i=1; i<=5;i++){ valores.add(new BigDecimal(i)); } MetodosUtil asserts = new MetodosUtil(); // asserts.identificarCombinacoesPossiveisDoSpedComNfe(new BigDecimal(6), valores); // for(Map.Entry<BigDecimal,List<BigDecimal>> valor : asserts.getListaDeCombinacoesEncontrados().entrySet()) // { // System.out.println("Chave :" + valor.getKey()); // for(BigDecimal vl : valor.getValue()){ // System.out.println(" -> valores :" + vl); // } // } asserts.getListaDeCombinacoesEncontrados().forEach((v, vls) ->{ System.out.println(" Pos" + v); vls.forEach(vs ->{ System.out.println(" valor" + vs); }); }); // asserts.listaDeCombinacoesEncontrados // // .forEach(valor -> // { // System.out.println(valor); // }); // // System.out.print("Aqui é o count ---->"+ valores.size()); assertTrue(true); } @Test public void testeListaGenerica(){ List<SPEDC170> list170 = new ArrayList<SPEDC170>(); List<SPEDC190> list190 = new ArrayList<SPEDC190>(); SPEDC170 spdc170 = new SPEDC170(); spdc170.setCFOP("123456"); list170.add(spdc170); testListGeneric(list170); SPEDC190 spdc190 = new SPEDC190(); spdc190.setCFOP("456789"); list190.add(spdc190); testListGeneric(list190); assertTrue(true); } @Test public void testarCrudEmpresa(){ Empresa empresa = new Empresa(); EmpresaDAO empresaDao = new EmpresaDAO(); empresa.setCnpj("62.190.574/0002-08"); try{ ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction().begin(); empresa = empresaDao.selecionarUm(empresa); System.out.println("empresa ----> " + empresa.getNome()); ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction().commit(); }catch(Exception ex){ ConstroyerHibernateUtil.getSessionFactory().getCurrentSession().beginTransaction().rollback(); System.out.println("" + ex.getMessage()); } } public void testListGeneric(List<? super SPEDC190>list){ for(Object l : list){ if(l instanceof SPEDC190){ SPEDC190 item = (SPEDC190)l; System.out.println("-->"+item.getCFOP()); }else if(l instanceof SPEDC170){ SPEDC170 item = (SPEDC170)l; System.out.println("-->"+item.getCFOP()); } } } }
package mandelbrot.gui; // @author Raphaël import geometry.StraightRectangle; import java.awt.Dimension; import java.awt.GraphicsDevice; import java.lang.reflect.Field; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import mandelbrot.controller.Controller; public class ProGUI extends javax.swing.JFrame { public static final String GO_TO_OPTION = "GO_TO_OPTION", ITERATIONS_OPTION = "ITERATIONS_OPTION", COLORS_OPTION = "COLORS_OPTION", SCREENSHOT_OPTION = "SCREENSHOT_OPTION", BROWSE_SCREENSHOT_FOLDER = "BROWSE_SCREENSHOT_FOLDER", VALIDATE_GO_TO = "VALIDATE_GO_TO", VALIDATE_ITERATIONS = "VALIDATE_ITERATIONS", VALIDATE_COLORS = "VALIDATE_COLORS", VALIDATE_SCREENSHOT = "VALIDATE_SCREENSHOT"; private final Controller controller; public ProGUI(Controller controller) { this.controller = controller; initComponents(); addWindowListener(controller); try { for(Field field : getClass().getDeclaredFields()) { if(field.getGenericType() == javax.swing.JButton.class) { ((javax.swing.JButton)field.get(this)).addActionListener(controller); } } } catch(IllegalArgumentException | IllegalAccessException ex) { Logger.getLogger(ProGUI.class.getName()).log(Level.SEVERE, null, ex); } ((ColorGradientChooser)colorComp1GradientChooser).setTranslatable(true); ((ColorGradientChooser)colorComp1GradientChooser).setScalable(true); ((ColorGradientChooser)colorComp1GradientChooser).addCurveListener(controller); ((ColorGradientChooser)colorComp2GradientChooser).addCurveListener(controller); ((ColorGradientChooser)colorComp3GradientChooser).addCurveListener(controller); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { tabbedPanes = new javax.swing.JTabbedPane(); explorationToolBar = new javax.swing.JPanel(); goToButton = new javax.swing.JButton(); iterationsButton = new javax.swing.JButton(); colorsButton = new javax.swing.JButton(); screenshotButton = new javax.swing.JButton(); simulationToolBar = new javax.swing.JPanel(); optionPanes = new javax.swing.JPanel(); goToOptionPane = new javax.swing.JPanel(); xTextField = new javax.swing.JTextField(); yTextField = new javax.swing.JTextField(); zoomTextField = new javax.swing.JTextField(); zoomLabel = new javax.swing.JLabel(); yLabel = new javax.swing.JLabel(); xLabel = new javax.swing.JLabel(); validateGoToButton = new javax.swing.JButton(); iterationsOptionPane = new javax.swing.JPanel(); iterationsTextField = new javax.swing.JTextField(); iterationsLabel = new javax.swing.JLabel(); estimatedTimeLabel1 = new javax.swing.JLabel(); estimatedTimeLabel2 = new javax.swing.JLabel(); validateIterationsButton = new javax.swing.JButton(); colorsOptionPane = new javax.swing.JPanel(); colorComp1GradientChooser = new mandelbrot.gui.ColorGradientChooser(controller.getPalette().getComp1Function(), controller.getPalette().isRGBMode() ? mandelbrot.config.color.ColorPalette.ColorComponent.red : mandelbrot.config.color.ColorPalette.ColorComponent.hue); colorComp2GradientChooser = new mandelbrot.gui.ColorGradientChooser(controller.getPalette().getComp2Function(), controller.getPalette().isRGBMode() ? mandelbrot.config.color.ColorPalette.ColorComponent.green : mandelbrot.config.color.ColorPalette.ColorComponent.saturation); colorComp3GradientChooser = new mandelbrot.gui.ColorGradientChooser(controller.getPalette().getComp3Function(), controller.getPalette().isRGBMode() ? mandelbrot.config.color.ColorPalette.ColorComponent.blue : mandelbrot.config.color.ColorPalette.ColorComponent.brightness); colorGradientViewer = new javax.swing.JPanel(); screenshotOptionPane = new javax.swing.JPanel(); lastScreenshotDisplayer = new ImageDisplayer(controller, Controller.LAST_SCREENSHOT_FIELD_NAME); validateScreenshotButton = new javax.swing.JButton(); screenshotFolderBrowserButton = new javax.swing.JButton(); screenshotFolderLabel = new javax.swing.JLabel(); overviewPane = new javax.swing.JPanel(); proMainViewer = new ProMainViewer(controller); statusBar = new javax.swing.JPanel(); progressBar = new javax.swing.JProgressBar(); infoLabel = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setExtendedState(javax.swing.JFrame.MAXIMIZED_BOTH); setMinimumSize(new java.awt.Dimension(640, 480)); goToButton.setText("Aller à"); goToButton.setActionCommand(GO_TO_OPTION); goToButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goToButtonActionPerformed(evt); } }); iterationsButton.setText("Itérations"); iterationsButton.setActionCommand(ITERATIONS_OPTION); colorsButton.setText("Couleurs"); colorsButton.setActionCommand(COLORS_OPTION); screenshotButton.setText("Capture"); screenshotButton.setActionCommand(SCREENSHOT_OPTION); javax.swing.GroupLayout explorationToolBarLayout = new javax.swing.GroupLayout(explorationToolBar); explorationToolBar.setLayout(explorationToolBarLayout); explorationToolBarLayout.setHorizontalGroup( explorationToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(explorationToolBarLayout.createSequentialGroup() .addContainerGap() .addComponent(goToButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(iterationsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(colorsButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(screenshotButton) .addGap(0, 541, Short.MAX_VALUE)) ); explorationToolBarLayout.setVerticalGroup( explorationToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(explorationToolBarLayout.createSequentialGroup() .addContainerGap() .addGroup(explorationToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(goToButton) .addComponent(iterationsButton) .addComponent(colorsButton) .addComponent(screenshotButton)) .addContainerGap()) ); tabbedPanes.addTab("Exploration", explorationToolBar); javax.swing.GroupLayout simulationToolBarLayout = new javax.swing.GroupLayout(simulationToolBar); simulationToolBar.setLayout(simulationToolBarLayout); simulationToolBarLayout.setHorizontalGroup( simulationToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 857, Short.MAX_VALUE) ); simulationToolBarLayout.setVerticalGroup( simulationToolBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 45, Short.MAX_VALUE) ); tabbedPanes.addTab("Simulation", simulationToolBar); optionPanes.setLayout(new java.awt.CardLayout()); goToOptionPane.setBackground(new java.awt.Color(51, 255, 204)); xTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT); xTextField.setText(Double.toString(util.MoreMath.round(controller.getExploRenderer().getCurrentFrame().getCenter().getX(), 10))); yTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT); yTextField.setText(Double.toString(util.MoreMath.round(controller.getExploRenderer().getCurrentFrame().getCenter().getY(), 10))); zoomTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT); zoomTextField.setText(Double.toString(util.MoreMath.round(controller.getExploRenderer().getCurrentFrame().getZoom(), 10))); zoomLabel.setText("zoom :"); yLabel.setText("y :"); xLabel.setText("x :"); validateGoToButton.setText("Aller"); validateGoToButton.setActionCommand(VALIDATE_GO_TO); javax.swing.GroupLayout goToOptionPaneLayout = new javax.swing.GroupLayout(goToOptionPane); goToOptionPane.setLayout(goToOptionPaneLayout); goToOptionPaneLayout.setHorizontalGroup( goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(goToOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(goToOptionPaneLayout.createSequentialGroup() .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(zoomLabel) .addComponent(yLabel) .addComponent(xLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(xTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE) .addComponent(yTextField) .addComponent(zoomTextField))) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, goToOptionPaneLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(validateGoToButton))) .addContainerGap()) ); goToOptionPaneLayout.setVerticalGroup( goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(goToOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(xTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(xLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(yTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(yLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(goToOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(zoomTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(zoomLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 246, Short.MAX_VALUE) .addComponent(validateGoToButton) .addContainerGap()) ); optionPanes.add(goToOptionPane, "GO_TO_OPTION"); iterationsOptionPane.setBackground(new java.awt.Color(204, 255, 51)); iterationsTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT); iterationsTextField.setText(Integer.toString(Controller.DEFAULT_MAX_ITER)); iterationsLabel.setText("<html>Nombre<br>&nbsp;&nbsp;d'itérations :</html>"); estimatedTimeLabel1.setText("<html>Temps de<br>calcul estimé :</html>"); estimatedTimeLabel2.setText("0.01 s"); validateIterationsButton.setText("Regénérer"); validateIterationsButton.setActionCommand(VALIDATE_ITERATIONS); javax.swing.GroupLayout iterationsOptionPaneLayout = new javax.swing.GroupLayout(iterationsOptionPane); iterationsOptionPane.setLayout(iterationsOptionPaneLayout); iterationsOptionPaneLayout.setHorizontalGroup( iterationsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(iterationsOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(iterationsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(iterationsOptionPaneLayout.createSequentialGroup() .addComponent(iterationsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(iterationsTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 110, Short.MAX_VALUE)) .addGroup(iterationsOptionPaneLayout.createSequentialGroup() .addComponent(estimatedTimeLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(estimatedTimeLabel2) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, iterationsOptionPaneLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(validateIterationsButton))) .addContainerGap()) ); iterationsOptionPaneLayout.setVerticalGroup( iterationsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(iterationsOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(iterationsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(iterationsLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(iterationsTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(iterationsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(estimatedTimeLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(estimatedTimeLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 256, Short.MAX_VALUE) .addComponent(validateIterationsButton) .addContainerGap()) ); optionPanes.add(iterationsOptionPane, "ITERATIONS_OPTION"); colorsOptionPane.setBackground(new java.awt.Color(102, 102, 255)); colorComp1GradientChooser.setBackground(new java.awt.Color(255, 255, 0)); javax.swing.GroupLayout colorComp1GradientChooserLayout = new javax.swing.GroupLayout(colorComp1GradientChooser); colorComp1GradientChooser.setLayout(colorComp1GradientChooserLayout); colorComp1GradientChooserLayout.setHorizontalGroup( colorComp1GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 180, Short.MAX_VALUE) ); colorComp1GradientChooserLayout.setVerticalGroup( colorComp1GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 96, Short.MAX_VALUE) ); colorComp2GradientChooser.setBackground(new java.awt.Color(255, 255, 0)); javax.swing.GroupLayout colorComp2GradientChooserLayout = new javax.swing.GroupLayout(colorComp2GradientChooser); colorComp2GradientChooser.setLayout(colorComp2GradientChooserLayout); colorComp2GradientChooserLayout.setHorizontalGroup( colorComp2GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); colorComp2GradientChooserLayout.setVerticalGroup( colorComp2GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); colorComp3GradientChooser.setBackground(new java.awt.Color(255, 255, 0)); javax.swing.GroupLayout colorComp3GradientChooserLayout = new javax.swing.GroupLayout(colorComp3GradientChooser); colorComp3GradientChooser.setLayout(colorComp3GradientChooserLayout); colorComp3GradientChooserLayout.setHorizontalGroup( colorComp3GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); colorComp3GradientChooserLayout.setVerticalGroup( colorComp3GradientChooserLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); colorGradientViewer.setBackground(new java.awt.Color(153, 153, 255)); javax.swing.GroupLayout colorGradientViewerLayout = new javax.swing.GroupLayout(colorGradientViewer); colorGradientViewer.setLayout(colorGradientViewerLayout); colorGradientViewerLayout.setHorizontalGroup( colorGradientViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); colorGradientViewerLayout.setVerticalGroup( colorGradientViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); javax.swing.GroupLayout colorsOptionPaneLayout = new javax.swing.GroupLayout(colorsOptionPane); colorsOptionPane.setLayout(colorsOptionPaneLayout); colorsOptionPaneLayout.setHorizontalGroup( colorsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(colorsOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(colorsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(colorComp1GradientChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(colorComp2GradientChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(colorComp3GradientChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(colorGradientViewer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); colorsOptionPaneLayout.setVerticalGroup( colorsOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(colorsOptionPaneLayout.createSequentialGroup() .addContainerGap() .addComponent(colorComp1GradientChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(colorComp2GradientChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(colorComp3GradientChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(colorGradientViewer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); optionPanes.add(colorsOptionPane, "COLORS_OPTION"); screenshotOptionPane.setBackground(new java.awt.Color(102, 255, 102)); javax.swing.GroupLayout lastScreenshotDisplayerLayout = new javax.swing.GroupLayout(lastScreenshotDisplayer); lastScreenshotDisplayer.setLayout(lastScreenshotDisplayerLayout); lastScreenshotDisplayerLayout.setHorizontalGroup( lastScreenshotDisplayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); lastScreenshotDisplayerLayout.setVerticalGroup( lastScreenshotDisplayerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 138, Short.MAX_VALUE) ); validateScreenshotButton.setText("Sauvegarder capture"); validateScreenshotButton.setActionCommand(VALIDATE_SCREENSHOT); screenshotFolderBrowserButton.setText("Choisir dossier"); screenshotFolderBrowserButton.setActionCommand(BROWSE_SCREENSHOT_FOLDER); screenshotFolderLabel.setText("Dossier actuel : " + controller.getScreenshotFolder()); javax.swing.GroupLayout screenshotOptionPaneLayout = new javax.swing.GroupLayout(screenshotOptionPane); screenshotOptionPane.setLayout(screenshotOptionPaneLayout); screenshotOptionPaneLayout.setHorizontalGroup( screenshotOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(screenshotOptionPaneLayout.createSequentialGroup() .addContainerGap() .addGroup(screenshotOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lastScreenshotDisplayer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, screenshotOptionPaneLayout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(validateScreenshotButton)) .addGroup(screenshotOptionPaneLayout.createSequentialGroup() .addGroup(screenshotOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(screenshotFolderBrowserButton) .addComponent(screenshotFolderLabel)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); screenshotOptionPaneLayout.setVerticalGroup( screenshotOptionPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(screenshotOptionPaneLayout.createSequentialGroup() .addContainerGap() .addComponent(lastScreenshotDisplayer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(screenshotFolderBrowserButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(screenshotFolderLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(validateScreenshotButton) .addContainerGap()) ); optionPanes.add(screenshotOptionPane, "SCREENSHOT_OPTION"); overviewPane.setBackground(new java.awt.Color(255, 102, 102)); javax.swing.GroupLayout overviewPaneLayout = new javax.swing.GroupLayout(overviewPane); overviewPane.setLayout(overviewPaneLayout); overviewPaneLayout.setHorizontalGroup( overviewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); overviewPaneLayout.setVerticalGroup( overviewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 122, Short.MAX_VALUE) ); proMainViewer.setBackground(new java.awt.Color(153, 255, 153)); javax.swing.GroupLayout proMainViewerLayout = new javax.swing.GroupLayout(proMainViewer); proMainViewer.setLayout(proMainViewerLayout); proMainViewerLayout.setHorizontalGroup( proMainViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); proMainViewerLayout.setVerticalGroup( proMainViewerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 0, Short.MAX_VALUE) ); statusBar.setBackground(new java.awt.Color(153, 153, 255)); infoLabel.setEditable(false); javax.swing.GroupLayout statusBarLayout = new javax.swing.GroupLayout(statusBar); statusBar.setLayout(statusBarLayout); statusBarLayout.setHorizontalGroup( statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(statusBarLayout.createSequentialGroup() .addContainerGap() .addComponent(infoLabel) .addGap(18, 18, 18) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); statusBarLayout.setVerticalGroup( statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusBarLayout.createSequentialGroup() .addContainerGap(16, Short.MAX_VALUE) .addGroup(statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(infoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(tabbedPanes) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(overviewPane, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(optionPanes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(proMainViewer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(statusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(5, 5, 5) .addComponent(tabbedPanes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(optionPanes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(overviewPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(proMainViewer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(statusBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void goToButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goToButtonActionPerformed // TODO add your handling code here: }//GEN-LAST:event_goToButtonActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel colorComp1GradientChooser; private javax.swing.JPanel colorComp2GradientChooser; private javax.swing.JPanel colorComp3GradientChooser; private javax.swing.JPanel colorGradientViewer; private javax.swing.JButton colorsButton; private javax.swing.JPanel colorsOptionPane; private javax.swing.JLabel estimatedTimeLabel1; private javax.swing.JLabel estimatedTimeLabel2; private javax.swing.JPanel explorationToolBar; private javax.swing.JButton goToButton; private javax.swing.JPanel goToOptionPane; private javax.swing.JTextField infoLabel; private javax.swing.JButton iterationsButton; private javax.swing.JLabel iterationsLabel; private javax.swing.JPanel iterationsOptionPane; private javax.swing.JTextField iterationsTextField; private javax.swing.JPanel lastScreenshotDisplayer; private javax.swing.JPanel optionPanes; private javax.swing.JPanel overviewPane; private javax.swing.JPanel proMainViewer; private javax.swing.JProgressBar progressBar; private javax.swing.JButton screenshotButton; private javax.swing.JButton screenshotFolderBrowserButton; private javax.swing.JLabel screenshotFolderLabel; private javax.swing.JPanel screenshotOptionPane; private javax.swing.JPanel simulationToolBar; private javax.swing.JPanel statusBar; private javax.swing.JTabbedPane tabbedPanes; private javax.swing.JButton validateGoToButton; private javax.swing.JButton validateIterationsButton; private javax.swing.JButton validateScreenshotButton; private javax.swing.JLabel xLabel; private javax.swing.JTextField xTextField; private javax.swing.JLabel yLabel; private javax.swing.JTextField yTextField; private javax.swing.JLabel zoomLabel; private javax.swing.JTextField zoomTextField; // End of variables declaration//GEN-END:variables public Controller getController() { return controller; } public JButton getColorsButton() { return colorsButton; } public JPanel getColorsOptionPane() { return colorsOptionPane; } public JLabel getEstimatedTimeLabel1() { return estimatedTimeLabel1; } public JLabel getEstimatedTimeLabel2() { return estimatedTimeLabel2; } public JPanel getExplorationToolBar() { return explorationToolBar; } public JButton getGoToButton() { return goToButton; } public JPanel getGoToOptionPane() { return goToOptionPane; } public JButton getIterationsButton() { return iterationsButton; } public JLabel getIterationsLabel() { return iterationsLabel; } public JPanel getIterationsOptionPane() { return iterationsOptionPane; } public JTextField getIterationsTextField() { return iterationsTextField; } public JPanel getOptionPanes() { return optionPanes; } public JPanel getOverviewPane() { return overviewPane; } public ProMainViewer getProMainViewer() { return (ProMainViewer)proMainViewer; } public JPanel getSimulationToolBar() { return simulationToolBar; } public JTabbedPane getTabbedPanes() { return tabbedPanes; } public JButton getValidateGoToButton() { return validateGoToButton; } public JButton getValidateIterationsButton() { return validateIterationsButton; } public JLabel getxLabel() { return xLabel; } public JTextField getxTextField() { return xTextField; } public JLabel getyLabel() { return yLabel; } public JTextField getyTextField() { return yTextField; } public JLabel getZoomLabel() { return zoomLabel; } public JTextField getZoomTextField() { return zoomTextField; } public JPanel getLastScreenshotDisplayer() { return lastScreenshotDisplayer; } public JButton getScreenshotButton() { return screenshotButton; } public JButton getScreenshotFolderBrowserButton() { return screenshotFolderBrowserButton; } public JLabel getScreenshotFolderLabel() { return screenshotFolderLabel; } public JPanel getScreenshotOptionPane() { return screenshotOptionPane; } public JButton getValidateScreenshotButton() { return validateScreenshotButton; } public ColorGradientChooser getColorComp1GradientChooser() { return (ColorGradientChooser)colorComp1GradientChooser; } public ColorGradientChooser getColorComp2GradientChooser() { return (ColorGradientChooser)colorComp2GradientChooser; } public ColorGradientChooser getColorComp3GradientChooser() { return (ColorGradientChooser)colorComp3GradientChooser; } public JTextField getInfoLabel() { return infoLabel; } public JPanel getjPanel1() { return statusBar; } public JProgressBar getProgressBar() { return progressBar; } public JPanel getColorGradientViewer() { return colorGradientViewer; } /*public CurveScroller getCurveEditor() { return (CurveScroller)curveEditor; }*/ }
package com.example.hp.googlebooks; import android.app.DownloadManager; import android.app.LoaderManager; import android.content.Context; import android.content.Intent; import android.content.Loader; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class Home extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Book>> { private static final int INITIAL_LOADER_ID = 1; /** URL used to fetch latest published books (max 10) as default list view items */ private static final String INITIAL_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=2018&orderBy=newest&langRestrict=en&maxResults=10"; /** Initial part of the url used when a search query is entered */ private static final String SEARCH_QUERY_URL = "https://www.googleapis.com/books/v1/volumes?"; /** This variable will contain the url that the loader will pass to asyncTask */ String QUERY; /** Holds the boolean value for if the device is connected to a network or not*/ boolean isConnected; ArrayList<Book> Books; EditText searchQuery; ListView booksList; BooksListCustomAdapter booksListCustomAdapter; LinearLayout emptyView, noConnectionView; ProgressBar loadingIndicator; ImageButton searchBtn; EditText search_query; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); showCursorOnTouch(); // References to UI elements. loadingIndicator = (ProgressBar) findViewById(R.id.loading_indicator); booksList = (ListView) findViewById(R.id.booksList); noConnectionView = (LinearLayout) findViewById(R.id.noConnectionView); emptyView = (LinearLayout) findViewById(R.id.emptyView); // Call the function to check internet connectivity // now this variable holds the network state of the device isConnected = checkInternetConnectivity(); // Setup the list view with an empty adapter until the data is fetched booksListCustomAdapter = new BooksListCustomAdapter(new ArrayList<Book>(), getApplicationContext()); booksList.setAdapter(booksListCustomAdapter); // Open the web page of the book when it's list item is clicked booksList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { String url = booksListCustomAdapter.getItem(i).getUrl(); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } }); // Get a reference to the LoaderManager, in order to interact with loaders. LoaderManager loaderManager = getLoaderManager(); // Initialize the loader. QUERY = INITIAL_REQUEST_URL; loaderManager.initLoader(INITIAL_LOADER_ID, null, this); // When the search button is clicked, a new query should be issued searchBtn = (ImageButton) findViewById(R.id.search_btn); searchBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { search_query = (EditText) findViewById(R.id.search_query); Uri baseUri = Uri.parse(SEARCH_QUERY_URL); Uri.Builder uriBuilder = baseUri.buildUpon(); uriBuilder.appendQueryParameter("q", search_query.getText().toString()); uriBuilder.appendQueryParameter("orderBy","newest"); QUERY = uriBuilder.toString(); getLoaderManager().restartLoader(INITIAL_LOADER_ID, null, Home.this); } }); } /** * This manages the search edit text, as it shouldn't show any blinking cursor * at first, the cursor should show along with the keyboard once the edit text is tapped. */ private void showCursorOnTouch() { searchQuery = (EditText) findViewById(R.id.search_query); searchQuery.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { searchQuery.setCursorVisible(true); return false; } }); } @Override public Loader<List<Book>> onCreateLoader(int i, Bundle bundle) { // Create a new loader for the given URL return new BookLoader(this, QUERY); } @Override public void onLoadFinished(Loader<List<Book>> loader, List<Book> Books) { // Stop the loading indicator once the loading is finished so we can show either the list or the empty state loadingIndicator.setVisibility(View.GONE); isConnected = checkInternetConnectivity(); noConnectionView.setVisibility(View.GONE); emptyView.setVisibility(View.GONE); if (isConnected == false) { booksList.setEmptyView(noConnectionView); } else { booksList.setEmptyView(emptyView); } // Clear the adapter of previous book data and load new data booksListCustomAdapter.clear(); // If there is a valid list of {@link Earthquake}s, then add them to the adapter's // data set. This will trigger the ListView to update. if (Books != null && !Books.isEmpty()) { booksListCustomAdapter.addAll(Books); } } @Override public void onLoaderReset(Loader<List<Book>> loader) { // Loader reset, so we can clear out our existing data. booksListCustomAdapter.clear(); } /** * Returns the state of device's network connectivity */ boolean checkInternetConnectivity() { ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean connection = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return connection; } }
package by.htp.count05.main; public class CounterLogic { public void decreaseCount(Counter counter) { int count = counter.getCount(); while (count > counter.getMin()) { count--; } counter.setCount(count); } public void increaseCount(Counter counter) { int count = counter.getCount(); while (count < counter.getMax()) { count++; } counter.setCount(count); } public int currentCount(Counter counter) { return counter.getCount(); } }
package com.javatunes.web; import java.io.File; import java.io.FileNotFoundException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Scanner; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.javatunes.data.CrudeDAO; import com.javatunes.data.ItemDAO; import com.javatunes.data.TransactionDAO; import com.javatunes.data.UserDAO; import com.javatunes.domain.Cart; import com.javatunes.domain.MusicItem; import com.javatunes.domain.Transaction; import com.javatunes.domain.User; import com.javatunes.persist.XMLDBLocation; import com.javatunes.util.GVColumnModel; import com.javatunes.util.JSGridView; @Controller @RequestMapping("/rest") public class RestfulController { private static class NameValue { private final String name; private final Double value; public static Comparator<NameValue> comparator = new Comparator<RestfulController.NameValue>() { @Override public int compare(final NameValue o1, final NameValue o2) { return o1.getName().compareTo(o2.getName()); } }; public NameValue(final String name, final String value) { this.name = name; this.value = Double.parseDouble(value); } public String getName() { return this.name; } public Double getValue() { return this.value; } } @Autowired private UserDAO userDAO; @Autowired private TransactionDAO transDAO; @Autowired @Qualifier("cart") private CrudeDAO<Cart, String> cartDAO; @Autowired private ItemDAO itemDAO; @Autowired private ReloadableResourceBundleMessageSource messageSource; @RequestMapping(value = "/getGrid/{userName}/{transID}", method = RequestMethod.GET) @ResponseBody public Object getGridView(final HttpServletRequest request, @PathVariable("userName") final String name, @PathVariable("transID") final long transID) { System.out.println(name); final User u = this.userDAO.getByID(name); final List<Transaction> transactions = this.transDAO.getTransactionForUsers(name); int index = 0; for (int x = 0; x < transactions.size(); x++) { if (transactions.get(x).getId() == transID) { index = x; } } final Transaction t = transactions.get(index); final List<MusicItem> list = t.getCart().getContents(); final int rows = list.size(); final int cols = 6; final ArrayList<GVColumnModel> columns = new ArrayList<GVColumnModel>(); final String[][] data = new String[rows][cols]; final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); for (int x = 0; x < cols; x++) { final GVColumnModel gvcm = new GVColumnModel(); gvcm.setText(this.messageSource.getMessage("col" + x, null, request.getLocale())); columns.add(gvcm); } for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { String val = ""; switch (y) { case 0: val = Long.toString(list.get(x).getId()); break; case 1: val = list.get(x).getTitle(); break; case 2: val = list.get(x).getArtist(); break; case 3: val = sdf.format(list.get(x).getReleaseDate()); break; case 4: val = Double.toString(list.get(x).getListPrice()); break; case 5: val = Double.toString(list.get(x).getPrice()); break; } data[x][y] = val; } } return new JSGridView(columns, data); } @RequestMapping(value = "/cart/{userName}", method = RequestMethod.GET) @ResponseBody public Object getGridViewCart(final HttpServletRequest request, @PathVariable("userName") final String name) { final Cart c = this.cartDAO.getByID(name); final List<MusicItem> list = c.getContents(); final int rows = list.size(); final int cols = 6; final ArrayList<GVColumnModel> columns = new ArrayList<GVColumnModel>(); final String[][] data = new String[rows][cols]; final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); for (int x = 0; x < cols; x++) { final GVColumnModel gvcm = new GVColumnModel(); gvcm.setText(this.messageSource.getMessage("col" + x, null, request.getLocale())); columns.add(gvcm); } for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { String val = ""; switch (y) { case 0: val = Long.toString(list.get(x).getId()); break; case 1: val = list.get(x).getTitle(); break; case 2: val = list.get(x).getArtist(); break; case 3: val = sdf.format(list.get(x).getReleaseDate()); break; case 4: val = Double.toString(list.get(x).getListPrice()); break; case 5: val = Double.toString(list.get(x).getPrice()); break; } data[x][y] = val; } } return new JSGridView(columns, data); } @RequestMapping(value = "/getMusicItems") @ResponseBody public Object getMusicItems(final HttpServletRequest request) { final List<MusicItem> list = this.itemDAO.getAll(); final int rows = list.size(); final int cols = 6; final ArrayList<GVColumnModel> columns = new ArrayList<GVColumnModel>(); final String[][] data = new String[rows][cols]; final SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); for (int x = 0; x < cols; x++) { final GVColumnModel gvcm = new GVColumnModel(); gvcm.setText(this.messageSource.getMessage("col" + x, null, request.getLocale())); columns.add(gvcm); } for (int x = 0; x < rows; x++) { for (int y = 0; y < cols; y++) { String val = ""; switch (y) { case 0: val = Long.toString(list.get(x).getId()); break; case 1: val = list.get(x).getTitle(); break; case 2: val = list.get(x).getArtist(); break; case 3: val = sdf.format(list.get(x).getReleaseDate()); break; case 4: val = Double.toString(list.get(x).getListPrice()); break; case 5: val = Double.toString(list.get(x).getPrice()); break; } data[x][y] = val; } } return new JSGridView(columns, data); } @RequestMapping(value = "/add/{numbers}") @ResponseBody public Object getRemoveCart(@PathVariable("numbers") final String numbers) { System.out.println(numbers); return true; } @RequestMapping(value = "/cart/remove/{userName}/{index}") @ResponseBody public Object getRemoveCart(@PathVariable("userName") final String user, @PathVariable("index") final int index) { // cartDAO.removeItem(user, index); return true; } @RequestMapping(value = "/transactions/{userName}", method = RequestMethod.GET) @ResponseBody public Object getTransactions(@PathVariable("userName") final String name) { final List<Transaction> t = this.transDAO.getTransactionForUsers(name); return t; } @RequestMapping(value = "/getStateAndTaxes", method = RequestMethod.GET) @ResponseBody public Object isUserNameAvailable() throws FileNotFoundException { final Scanner s = new Scanner(new File(XMLDBLocation.root + "\\taxes.csv")); final ArrayList<NameValue> hm = new ArrayList<RestfulController.NameValue>(); s.nextLine(); while (s.hasNext()) { final String line = s.nextLine(); final String[] parts = line.split(","); hm.add(new NameValue(parts[0], parts[1])); } return hm; } @RequestMapping(value = "/isUserNameAvailable/{userName}", method = RequestMethod.GET) @ResponseBody public Object isUserNameAvailable(@PathVariable("userName") String userName) { System.out.println(userName); userName = userName.replace('|', '.'); try { Thread.sleep(5000); } catch (final InterruptedException e) { e.printStackTrace(); } final Boolean b = this.userDAO.getByID(userName) == null; return b; } }
package com.saechimdaeki.chap07; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.net.URI; @RestController @RequiredArgsConstructor @Slf4j public class SpringItemController { private final AmqpTemplate template; @PostMapping("/items") Mono<ResponseEntity<?>> addNewItemUsingSpringAmqp(@RequestBody Mono<Item> item){ return item.subscribeOn(Schedulers.boundedElastic()) .flatMap(content -> { return Mono.fromCallable( () -> { this.template.convertAndSend( "hacking-spring-boot", "new-items-spring-amqp",content ); return ResponseEntity.created(URI.create("/items")).build(); }); }); } }
package com.example.demo.moduls.redis.service.impl; import com.example.demo.moduls.redis.service.RedisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; @Service public class RedisServiceImpl implements RedisService { @Autowired RedisTemplate redisTemplate; @Override public void addString(String key, String value) { redisTemplate.opsForValue().set(key,value); } @Override public boolean deleteString(String key) { return redisTemplate.delete(key); } }
/** * 湖北安式软件有限公司 * Hubei Anssy Software Co., Ltd. * FILENAME : PartnershipIdVo.java * PACKAGE : com.anssy.inter.team.vo * CREATE DATE : 2016-8-23 * AUTHOR : make it * MODIFIED BY : * DESCRIPTION : */ package com.anssy.inter.team.vo; /** * @author make it * @version SVN #V1# #2016-8-23# * 合伙辅助类 */ public class PartnershipIdVo { /** * 合伙ID */ private Long partnershipId; public Long getPartnershipId() { return partnershipId; } public void setPartnershipId(Long partnershipId) { this.partnershipId = partnershipId; } }
package frc.robot; public class RobotState{ private static RobotState m_robotstate = null; private RobotState(){ } public State m_state = null; public static RobotState getInstance(){ if(m_robotstate == null) m_robotstate = new RobotState(); return m_robotstate; } public void setState(State state){ m_state = state; } public State state(){ return m_state; } public enum State{ GRAB_CELL, PASSTHROUGH, SHOOT, EJECT, WAITING, SCORE, REVERSE_ALL, REVERSE_INTAKE, SPIN, COLOR_SELECT; } }
package artronics.gsdwn.networkMap; import artronics.gsdwn.helper.FakePacketFactory; import artronics.gsdwn.node.SdwnNode; import artronics.gsdwn.packet.Packet; import org.junit.Before; import org.junit.Test; import java.util.concurrent.BlockingQueue; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; public class NetworkMapUpdaterTest { NetworkMap networkMap = new SdwnNetworkMap(); BlockingQueue<Packet> queue; //It always return a fixed number for weight WeightCalculator weightCalculator = new FixedWeightCalculator(100.0); FakePacketFactory factory = new FakePacketFactory(); NetworkMapUpdater mapUpdater = new NetworkMapUpdater(networkMap, weightCalculator); // NetworkMapUpdater mapUpdater; Thread updater = new Thread(mapUpdater); SdwnNode node0 = new SdwnNode(0); SdwnNode node30 = new SdwnNode(30); SdwnNode node35 = new SdwnNode(35); SdwnNode node36 = new SdwnNode(36); SdwnNode node37 = new SdwnNode(37); SdwnNode node40 = new SdwnNode(40); @Before public void setUp() throws Exception { queue = mapUpdater.getPacketQueue(); } @Test public void it_should_create_a_graph_with_report_packet() throws InterruptedException { Packet packet = factory.createReportPacket(); queue.add(packet); updater.start(); Thread.sleep(200); NetworkMap expMap = getDefaultNetworkMap(); assertMapEqual(expMap, networkMap); //it should not contain destination node assertFalse(networkMap.contains(node0)); } /* After sending default packet we send another which says node 35 is connected to 36. This report is from 35 to 0 and neighbors are 30 and 36 */ @Test public void it_should_add_nodes_to_current_graph() throws InterruptedException { Packet packet = factory.createReportPacket(); Packet packet2 = factory.createReportPacket(35, 0, factory.createNeighbors(30, 36)); queue.add(packet); queue.add(packet2); updater.start(); Thread.sleep(300); NetworkMap expMap = getDefaultNetworkMap(); expMap.addLink(node35, node36, 87); assertMapEqual(expMap, networkMap); } /* Now we introduce a new node to network by node 37. The address is 40. */ @Test public void it_should_add_new_nodes_with_report() throws InterruptedException { Packet packet = factory.createReportPacket(); Packet packet2 = factory.createReportPacket(37, 0, factory.createNeighbors(30, 40)); queue.add(packet); queue.add(packet2); updater.start(); Thread.sleep(300); NetworkMap expMap = getDefaultNetworkMap(); expMap.addNode(node40); expMap.addLink(node37, node40, 87); assertMapEqual(expMap, networkMap); } /* Now by sending some reports we add nodes and links Then by sending other reports we simulate the situation where a nodes looses its links but it's not island yet */ @Test public void it_should_remove_links_and_not_nodes() throws InterruptedException { Packet packet = factory.createReportPacket(); Packet packet2 = factory.createReportPacket(35, 0, factory.createNeighbors(30, 36)); Packet packet3 = factory.createReportPacket(37, 0, factory.createNeighbors(30, 40)); //Now 35 drops its link from 36 and create a link with 37 and 40 Packet packet4 = factory.createReportPacket(35, 0, factory.createNeighbors(30, 37, 40)); queue.add(packet); queue.add(packet2); queue.add(packet3); queue.add(packet4); updater.start(); Thread.sleep(500); NetworkMap expMap = getDefaultNetworkMap(); expMap.addNode(node40); expMap.addLink(node37, node40, 87); expMap.addLink(node35, node37, 87); expMap.addLink(node35, node40, 87); assertMapEqual(expMap, networkMap); } @Test public void it_should_detect_island_node_and_remove_it() throws InterruptedException { Packet packet = factory.createReportPacket(); Packet packet2 = factory.createReportPacket(30, 0, factory.createNeighbors(35, 36)); queue.add(packet); queue.add(packet2); updater.start(); Thread.sleep(300); NetworkMap expMap = getDefaultNetworkMap(); expMap.removeNode(node37); assertMapEqual(expMap, networkMap); } /* It is not possible for the network to have unconnected graph however, at the beginning of network formation it's likely to receive packets from different parts of the network. */ @Test public void it_should_create_a_not_connected_graph() throws InterruptedException { Packet packet = factory.createReportPacket(); Packet packet2 = factory.createReportPacket(40, 0, factory.createNeighbors(41)); queue.add(packet); queue.add(packet2); updater.start(); Thread.sleep(300); NetworkMap expMap = getDefaultNetworkMap(); SdwnNode node41 = new SdwnNode(41); expMap.addNode(node40); expMap.addNode(node41); expMap.addLink(node40, node41, 65); assertMapEqual(expMap, networkMap); } private void assertMapEqual(NetworkMap exp, NetworkMap act) { assertEquals(exp.getNetworkGraph().vertexSet(), act.getNetworkGraph().vertexSet()); //I use toString because actual equal override is considered as weighted //however here i do not consider weigh of each link //For this to work you should construct your link exactly in order assertEquals(exp.getNetworkGraph().edgeSet().toString(), act.getNetworkGraph().edgeSet().toString()); } //this returns a netMap correspond to default ReportPacket //which FakePacketFactory produces private NetworkMap getDefaultNetworkMap() { NetworkMap expMap = new SdwnNetworkMap(); expMap.addNode(node30); expMap.addNode(node35); expMap.addNode(node36); expMap.addNode(node37); expMap.addLink(node30, node35, 45); expMap.addLink(node30, node36, 45); expMap.addLink(node30, node37, 45); return expMap; } }
package com.jic.libin.leaderus.study007; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; import java.util.stream.Collectors; /** * Created by andylee on 17/1/26. */ public class BinleeStudy00702 { public static void main(String[] args) throws IOException { String filePath = "/Users/andylee/IdeaProject/LeaderUS-Study/src"; List<File> files = new ArrayList<>(); SimpleFileVisitor<Path> finder = new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { String fileName = file.toFile().getName(); if(fileName.endsWith(".java")) files.add(file.toFile()); return super.visitFile(file, attrs); } }; Files.walkFileTree(Paths.get(filePath),finder); System.out.println(files.size()); ForkJoinPool pool = new ForkJoinPool(Runtime.getRuntime().availableProcessors()); List<SerachResult> searchResults = pool.invoke(new ForkJoinWordCount(files,"name")); Integer countSum = searchResults .parallelStream() .reduce(0, (sum, p) -> { return sum += p.getCount(); }, (sum1, sum2) -> { return sum1 + sum2; }); searchResults.stream().filter(s -> s.getCount()>0).sorted((a,b) -> Integer.compare(b.getCount(),a.getCount())).limit(searchResults.size()) .forEachOrdered(System.out::println); System.out.println(countSum); } private static class ForkJoinWordCount extends RecursiveTask<List<SerachResult>>{ private List<File> files; private String token; public ForkJoinWordCount(List<File> files, String token) { this.files = files; this.token = token; } @Override protected List<SerachResult> compute() { if(files.size()==1) { List<SerachResult> results = new ArrayList<>(); File file = files.get(0); SerachResult serachResult = new SerachResult(token,0,file.getAbsolutePath()); try { List<String> strings = Files.readAllLines(Paths.get(file.getAbsolutePath())); strings.stream().forEach(s -> { String[] stringTokenizer = s.split(token); if(stringTokenizer.length>1) serachResult.setCount(serachResult.getCount()+stringTokenizer.length-1); }); } catch (IOException e) { e.printStackTrace(); } results.add(serachResult); return results; } else { List<RecursiveTask> subTasks = createSubTasks(); for (RecursiveTask subTask : subTasks) subTask.fork(); List<SerachResult> results = new ArrayList<>(); for (RecursiveTask subTask : subTasks) { List<SerachResult> subList = (List<SerachResult>) subTask.join(); results.addAll(subList); } return results; } } private List<RecursiveTask> createSubTasks() { List<RecursiveTask> subTasks = new ArrayList<>(); int mid = files.size() / 2; RecursiveTask<List<SerachResult>> subTasks1 = new ForkJoinWordCount(files.subList(0, mid),token); RecursiveTask<List<SerachResult>> subTasks2 = new ForkJoinWordCount(files.subList(mid, files.size()),token); subTasks.add(subTasks1); subTasks.add(subTasks2); return subTasks; } } }
package com.gaoshin.amazon; import com.gaoshin.dao.jpa.DaoComponent; public interface AwsDao extends DaoComponent { }
import java.util.Scanner; public class Yunsuan { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); System.out.println("تلبًa:"); int a = scanner.nextInt(); System.out.println("تلبًb:"); int b = scanner.nextInt(); if (a%b==0||a+b>1000) { System.out.println("a:"+a); } else System.out.println("a:"+b); } }
package com.bupsolutions.polaritydetection.ml; import com.bupsolutions.polaritydetection.model.Polarity; public interface PolarityModel extends ClassificationModel<Polarity> { void handleNegations(boolean flag); }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.alipay.sofa.registry.server.data; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.alipay.remoting.Connection; import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.RegisterVersion; import com.alipay.sofa.registry.common.model.dataserver.Datum; import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.alipay.sofa.registry.common.model.slot.Slot; import com.alipay.sofa.registry.common.model.slot.SlotAccess; import com.alipay.sofa.registry.common.model.slot.SlotConfig; import com.alipay.sofa.registry.common.model.slot.func.SlotFunctionRegistry; import com.alipay.sofa.registry.common.model.store.DataInfo; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.remoting.bolt.BoltChannel; import com.alipay.sofa.registry.server.data.bootstrap.CommonConfig; import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.server.data.cache.LocalDatumStorage; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.task.FastRejectedExecutionException; import com.alipay.sofa.registry.task.KeyedThreadPoolExecutor; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.netty.channel.Channel; import io.netty.util.Attribute; import io.netty.util.AttributeKey; import java.net.InetSocketAddress; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import org.junit.Assert; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public final class TestBaseUtils { private static final AtomicLong REGISTER_ID_SEQ = new AtomicLong(); private static final AtomicLong CLIENT_VERSION = new AtomicLong(); public static final String TEST_DATA_ID = "testDataId"; public static final String TEST_DATA_INFO_ID; private static final String TEST_REGISTER_ID = "testRegisterId"; private static final AtomicLong DATA_ID_SEQ = new AtomicLong(); static { Publisher p = TestBaseUtils.createTestPublisher(TEST_DATA_ID); TEST_DATA_INFO_ID = p.getDataInfoId(); } private TestBaseUtils() {} public static Publisher createTestPublisher(String dataId) { Publisher publisher = new Publisher(); DataInfo dataInfo = DataInfo.valueOf(DataInfo.toDataInfoId(dataId, "I", "G")); publisher.setDataInfoId(dataInfo.getDataInfoId()); publisher.setDataId(dataInfo.getDataId()); publisher.setInstanceId(dataInfo.getInstanceId()); publisher.setGroup(dataInfo.getGroup()); publisher.setRegisterId(TEST_REGISTER_ID + REGISTER_ID_SEQ.incrementAndGet()); publisher.setSessionProcessId(ServerEnv.PROCESS_ID); publisher.setRegisterTimestamp(System.currentTimeMillis()); publisher.setVersion(100 + CLIENT_VERSION.incrementAndGet()); ConnectId connectId = ConnectId.of( ServerEnv.PROCESS_ID.getHostAddress() + ":9999", ServerEnv.PROCESS_ID.getHostAddress() + ":9998"); publisher.setSourceAddress(URL.valueOf(connectId.clientAddress())); publisher.setTargetAddress(URL.valueOf(connectId.sessionAddress())); return publisher; } public static Publisher cloneBase(Publisher publisher) { Publisher clone = TestBaseUtils.createTestPublisher(publisher.getDataId()); clone.setRegisterId(publisher.getRegisterId()); clone.setVersion(publisher.getVersion()); clone.setRegisterTimestamp(publisher.getRegisterTimestamp()); clone.setSessionProcessId(publisher.getSessionProcessId()); return clone; } public static void assertEquals(Datum datum, Publisher publisher) { Assert.assertEquals(publisher.getDataInfoId(), datum.getDataInfoId()); Assert.assertEquals(publisher.getDataId(), datum.getDataId()); Assert.assertEquals(publisher.getInstanceId(), datum.getInstanceId()); Assert.assertEquals(publisher.getGroup(), datum.getGroup()); Assert.assertTrue(datum.getPubMap().containsKey(publisher.getRegisterId())); } public static ConnectId notExistConnectId() { return ConnectId.of("notExist:9999", "notExist:9998"); } public static LocalDatumStorage newLocalStorage(String dataCenter, boolean init) { DataServerConfig dataServerConfig = newDataConfig(dataCenter); LocalDatumStorage storage = new LocalDatumStorage(); storage.setDataServerConfig(dataServerConfig); if (init) { for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { storage.getSlotChangeListener().onSlotAdd(i, Slot.Role.Leader); } } return storage; } public static DataServerConfig newDataConfig(String dataCenter) { CommonConfig commonConfig = mock(CommonConfig.class); when(commonConfig.getLocalDataCenter()).thenReturn(dataCenter); return new DataServerConfig(commonConfig); } public static DatumCache newLocalDatumCache(String localDataCenter, boolean init) { DatumCache cache = new DatumCache(); LocalDatumStorage storage = TestBaseUtils.newLocalStorage(localDataCenter, init); cache.setLocalDatumStorage(storage); cache.setDataServerConfig(storage.getDataServerConfig()); return cache; } public static DatumSummary newDatumSummary(int pubCount) { final String dataId = TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet(); return newDatumSummary(pubCount, dataId); } public static DatumSummary newDatumSummary(int pubCount, String dataInfoId) { Map<String, RegisterVersion> versions = Maps.newHashMap(); for (int i = 0; i < pubCount; i++) { final String registerId = TEST_REGISTER_ID + "-" + REGISTER_ID_SEQ.incrementAndGet(); versions.put( registerId, RegisterVersion.of(CLIENT_VERSION.incrementAndGet(), System.currentTimeMillis())); } return new DatumSummary(dataInfoId, versions); } public static List<Publisher> createTestPublishers(int slotId, int count) { List<Publisher> list = Lists.newArrayListWithCapacity(count); for (int i = 0; i < Integer.MAX_VALUE; i++) { Publisher p = createTestPublisher(TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet() + "-" + i); int id = SlotFunctionRegistry.getFunc().slotOf(p.getDataInfoId()); if (id == slotId) { // find the slotId list.add(p); for (int j = 1; j < count; j++) { list.add(createTestPublisher(p.getDataId())); } break; } } return list; } public static MockBlotChannel newChannel(int localPort, String remoteAddress, int remotePort) { return new MockBlotChannel(localPort, remoteAddress, remotePort); } public static final class MockBlotChannel extends BoltChannel { final InetSocketAddress remote; final InetSocketAddress local; public volatile boolean connected = true; private final AtomicBoolean active = new AtomicBoolean(true); public final Connection conn; public MockBlotChannel(int localPort, String remoteAddress, int remotePort) { super(new Connection(createChn())); this.conn = getConnection(); this.local = new InetSocketAddress(ServerEnv.IP, localPort); this.remote = new InetSocketAddress(remoteAddress, remotePort); Channel chn = conn.getChannel(); Mockito.when(chn.remoteAddress()).thenReturn(remote); Mockito.when(chn.isActive()) .thenAnswer( new Answer<Boolean>() { public Boolean answer(InvocationOnMock var1) throws Throwable { return active.get(); } }); } private static Channel createChn() { Channel chn = Mockito.mock(io.netty.channel.Channel.class); Mockito.when(chn.attr(Mockito.any(AttributeKey.class))) .thenReturn(Mockito.mock(Attribute.class)); return chn; } @Override public InetSocketAddress getRemoteAddress() { return remote; } @Override public InetSocketAddress getLocalAddress() { return local; } @Override public boolean isConnected() { return active.get(); } public void setActive(boolean b) { active.set(b); } } public static SlotAccess moved() { return new SlotAccess(1, 1, SlotAccess.Status.Moved, 1); } public static SlotAccess accept() { return accept(1, 1, 1); } public static SlotAccess accept(int slotId, long tableEpoch, long leaderEpoch) { return new SlotAccess(slotId, 1, SlotAccess.Status.Accept, leaderEpoch); } public static SlotAccess migrating() { return migrating(1, 1, 1); } public static SlotAccess migrating(int slotId, long tableEpoch, long leaderEpoch) { return new SlotAccess(slotId, 1, SlotAccess.Status.Migrating, leaderEpoch); } public static SlotAccess misMatch() { return new SlotAccess(1, 1, SlotAccess.Status.MisMatch, 1); } public static void assertException(Class<? extends Throwable> eclazz, Runnable runnable) { try { runnable.run(); Assert.fail("except exception"); } catch (Throwable exception) { Assert.assertEquals(exception.getClass(), eclazz); } } public static KeyedThreadPoolExecutor rejectExecutor() { KeyedThreadPoolExecutor executor = Mockito.mock(KeyedThreadPoolExecutor.class); Mockito.when(executor.execute(Mockito.anyObject(), Mockito.anyObject())) .thenThrow(new FastRejectedExecutionException("reject")); return executor; } }
/** * <p>Package contains classes of JTS3ServerQuery Library.</p> * <p>You can visit <a href="https://www.stefan1200.de/forum/index.php?topic=10.0">HERE</a> for more information!</p> */ package de.stefan1200.jts3serverquery;
package com.github.ytjojo.supernestedlayout.demo.nobehavior; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.github.ytjojo.supernestedlayout.demo.R; /** * Created by Administrator on 2017/7/14 0014. */ public class SimpleActivty extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_simple); findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent= new Intent(SimpleActivty.this,SimpleRefreshHeaderActivity.class); startActivity(intent); } }); } }
package com.git.cloud.request.dao.impl; import com.git.cloud.common.dao.CommonDAOImpl; import com.git.cloud.request.dao.IVirtualExtendDAO; /** * 虚机扩容临时类 * @author huangrongsheng * @version 1.0 2014-9-9 * @see */ public class VirtualExtendDAOImpl extends CommonDAOImpl implements IVirtualExtendDAO{ }
package com.wrathOfLoD.Models.Entity; import com.wrathOfLoD.Models.Commands.ActionCommand; import com.wrathOfLoD.Models.Commands.ActionCommandVendor; import com.wrathOfLoD.Models.Commands.EntityActionCommands.DieCommand; import com.wrathOfLoD.Models.Commands.EntityActionCommands.DropItemCommand; import com.wrathOfLoD.Models.Entity.Character.Character; import com.wrathOfLoD.Models.Entity.EntityCanMoveVisitor.TerrestrialCanMoveVisitor; import com.wrathOfLoD.Models.Entity.EntityCanMoveVisitor.CanMoveVisitor; import com.wrathOfLoD.Models.Inventory.Inventory; import com.wrathOfLoD.Models.Items.TakeableItem; import com.wrathOfLoD.Models.LocationTracker.LocationTrackerManager; import com.wrathOfLoD.Models.Map.Map; import com.wrathOfLoD.Models.Map.MapArea; import com.wrathOfLoD.Models.Stats.Stats; import com.wrathOfLoD.Models.Stats.StatsModifiable; import com.wrathOfLoD.Models.Target.NPCTargetManager; import com.wrathOfLoD.Models.Target.TargetManager; import com.wrathOfLoD.Observers.ModelObservers.EntityObservable; import com.wrathOfLoD.Observers.ModelObservers.EntityObserver; import com.wrathOfLoD.Utility.Direction; import com.wrathOfLoD.Utility.Position; import com.wrathOfLoD.VisitorInterfaces.EntityVisitor; import java.util.ArrayList; import java.util.Iterator; /** * Created by zach on 4/7/16. */ public abstract class Entity implements EntityObservable{ private TargetManager targetManager = new NPCTargetManager(); private String name; private Position position; private Stats stats; private Direction direction; private Inventory inventory; private boolean isActive = false; private ArrayList<EntityObserver> entityObservers; private CanMoveVisitor canMoveVisitor; private boolean isDead; /** * aggroLevel is 0 for non aggressive entities * 1 for aggressive ones */ private int aggroLevel = 0; //TODO: change the default can move visitor to an instance of DefaultCanMoveVisitor or something public Entity(){ this("Master Chief", new Position(0,0,0,0), new TerrestrialCanMoveVisitor()); } public Entity(String name, Position position, CanMoveVisitor canMoveVisitor){ this.name = name; this.position = position; this.inventory = new Inventory(); this.stats = new Stats(this); this.direction = Direction.DOWN_SOUTH; entityObservers = new ArrayList<>(); this.canMoveVisitor = canMoveVisitor; } /***** getter & setter for Entity *******/ public Direction getDirection(){return this.direction; } public Inventory getInventory(){ return this.inventory; } public String getName() { return this.name; } public Position getPosition() { return this.position; } public Stats getStats() { return this.stats; } public void setActive(){ isActive = true; } public void setInactive(){ isActive = false; } public void setDirection(Direction newDirection){ this.direction = newDirection; } public void setPosition(Position newPosition){ hideTiles(); this.position = newPosition; showTiles(); } protected void setName(String name){ this.name = name; } public CanMoveVisitor getCanMoveVisitor() { return canMoveVisitor; } public void setCanMoveVisitor(CanMoveVisitor canMoveVisitor) { this.canMoveVisitor = canMoveVisitor; } /********* END Getters and Setters *********/ public void move(Direction movingDirection){ if(!isActive()){ setActive(); ActionCommand acm = ActionCommandVendor.createMovementCommand(this, movingDirection); //TODO: may need command's execute to return ticks to set entity inActive and not to notify observer acm.execute(); } } public void fly(Direction movingDirection){ if(!isActive()){ setActive(); ActionCommand acm = ActionCommandVendor.createFlyCommand(this, movingDirection); //TODO: may need command's execute to return ticks to set entity inActive and not to notify observer acm.execute(); } } public abstract void hideTiles(); public abstract void showTiles(); public void insertItemToInventory(TakeableItem item){ this.inventory.addItem(item); } //drops item to map by calling dropItemCommand public void dropItem(TakeableItem item){ if(inventory.hasItem(item)){ inventory.removeItem(item); ActionCommand dropItemCommand = new DropItemCommand(this,item); dropItemCommand.execute(); } } public void heal(int healAmount){ stats.modifyStats(StatsModifiable.createHealthStatsModifiable(healAmount)); } public void takeDamage(int damageAmount){ stats.modifyStats(StatsModifiable.createHealthStatsModifiable(-damageAmount)); } public void loseMana(int mana){ stats.modifyStats(StatsModifiable.createManaStatsModifiable(-mana)); } public void doInteraction(Character character) { //the entity starts the interaction //what is an interaction? } public void gainExp(int exp) { StatsModifiable expStats = StatsModifiable.createExperienceStatsModifiable(exp); getStats().modifyStats(expStats); } public void levelUp() { //// TODO: check if this is correct!!! } public void die(){ ActionCommand dieCommand = new DieCommand(this); dieCommand.execute(); notifyObserversOnDie(this.getPosition()); this.setActive(); // System.out.println("LIFES LIVE: "+ getStats().getLivesLeft()); // if(getStats().getLivesLeft() > 0) { // respawn(); // } entityObservers.clear(); } public boolean isActive() { return isActive; } public void accept(EntityVisitor ev){ ev.visitEntity(this); } public TargetManager getTargetManager() { return targetManager; } protected void setTargetManager(TargetManager t){ targetManager = t; } public Iterator<EntityObserver> getEntityObservers(){ return entityObservers.iterator(); } @Override public void registerObserver(EntityObserver eo) { entityObservers.add(eo); } @Override public void deregisterObserver(EntityObserver eo) { entityObservers.remove(eo); } //TODO: not sure if this is good public void notifyObserverOnMove(Position src, Position dest, Direction dir, int ticks) { for (EntityObserver eo : entityObservers) { eo.notifyMove(src, dest, dir, ticks); } } public void notifyObsersersOnDirectionChange(Direction dir) { for (EntityObserver eo: entityObservers) eo.notifyDirectionChange(dir); } public void notifyObserversOnDie(Position position){ for(int i = 0; i < entityObservers.size(); i++){ entityObservers.get(i).notifyDie(position); } } public void notifyObserverOnAtt(){ for(int i = 0; i < entityObservers.size(); i++){ entityObservers.get(i).notifyAttack(); } } public void notifyObserverDoneAtt(){ for(int i = 0; i < entityObservers.size(); i++){ entityObservers.get(i).notifyDoneAttack(); } } public void setAggroLevel(int aggro){ this.aggroLevel = aggro; } public int getAggroLevel(){ return aggroLevel; } public void respawn(){ StatsModifiable modifiable = StatsModifiable.createHealthManaStatsModifiable(getStats().getMaxMana(), getStats().getMaxHealth()); getStats().modifyStats(modifiable); notifyObserverOnMove(this.getPosition(), Map.getInstance().getActiveMapArea().getSpawnPoint(), direction, 0); this.setPosition(Map.getInstance().getActiveMapArea().getSpawnPoint()); //LocationTrackerManager.getInstance().registerEntity(this); System.out.println("GESTS CLLLAFED??"); } public boolean isDead() { return isDead; } public void setDead(boolean dead) { isDead = dead; } public void changeMovementSpeed(StatsModifiable mooveModifiable){ getStats().modifyStats(mooveModifiable); } }
package pl.seafta.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.factory.PasswordEncoderFactories; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration public class PasswordEncoderConf { @Bean public PasswordEncoder passwordEncoder() { return PasswordEncoderFactories.createDelegatingPasswordEncoder(); } }
package com.example.in28mins.first.web; @WebServlet(urlPatterns ="/login.do") public class LoginServlet extends HttpServlet{ private UserValidationService service = new UserValidationService service(); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{ request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward( request,response); ) } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{ String name = request.getParameter("name") String password = request.getParameter("password)" boolean isUserValid = service.isUserValid(name,password); if(isUserValid) {request.setAttribute("name", name); request.setAttribute("password", password); request.getRequestDispatcher("/WEB-INF/views/welcome.jsp").forward( request,response); ) } else { request.setAttribute("errorMessage", "invalidCreds") request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward( request,response); } } }
package model; import java.awt.Image; import javax.swing.ImageIcon; /** * Class Rock * @author Group6 * */ public class Rock extends GraphicElements { private int i=1; /** * Instantiates a rock * @param x * @param y */ public Rock(int x, int y) { super(32,32, x, y); super.icoObject= new ImageIcon(getClass().getResource("/images/roche.png")); super.imgObject= this.icoObject.getImage(); } public Rock() {} @Override public Image shine() { if((i==1)||(i>1 && i<4)) { this.setIcoObject(new ImageIcon(getClass().getResource("/images/roche"+i+".png"))); this.setImgObject(this.getIcoObject().getImage()); i++; }else { i=1; this.setIcoObject(new ImageIcon(getClass().getResource("/images/roche"+i+".png"))); this.setImgObject(this.getIcoObject().getImage()); } return this.getImgObject(); } }
package com.romitus; public interface Atacar { public void atacarPersonaje(Personajes p1); }
package com.gaoshin.top.plugin.dialer; import android.view.View; import com.gaoshin.top.ShortcutEditActivity; public class CallShortcutEditActivity extends ShortcutEditActivity { private CallShortcutEditor editor; protected View getEditor() { editor = new CallShortcutEditor(this); editor.setValue(shortcut.getData()); return editor; } protected void save() { String phone = editor.getValue(); shortcut.setData(phone); super.save(); } }
package com.ds.assignment2.app.dsAs2.Repositories; import com.ds.assignment2.app.dsAs2.Model.Item; import org.springframework.data.mongodb.repository.MongoRepository; public interface ItemRepository extends MongoRepository<Item, Integer> { }
package com.dgt.tools.dgtviewer.model; import java.util.Iterator; /** * * @author Wayssen */ public interface MachineModelAccesor { Iterator<MachineModel> getMachineModelIterator(); }
package com.role.game.constants; public class RolePlayingGameConstants { public static final String TAB = "\t"; public static final String SEPARATOR = ": "; public static final String OPTION_SELECT = "Please choose one of the below options:"; public static final String INVALID_OPTION = "Sorry the option you have selected is invalid"; public static final String NO_OPTION_SELECTED = "Sorry, seems like you haven't selected any of the option or system might not have recognised you command"; public static final String NAME_QUESTION = "What is your name?"; public static final String GENDER = "What is your gender?"; public static final String ABOUT = "Tell about yourself"; public static final int ATTACK_POWER = 10; public static final int DEFAULT_HEALTH = 100; public static final String WELCOME_MESSAGE = "Welcome to the world of shdow fights"; public static final String MISSION_WELCOME_MESSAGE = "I hope u will enjoy battling with the enemies.Explore and attack the enemies with full power"; public static final String MAP_INFO_DETAILS = "E - Enemy at this location " + "\n" + "P - This is your location"; public static final String GAME_SAVED = "Your game has been saved successfully"; public static final String XAXIS = "Xaxis"; public static final String YAXIS = "Yaxis"; }
package br.com.lucro.manager.model; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.persistence.UniqueConstraint; /** * The persistent class for the file_tivit_cielo_outstanding_balance_by_flag database table. * */ @Entity @Table( name="file_tivit_cielo_outstanding_balance_by_flag", uniqueConstraints=@UniqueConstraint(columnNames={"reference_date", "platform_type", "card_flag_id"}) ) @NamedQuery(name="FileOutstandingBalanceByFlagCielo.findAll", query="SELECT f FROM FileOutstandingBalanceByFlagCielo f") public class FileOutstandingBalanceByFlagCielo implements Serializable { private static final long serialVersionUID = 1L; @Id @SequenceGenerator(name="FILE_TIVIT_CIELO_OUTSTANDING_BALANCE_BY_FLAG_ID_GENERATOR", sequenceName="FILE_TIVIT_CIELO_OUTSTANDING_BALANCE_BY_FLAG_ID_SEQ", initialValue=1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="FILE_TIVIT_CIELO_OUTSTANDING_BALANCE_BY_FLAG_ID_GENERATOR") private Long id; @Column(name="anticipated_value") private Double anticipatedValue; @Column(name="branches_size") private Integer branchesSize; @Column(name="card_flag_id") private Integer cardFlagId; @Column(name="ceded_value") private Double cededValue; @Column(name="establishment_number") private String establishmentNumber; @Column(name="gross_value") private Double grossValue; @ManyToOne @JoinColumn(name="header_id", nullable=false, insertable=true) private FileHeaderCielo header; @Column(name="net_value") private Double netValue; @Column(name="platform_type") private String platformType; @Temporal(TemporalType.DATE) @Column(name="reference_date") private Date referenceDate; @Column(name="to_compensate_value") private Double toCompensateValue; public FileOutstandingBalanceByFlagCielo() { } /** * @return the header */ public FileHeaderCielo getHeader() { return header; } /** * @param header the header to set */ public void setHeader(FileHeaderCielo header) { this.header = header; } public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Double getAnticipatedValue() { return this.anticipatedValue; } public void setAnticipatedValue(Double anticipatedValue) { this.anticipatedValue = anticipatedValue; } public Integer getBranchesSize() { return this.branchesSize; } public void setBranchesSize(Integer branchesSize) { this.branchesSize = branchesSize; } public Integer getCardFlagId() { return this.cardFlagId; } public void setCardFlagId(Integer cardFlagId) { this.cardFlagId = cardFlagId; } public Double getCededValue() { return this.cededValue; } public void setCededValue(Double cededValue) { this.cededValue = cededValue; } public String getEstablishmentNumber() { return this.establishmentNumber; } public void setEstablishmentNumber(String establishmentNumber) { this.establishmentNumber = establishmentNumber; } public Double getGrossValue() { return this.grossValue; } public void setGrossValue(Double grossValue) { this.grossValue = grossValue; } public Double getNetValue() { return this.netValue; } public void setNetValue(Double netValue) { this.netValue = netValue; } public String getPlatformType() { return this.platformType; } public void setPlatformType(String platformType) { this.platformType = platformType; } public Date getReferenceDate() { return this.referenceDate; } public void setReferenceDate(Date referenceDate) { this.referenceDate = referenceDate; } public Double getToCompensateValue() { return this.toCompensateValue; } public void setToCompensateValue(Double toCompensateValue) { this.toCompensateValue = toCompensateValue; } }
import javax.swing.JLabel; import java.util.concurrent.TimeUnit; /** * Stopwatch.java * * @author Sebrianne Ferguson, Lovejit Kharod * Last edited: November 19, 2018 * Purpose: to keep track of time for the drone game. Gets displayed at the top of the * screen. Once the time in the stopwatch has reached a certain number, it will signal the game * to be over. * <p> * From the instructions: time for the game is 1:30 minutes. If the drone does not hit more than * 2 airplanes during the time, then the game finishes, the user'stopwatch score is incremented by one, * and the time is reset. */ class Stopwatch extends JLabel implements Runnable { private int seconds; private final Scores s; private Thread timerThread; boolean gameOver; /** * Stopwatch() * Initializes the text of the JLabel with seconds = 0 */ public Stopwatch(Scores s) { this.s = s; gameOver = false; this.setFont(this.getFont().deriveFont(30.0f)); //sets font size this.setText("Time: " + (90 - seconds++)); } void setTimerThread(Thread timerThread) { this.timerThread = timerThread; } /** * begin() * Handles the countdown timerThread */ private void begin() { seconds = 0; gameOver = false; this.setText("Time: " + (90 - seconds++)); this.updateUI(); while (!gameOver && seconds <= 90) { //for a minute and 1/2 try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { System.err.println("Exception in stopwatch: " + e.getMessage()); } if (gameOver) break; this.setText("Time: " + (90 - seconds++)); this.updateUI(); } if (!gameOver) // Time up timerThread.interrupt(); this.setText("Press space to restart"); this.updateUI(); s.gameEnded(!gameOver); // gameOver is false only if time is up } @Override // Runnable public void run() { this.begin(); } }
package deliver.model; public class Order { private int person_id; private String orderName; private String from; private String destination; private String note; private String status; public Order() { } public Order(String orderName, String from, String destination, String note) { this.orderName = orderName; this.from = from; this.destination = destination; this.note = note; } //getters and setters public int getPerson_id() { return person_id; } public void setPerson_id(int person_id) { this.person_id = person_id; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } public String getFrom() { return from; } public void setFrom(String from) { this.from = from; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
package com.example.uberv.jsonparsingdemo; import java.util.List; public class Entry { Attribute name; List<Attribute> image; }
package org.softRoad.services; import org.softRoad.exception.DuplicateDataException; import org.softRoad.exception.ForbiddenException; import org.softRoad.exception.InvalidDataException; import org.softRoad.models.Fee; import org.softRoad.security.Permission; import javax.enterprise.context.ApplicationScoped; import javax.transaction.Transactional; import javax.ws.rs.core.Response; @ApplicationScoped public class FeeService extends CrudService<Fee> { public FeeService() { super(Fee.class); } @Override protected boolean hasPermission(PermissionType type) { return true; } @Override @Transactional public Response create(Fee fee) { checkState(fee.consultant.user.id.equals(acm.getCurrentUserId()) || acm.hasPermission(Permission.CREATE_FEE)); long count = Fee.count(Fee.CONSULTANT + "=?1 and " + Fee.CATEGORY + "=?2 and " + Fee.MINUTE + "=?3", fee.consultant.id, fee.category.id, fee.minute); if (count > 0) throw new DuplicateDataException("Duplicate fee for this category-minute-consultant !"); return super.create(fee); } @Override @Transactional public Response update(Fee obj) { Fee fee = Fee.findById(obj.id); if (fee == null) throw new InvalidDataException("Invalid fee"); checkState(fee.consultant.user.id.equals(acm.getCurrentUserId()) || acm.hasPermission(Permission.UPDATE_FEE)); if (obj.presentFields.contains("category") || obj.presentFields.contains("minute")) throw new ForbiddenException("Category or Minute of Fee can not modified."); return super.update(obj); } @Override @Transactional public Response delete(Integer id) { Fee fee = Fee.findById(id); if (fee == null) throw new InvalidDataException("Invalid fee"); checkState(fee.consultant.user.id.equals(acm.getCurrentUserId()) || acm.hasPermission(Permission.DELETE_FEE)); return super.delete(id); } }
package servicenow.datamart; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import servicenow.api.DateTime; import servicenow.api.Log; public class DateTimeFactory { final Properties lastMetrics; final Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}( \\d{2}:\\d{2}:\\d{2})?"); final Pattern namePattern = Pattern.compile("[a-z][a-z0-9_.]*", Pattern.CASE_INSENSITIVE); final Pattern exprPattern = Pattern.compile("([a-z][a-z0-9_.]*)?([+-])(\\d+)([a-z])", Pattern.CASE_INSENSITIVE); private Logger logger = LoggerFactory.getLogger(this.getClass()); DateTimeFactory() throws ConfigParseException { File metricsFile = Globals.getMetricsFile(); if (metricsFile == null || !metricsFile.exists()) { this.lastMetrics = null; return; } this.lastMetrics = new Properties(); try { FileInputStream input = new FileInputStream(metricsFile); lastMetrics.load(input); } catch (IOException e) { throw new ConfigParseException(e); } } /** * Used for testing * @see DateTimeFactoryTest */ DateTimeFactory(DateTime start, Properties lastMetrics) { Globals.setStart(start); this.lastMetrics = lastMetrics; } DateTime getStart() { return Globals.getStart(); } DateTime getLast(String propName) throws ConfigParseException { assert propName != null; if (lastMetrics == null) { String message = String.format("No metrics file; unable to determine last \"%s\"", propName); logger.error(Log.INIT, message); throw new ConfigParseException(message); } String propValue = lastMetrics.getProperty(propName); if (propValue == null) throw new ConfigParseException("Property not found: " + propName); return new DateTime(propValue); } DateTime getDate(Object obj) throws ConfigParseException { assert obj != null; DateTime result; logger.debug(Log.INIT, String.format("getDate %s=%s", obj.getClass().getName(), obj.toString())); if (obj instanceof java.util.Date) result = new DateTime((java.util.Date) obj); else { String expr = obj.toString(); if (datePattern.matcher(expr).matches()) result = new DateTime(expr); else if (namePattern.matcher(expr).matches()) result = getName(expr); else if (exprPattern.matcher(expr).matches()) result = getExpr(expr); else throw new ConfigParseException("Invalid datetime: " + expr); logger.debug(Log.INIT, String.format("getDate(%s)=%s", expr, result)); } return result; } private DateTime getName(String name) throws ConfigParseException { assert name != null; if (name.equalsIgnoreCase("void")) return null; if (name.equalsIgnoreCase("empty")) return null; if (name.equalsIgnoreCase("start")) return getStart(); if (name.equalsIgnoreCase("today")) return getStart().truncate(); if (name.equalsIgnoreCase("last")) return getLast("start"); if (name.toLowerCase().startsWith("last.")) { name = name.substring(5); return getLast(name); } // TODO: What is the purpose of this? // System property or profile property will override metrics value String propValue = Globals.getValue(name); if (propValue != null) return new DateTime(propValue); DateTime lastValue = getLast(name); if (lastValue == null) throw new ConfigParseException("Invalid datetime: " + name); else return lastValue; } private DateTime getExpr(String text) throws ConfigParseException { Matcher m = exprPattern.matcher(text); if (m.matches()) { String name = m.group(1); String op = m.group(2); int sign = (op == "+") ? +1 : -1; int num = sign * Integer.parseInt(m.group(3)); String units = m.group(4); if (name == null) name = "start"; DateTime base = getName(name); switch (units.toLowerCase()) { case "d": return base.addSeconds(num * DateTime.SEC_PER_DAY); case "h": return base.addSeconds(num * DateTime.SEC_PER_HOUR); case "m": return base.addSeconds(num * DateTime.SEC_PER_MINUTE); default: throw new ConfigParseException(String.format("Illegal units \"%s\" in \"%s\"", units, text)); } } else { throw new ConfigParseException(String.format("Invalid date expresion: %s", text)); } } }
package classes; import interfaces.DrawAPI; /** * @author dylan * */ public class GreenCircle implements DrawAPI { /* * (non-Javadoc) * * @see interfaces.DrawAPI#drawCircle(int, int, int) */ @Override public void drawCircle(int radius, int x, int y) { System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]"); } }
package com.example.android.finalproject_yaocmengqid.SideMenu; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.example.android.finalproject_yaocmengqid.People; import com.example.android.finalproject_yaocmengqid.R; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class GroupActivity extends AppCompatActivity { private FirebaseDatabase database; private DatabaseReference peopleRef; private String TAG = "GroupActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_group); FirebaseAuth mAuth = FirebaseAuth.getInstance(); FirebaseAuth.AuthStateListener mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); database = FirebaseDatabase.getInstance(); peopleRef = database.getReference("people").child(user.getUid()); Log.d(TAG, peopleRef.toString()); } else { // User is signed out Log.d(TAG, "onAuthStateChanged:signed_out"); finish(); } } }; mAuth.addAuthStateListener(mAuthListener); } public void saveMember(View view) { EditText name = (EditText) findViewById(R.id.add_name); EditText email = (EditText) findViewById(R.id.add_email); String peopleName = name.getText().toString(); String peopleEmail = email.getText().toString(); People people = new People(peopleName, peopleEmail); peopleRef.push().setValue(people); Toast.makeText(GroupActivity.this, "Add member successful", Toast.LENGTH_SHORT).show(); name.setText(""); email.setText(""); } }
package com.demo.mediacodec; import com.demo.lib.av.DataSource; import com.demo.mediacodec.R; import android.app.Activity; import android.content.res.Configuration; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Surface; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; public class MainActivity extends Activity { private static final String TAG = "MainActivity"; private SurfaceView surfaceView; private SurfaceHolder surfaceHolder; private Surface surface; private MyMediaCodec mediaCodec = null; private DataSource ds = null; private String Rtsp_Path = "rtsp://192.168.43.1:8554/cam0.h264"; private boolean play_state = false; private EditText et_rtsp; private Button btn_play; @Override protected void onCreate(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); surfaceView = (SurfaceView) findViewById(R.id.surfaceView); et_rtsp = (EditText) findViewById(R.id.et_rtsp); btn_play = (Button) findViewById(R.id.btn_play); btn_play.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (!play_state) { String rtsp = et_rtsp.getText().toString(); if (!rtsp.trim().isEmpty()) { Rtsp_Path = rtsp; } startRtsp(); play_state = true; btn_play.setText("Stop"); } else { stopRtsp(); play_state = false; btn_play.setText("Play"); } } }); } @Override protected void onResume() { // TODO Auto-generated method stub Log.i(TAG, "onResume"); super.onResume(); surfaceHolder = surfaceView.getHolder(); surface = surfaceHolder.getSurface(); if (play_state) { startRtsp(); } Log.i(TAG, "onResume OK"); } @Override protected void onPause() { // TODO Auto-generated method stub Log.i(TAG, "onPause"); super.onPause(); if (play_state) { stopRtsp(); } Log.i(TAG, "onPause OK"); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Log.i(TAG, "onDestroy"); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); Log.i(TAG, "onConfigurationChanged()"); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { Log.i(TAG, "Configuration.ORIENTATION_LANDSCAPE"); } else { Log.i(TAG, "Configuration.ORIENTATION_PORTRAIT"); } } private synchronized void startRtsp() { Log.i(TAG, "startRtsp()"); ds = new DataSource(); Log.i(TAG, "startRtsp() 2"); mediaCodec = new MyMediaCodec(); mediaCodec.init(this, ds, surface); Log.i(TAG, "startRtsp() 3"); ds.Sink = mediaCodec; ds.init(Rtsp_Path); Log.i(TAG, "startRtsp() 4"); } private synchronized void stopRtsp() { if (null != mediaCodec) { Log.i(TAG, "mediaCodec.deinit"); mediaCodec.deinit(); } if (null != ds) { Log.i(TAG, "ds.deinit()"); ds.deinit(); ds = null; } } }
package com.apps.dashboard.service; import com.apps.dashboard.model.AppModel; import java.util.List; public interface FileReader { List<AppModel> getAppDetails(); }
package com.example.reggiewashington.c196; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; public class AssessmentsActivity extends AppCompatActivity { DatabaseHelper myDb; SQLiteDatabase database; private static final String TAG = "AssessmentsActivity"; private ArrayList<Assessments> list = new ArrayList<>(); Terms tm; Context c; private ArrayList<String> listString; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_assessments); listView = (ListView) findViewById(R.id.assessments_listView); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); myDb = new DatabaseHelper(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); populateView(); CustomAdapter adapter = new CustomAdapter(this, R.layout.content_assessments, list); listView.setAdapter(adapter); adapter.notifyDataSetChanged(); } public void populateView(){ Cursor data = myDb.getAssessmentsData(); while(data.moveToNext()){ String type = data.getString(1); String name = data.getString(2); String date = data.getString(3); list.add(new Assessments(type,name,date)); } } public void handleAddAssessmentsActivity(View view){ Intent intent = new Intent(AssessmentsActivity.this, AddAssessment.class); startActivity(intent); } public class CustomAdapter extends BaseAdapter { private Context context; private int layout; ArrayList<Assessments> textList; public CustomAdapter(Context context, int layout, ArrayList<Assessments> textList){ this.context = context; this.layout = layout; this.textList = textList; } @Override public int getCount() { return textList.size(); } @Override public Object getItem(int position) { return textList.get(position); } @Override public long getItemId(int position) { return position; } private class ViewHolder{ TextView textType; TextView textName; TextView textDate; } @Override public View getView(int position, View view, ViewGroup parent) { View row = view; ViewHolder holder; if (row == null){ LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(layout, null); holder = new ViewHolder(); holder.textType = (TextView) row.findViewById(R.id.a_type); holder.textName = (TextView) row.findViewById(R.id.a_name); holder.textDate = (TextView) row.findViewById(R.id.a_duedate); row.setTag(holder); } else{ holder = (ViewHolder) row.getTag(); } final Assessments assessment = textList.get(position); holder.textType.setText(assessment.getType()); holder.textName.setText(assessment.getName()); holder.textDate.setText(assessment.getDate()); row.setOnClickListener(new AdapterView.OnClickListener(){ @Override public void onClick(View v) { Cursor data = myDb.getAssessmentID(assessment.getName()); int assessmentId = -1; String assessmentType = ""; String assessmentName = ""; String assessmentDate = ""; while (data.moveToNext()) { assessmentId = data.getInt(0); assessmentType = data.getString(1); assessmentName = data.getString(2); assessmentDate = data.getString(3); Intent intent = new Intent(AssessmentsActivity.this, AssessmentDetailActivity.class); intent.putExtra("Id", assessmentId); intent.putExtra("Name", assessment.getName()); startActivity(intent); } } }); return row; } } }
package ivankar.parking.service; import ivankar.parking.domain.Invoice; import ivankar.parking.domain.Ticket; /** * Service for calculating parking fee. * <p> * Created by Ivan_Kar on 10/18/2016. */ public interface PricingService { /** * Calculates fee for provided parking ticket. * * @param ticket parking ticket * @return invoice with total price and duration */ Invoice calculatePrice(Ticket ticket); }
package edu.cpp.iipl.util; import com.google.gson.Gson; import edu.cmu.lti.lexical_db.NictWordNet; import edu.cmu.lti.ws4j.RelatednessCalculator; import edu.cmu.lti.ws4j.impl.*; import edu.cmu.lti.ws4j.util.WS4JConfiguration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.List; /** * Calculate semantic similarity between two words * Currently implemented using ws4j web demo * ws4j: https://code.google.com/p/ws4j/ * ws4j web demo: http://ws4jdemo.appspot.com/ * @author Xing */ public class SemSimilarity { private class Result { private int input1_num; // total number of synsets private int input2_num; private String input1; private String input2; private double score; private double time; public double getScore() { return score; } public double getTime() { return time; } } private class Response { private List<Result> result; private String measure; public List<Result> getResult() { return result; } public String getMeasure() { return measure; } } private Gson gson = new Gson(); private final RelatednessCalculator hso; private final RelatednessCalculator lch; private final RelatednessCalculator lesk; private final RelatednessCalculator wup; private final RelatednessCalculator res; private final RelatednessCalculator jcn; private final RelatednessCalculator lin; private final RelatednessCalculator path; private boolean isOffline = false; public SemSimilarity(boolean isOffline) { hso = new HirstStOnge(new NictWordNet()); lch = new LeacockChodorow(new NictWordNet()); lesk = new Lesk(new NictWordNet()); wup = new WuPalmer(new NictWordNet()); res = new Resnik(new NictWordNet()); jcn = new JiangConrath(new NictWordNet()); lin = new Lin(new NictWordNet()); path = new Path(new NictWordNet()); WS4JConfiguration.getInstance().setMFS(true); this.isOffline = isOffline; } // get response (JSON) from url private String getResponseFromUrl(String strUrl) throws IOException { URL url = new URL(strUrl); StringBuilder sb = new StringBuilder(); try (BufferedReader br = new BufferedReader( new InputStreamReader(url.openStream(), "UTF-8"))) { int read; char[] chars = new char[1024]; while ((read = br.read(chars)) != -1) sb.append(chars, 0, read); } return sb.toString(); } // construct url to query http://ws4jdemo.appspot.com/ private String getUrl(String measure, String word1, String word2) { word1 = word1.replaceAll("#", "%23"); word2 = word2.replaceAll("#", "%23"); return "http://ws4jdemo.appspot.com/ws4j?measure=" + measure + "&args=" + word1 + "%3A%3A" + word2 + "&trace=0"; } // base method for getting similarity score private double getSimilarityScore(String measure, String word1, String word2) throws IOException { // construct url String url = getUrl(measure, word1, word2); while (true) { try { // get response content from ws4j webserver String content = getResponseFromUrl(url); // parse to Response object Response response = gson.fromJson(content, Response.class); if (response.getMeasure().equals(measure) && response.getResult().size() > 0) return response.getResult().get(0).getScore(); else throw new Exception("Something wrong"); } catch (Exception e) { System.out.println(e.getMessage()); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } public double getWup(String word1, String word2) throws IOException { if (isOffline) return wup.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("wup", word1, word2); } public double getJcn(String word1, String word2) throws IOException { if (isOffline) return jcn.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("jcn", word1, word2); } public double getLch(String word1, String word2) throws IOException { if (isOffline) return lch.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("lch", word1, word2); } public double getLin(String word1, String word2) throws IOException { if (isOffline) return lin.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("lin", word1, word2); } public double getRes(String word1, String word2) throws IOException { if (isOffline) return res.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("res", word1, word2); } public double getPath(String word1, String word2) throws IOException { if (isOffline) return path.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("path", word1, word2); } public double getLesk(String word1, String word2) throws IOException { if (isOffline) return lesk.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("lesk", word1, word2); } public double getHso(String word1, String word2) throws IOException { if (isOffline) return hso.calcRelatednessOfWords(word1, word2); else return getSimilarityScore("hso", word1, word2); } }
package com.neu.spring; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.neu.spring.dao.TraderDao; import com.neu.spring.pojo.Trader; @Controller public class SetCreditController { @Autowired @Qualifier("traderDao") TraderDao traderDao; @RequestMapping(value = "/setcredit.htm",method = RequestMethod.GET) public ModelAndView initializeForm(HttpServletRequest request) { long id=0; try{ id=Long.parseLong(request.getParameter("id")); System.out.println("jay"+id); } catch(Exception e) { System.out.println("jay"+id); } Trader trader=traderDao.getTraderById(id); ModelAndView mv=new ModelAndView(); mv.addObject("trader", trader); mv.setViewName("setpdform"); return mv; } @RequestMapping(value = "/setcredit.htm",method = RequestMethod.POST) public String doSubmitAction(HttpServletRequest request) { String creditScore=request.getParameter("score"); long id=Long.parseLong(request.getParameter("id")); int result=traderDao.updatePd(id, creditScore); System.out.println("result" + result); return "updatedpd"; } }
package java0722; import java.util.*; public class BookService { Scanner scan = new Scanner(System.in); public void text(NameDTO name) { System.out.println("-----------------------------------------------------------------"); System.out.println("1. 회원등록 | 2.도서등록 | 3. 도서대출 | 4. 도서반납 | 5. 도서목록 | 6. 종료"); System.out.println("-----------------------------------------------------------------"); System.out.print("선택 > "); } public NameDTO enter(NameDTO name) { System.out.print("회원 이름 : "); String name1 = scan.next(); System.out.print("전화번호 : "); String num = scan.next(); name.setName(name1); name.setNumber(num); return name; } public BookDTO enterbook(BookDTO book) { System.out.print("책 이름 : "); String name = scan.next(); System.out.print("작가 이름 : "); String author = scan.next(); System.out.print("책 번호 : "); int number = scan.nextInt(); book.setBookname(name); book.setAuthor(author); book.setBooknumber(number); return book; } public void bookin(List<BookDTO> bookList) { for (int i = 1; i < bookList.size(); i++) { System.out.println(bookList.get(i).toString()); } } public List<BookDTO> ang(List<BookDTO> bookList, List<NameDTO> nameList) { System.out.print("고객이름 : "); String num = scan.next(); for (int i = 1; i < nameList.size(); i++) { if (num.equals(nameList.get(i).getName())) { System.out.print("빌릴책 번호 : "); int sum = scan.nextInt(); for (int j = 1; j < bookList.size(); j++) { if (sum == bookList.get(j).getBooknumber()) { boolean boo = false; bookList.get(j).setLoans(boo); bookList.get(j).setLoansname(nameList.get(i).getName()); } } } } return bookList; } public List<BookDTO> bookin(List<BookDTO> bookList, List<NameDTO> nameList) { System.out.print("고객이름 : "); String num = scan.next(); for (int i = 1; i < nameList.size(); i++) { if (num.equals(nameList.get(i).getName())) { System.out.print("반납할 책 번호 : "); int sum = scan.nextInt(); boolean boo = false; for (int j = 1; j < bookList.size(); j++) { if (sum == bookList.get(j).getBooknumber() && boo == bookList.get(j).isLoans()) { boo = true; bookList.get(j).setLoans(boo); bookList.get(j).setLoansname(null); } } } } return bookList; } }
package com.trump.auction.cust.api; import com.trump.auction.cust.model.PromotionChannelModel; /** * 推广渠道信息相关 * @author wangbo 2018/2/5. */ public interface PromotionChannelStubService { /** * 根据渠道名称查询渠道信息 * @param channelName 渠道名称 * @return 渠道信息 */ PromotionChannelModel findChannelByName(String channelName); /** * 根据渠道Id查询渠道信息 * @param channelId 渠道id * @return 渠道信息 */ PromotionChannelModel findByChannelId(String channelId); }
/* * 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 edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.Timer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Vector; import javax.microedition.io.Connector; import javax.microedition.io.ServerSocketConnection; import javax.microedition.io.SocketConnection; public class DebuggingServer implements Runnable { private static DebuggingServer instance_; Thread serverThread = new Thread(this); private int listenPort_; private Vector connections_; double lastHeartbeatTime_ = -1; private boolean listening_ = true; private Vector sendData = new Vector(); public static DebuggingServer getInstance() { if (instance_ == null) { instance_ = new DebuggingServer(); } return instance_; } public void addDebugData(DebuggingPackage dp){ sendData.addElement(dp); } public void start() { serverThread.start(); } public void stop() { listening_ = false; } private DebuggingServer() { this(1180); } private DebuggingServer(int port) { listenPort_ = port; connections_ = new Vector(); } public boolean hasClientConnection() { return lastHeartbeatTime_ > 0 && (Timer.getFPGATimestamp() - lastHeartbeatTime_) < 3.0; } public void setPort(int port) { listenPort_ = port; } public void reset(){ lastHeartbeatTime_ = -1; } // This class handles incoming TCP connections private class VisionServerConnectionHandler implements Runnable { SocketConnection connection; public VisionServerConnectionHandler(SocketConnection c) { connection = c; } public void run() { try { OutputStream os = connection.openOutputStream(); int ch = 0; byte[] b = new byte[1024]; double timeout = 10.0; double lastHeartbeat = Timer.getFPGATimestamp(); DebuggingServer.this.lastHeartbeatTime_ = lastHeartbeat; Vector s_d = DebuggingServer.instance_.sendData; while (Timer.getFPGATimestamp() < lastHeartbeat + timeout) { boolean gotData = false; while (!s_d.isEmpty()) { os.write(((DebuggingPackage)s_d.elementAt(0)).getVal()); s_d.removeElementAt(0); } try { Thread.sleep(50); // sleep a bit } catch (InterruptedException ex) { System.out.println("Thread sleep failed."); } } os.close(); connection.close(); } catch (IOException e) { } } } // run() to implement Runnable // This method listens for incoming connections and spawns new // VisionServerConnectionHandlers to handle them public void run() { ServerSocketConnection s = null; try { s = (ServerSocketConnection) Connector.open("serversocket://:" + listenPort_); while (listening_) { SocketConnection connection = (SocketConnection) s.acceptAndOpen(); Thread t = new Thread(new DebuggingServer.VisionServerConnectionHandler(connection)); t.start(); connections_.addElement(connection); try { Thread.sleep(100); } catch (InterruptedException ex) { System.out.println("Thread sleep failed."); } } } catch (IOException e) { System.out.println("Socket failure."); e.printStackTrace(); } } }
package jdbc; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Scanner; import java.util.StringTokenizer; import javax.swing.*; import javax.swing.border.*; //테이블에서 insert나 delete를 해줄때마다(예약 등록/변경,취소 등) commit;해줘야 제대로 입력됩니다. //create table 쿼리가 들어있는 메모장의 쿼리들을 sql command line에 입력해줘야 합니다. public class TermP implements ActionListener { public void readFile(File textile) throws SQLException { Scanner scanner = null; int indexcount = 0; int check = 0; try { scanner = new Scanner(textile); while (scanner.hasNextLine()) { check++; String test = scanner.nextLine().toString(); try { if (check == 1) { while (indexcount < 5) { test = scanner.nextLine().toString(); StringTokenizer token = new StringTokenizer(test, "\t"); while (token.hasMoreTokens()) { String guestName = token.nextToken(); String guestGender = token.nextToken(); String guestAddress = token.nextToken(); String guestPhone = token.nextToken(); String sqlStr = "insert into customer values ('" + guestName + "', '" + guestGender + "' ,'" + guestAddress + "' ,'" + guestPhone + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); rs.close(); stmt.close(); } indexcount++; } indexcount = 0; } else if (check == 2) { while (indexcount < 5) { test = scanner.nextLine().toString(); StringTokenizer token = new StringTokenizer(test, "\t"); while (token.hasMoreTokens()) { String staffName = token.nextToken(); String staffGender = token.nextToken(); String staffAddress = token.nextToken(); String staffPhone = token.nextToken(); String sqlStr = "insert into staff values ('" + staffName + "', '" + staffGender + "' ,'" + staffAddress + "' ,'" + staffPhone + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); rs.close(); stmt.close(); } indexcount++; } indexcount = 0; } else if (check == 3) { while (indexcount < 20) { test = scanner.nextLine().toString(); StringTokenizer token = new StringTokenizer(test, "\t"); while (token.hasMoreTokens()) { int roomNo = Integer.parseInt(token.nextToken()); int roomPeople = Integer.parseInt(token.nextToken()); String roomType = token.nextToken(); String sqlStr = "insert into room values (" + roomNo + ", " + roomPeople + " ,'" + roomType + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); rs.close(); stmt.close(); } indexcount++; } indexcount = 0; } } catch (Exception e) { JOptionPane.showMessageDialog(null, "파일 읽기에 실패했습니다. check==1,2,3: 다시 시도해 주세요"); // e.printStackTrace(); } } // while(scanner.hasNextLine()) } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "파일 읽기에 실패했습니다. 파일notfound: 다시 시도해 주세요"); } catch (Exception e) { JOptionPane.showMessageDialog(null, "파일 읽기에 실패했습니다. 제일아래 exception: 다시 시도해 주세요"); } finally { scanner.close(); } } private static Connection dbTest; private Border loweredborder = BorderFactory.createLoweredBevelBorder(); TitledBorder titledborder = BorderFactory.createTitledBorder(loweredborder, "title"); private JPanel login_panel = new JPanel(); private String username; private String password; private JLabel idLabel = new JLabel("아이디"); private JLabel pwdLabel = new JLabel("비밀번호"); private JTextField idInput = new JTextField(); private JPasswordField pwdInput = new JPasswordField(); private JButton loginButton = new JButton("로그인"); private JFileChooser jfc = new JFileChooser(); private JMenuBar jmb; private JMenuItem menuopen; private JFrame frame = new JFrame(); private JFrame login_frame = new JFrame(); private JFrame emp_frame = new JFrame(); private JFrame cust_frame = new JFrame(); private JPanel reserve_panel = new JPanel(); private JPanel res_panel = new JPanel(new GridLayout(5, 2, 30, 20)); private JPanel current_panel = new JPanel(); private JPanel cur_panel = new JPanel(new GridLayout(4, 5, 30, 37)); private JPanel enroll_panel = new JPanel(); private JLabel title = new JLabel("호텔 관리 시스템", JLabel.CENTER); private JLabel reserve = new JLabel("투숙예약", JLabel.CENTER); private JLabel todate = new JLabel(); private JLabel res_customer = new JLabel("고객명"); private JTextField res_cust_Input = new JTextField(); private JLabel res_checkin = new JLabel("체크인(YYYYMMDD)"); private JTextField res_checkin_Input = new JTextField(); private JLabel res_day = new JLabel("박"); private JComboBox<Integer> res_day_box = new JComboBox<Integer>(); private JLabel res_room = new JLabel("객실"); private JComboBox<String> res_room_box = new JComboBox<String>(); // db에서 // room // 가져오기 private JButton res_enroll = new JButton("예약 등록/변경"); private JButton res_cancel = new JButton("예약 취소"); private JLabel cur_reserve = new JLabel("객실 예약 현황", JLabel.CENTER); private JLabel table1[] = new JLabel[20]; private JLabel table2[] = new JLabel[20]; private JLabel check = new JLabel("등록/조회", JLabel.CENTER); private JTabbedPane tabPanel; private JComboBox<String> check_room_box = new JComboBox<String>(); private JLabel check_guestname, check_empname, check_room; private JPanel searchRegi_P, guestTab, roomTab, empTab; private TextField check_empname_Input; private TextField check_guestname_Input; private JButton check_register, check_search, check_empRegister, check_empSearch; private JTextArea guest_textarea, emp_textarea, room_textarea; // 고객 회원가입 패널 private JPanel cust_panel = new JPanel(); private JLabel customer = new JLabel("고객명"); private JLabel cust_gender = new JLabel("성별"); private JLabel cust_address = new JLabel("주소"); private JLabel cust_call_Number = new JLabel("연락처"); private JTextField cust_Input = new JTextField(); private JTextField cust_call_Input = new JTextField(); private JComboBox<String> cust_gender_box = new JComboBox<String>(); private JComboBox<String> cust_address_box = new JComboBox<String>(); private JButton enroll_cust = new JButton("가입신청"); private JButton cust_cancel = new JButton("취소"); // 직원 등록 패널 private JPanel emp_panel = new JPanel(); private JLabel employee = new JLabel("직원명"); private JLabel emp_p_customer = new JLabel("고객명"); private JLabel emp_p_gender = new JLabel("성별"); private JLabel emp_p_address = new JLabel("주소"); private JLabel emp_p_call_Number = new JLabel("연락처"); private JTextField emp_p_Input = new JTextField(); private JComboBox<String> emp_p_gender_box = new JComboBox<String>(); private JComboBox<String> emp_p_address_box = new JComboBox<String>(); private JButton emp_p_enroll_cust = new JButton("가입신청"); private JButton emp_p_cancel = new JButton("취소"); private JTextField emp_p_call_Input = new JTextField(); PreparedStatement stmt; ResultSet rs; // dbtable을 만드는 함수 public void createTable() throws SQLException { String customerQuery = "CREATE TABLE customer (\n" + "c_name varchar(10) not null,\n" + "c_gender varchar(10) not null, \n" + "c_address varchar(10) not null, \n" + "c_phone number not null, \n" + "primary key(c_phone) \n" + ")"; String managerQuery = "CREATE TABLE staff (\n" + "s_name varchar(10) not null,\n" + "s_gender varchar(10) not null, \n" + "s_address varchar(10) not null, \n" + "s_phone varchar(10) not null, \n" + "primary key(s_phone) \n" + ")"; String roomQuery = "CREATE TABLE room (\n" + "roomno number not null,\n" + "person number not null,\n" + "type varchar(10) not null,\n" + "primary key(roomno) \n" + ")"; String reservationQuery = "CREATE TABLE reservation (\n" + "id number not null,\n" + "c_name varchar(10) not null,\n" + "checkin date not null,\n" + "checkout date not null,\n" + "term number not null, \n" + "roomno number not null, \n" + "s_name varchar(10) not null, \n" + "primary key(id) \n"+ ")"; String sql = ""; // for문으로 table 생성을 위해 table이름, query 배열을 생성 try { String[] tablename = { "customer", "staff", "room", "reservation" }; String[] query = { customerQuery, managerQuery, roomQuery, reservationQuery }; for (int i = 0; i < tablename.length; i++) { // db에 이미 table이 생성이 되어있는지를 check, 없다면 생성, 있다면 생성하지 않음 if (dbtableexist(tablename[i]) == false) { // System.out.println(tablename[i]); sql = query[i]; stmt = dbTest.prepareStatement(sql); rs = stmt.executeQuery(); dbTest.commit(); } } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "테이블생성에 문제가 발생했습니다 : " + e); dbTest.rollback(); } finally { stmt.close(); rs.close(); } } // createTable 함수 실행시 DB에 table의 존재 유무를 알려주는 함수 public boolean dbtableexist(String tablename) throws SQLException { String sql = "Select TABLE_NAME from user_tables where table_name='" + tablename.toUpperCase() + "' "; boolean existTable = false; stmt = dbTest.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { if (rs.getString("table_name").equals(tablename.toUpperCase())) { existTable = true; // db에 이미 테이블 존재시 true : table 생성할 필요가 없음 } } stmt.close(); rs.close(); return existTable; } public TermP() { login_panel.setLayout(null); idLabel.setBounds(20, 10, 60, 30); pwdLabel.setBounds(20, 50, 60, 30); idInput.setBounds(100, 10, 80, 30); pwdInput.setBounds(100, 50, 80, 30); loginButton.setBounds(200, 25, 80, 35); loginButton.addActionListener(this); login_panel.add(idLabel); login_panel.add(pwdLabel); login_panel.add(idInput); login_panel.add(pwdInput); login_panel.add(loginButton); login_frame.add(login_panel); login_frame.setTitle("호텔시스템 로그인"); login_frame.setSize(320, 130); login_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); login_frame.setVisible(true); } private void hotel() throws SQLException { createTable(); login_frame.setVisible(false); frame.setLayout(null); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String today = "(" + sdf.format(date) + ")"; todate.setText(today); todate.setBounds(950, 130, 150, 20); todate.setFont(new Font("돋움", Font.BOLD, 20)); frame.add(todate); // 상단 메뉴바 생성 jmb = new JMenuBar(); JMenu jmFile = new JMenu("file"); // 메뉴바 menuopen = new JMenuItem("Open"); // 메뉴바 하위메뉴 생성 menuopen.addActionListener(this); jmFile.add(menuopen); jmb.add(jmFile); // 상위메뉴를 메뉴바에 추가 frame.setTitle("호텔관리시스템"); frame.setJMenuBar(jmb); frame.setSize(1150, 900); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); title.setFont(new Font("돋움", Font.BOLD, 25)); // 글씨체 title.setBounds(300, 50, 500, 50); // label 위치 title.setBorder(new LineBorder(Color.black)); // label 테두리설정 frame.add(title); reserve.setFont(new Font("돋움", Font.BOLD, 20)); reserve.setBounds(50, 130, 150, 20); frame.add(reserve); cur_reserve.setFont(new Font("돋움", Font.BOLD, 20)); cur_reserve.setBounds(600, 130, 150, 20); frame.add(cur_reserve); check.setFont(new Font("돋움", Font.BOLD, 20)); check.setBounds(30, 420, 150, 20); frame.add(check); res_panel.setBounds(100, 100, 250, 250); res_day_box.addItem(1); res_day_box.addItem(2); res_day_box.addItem(3); res_day_box.addItem(4); res_day_box.addItem(5); res_day_box.addItem(6); res_day_box.addItem(7); res_day_box.addItem(8); res_day_box.addItem(9); res_day_box.addItem(10); res_panel.add(res_customer); res_panel.add(res_cust_Input); res_panel.add(res_checkin); res_panel.add(res_checkin_Input); res_panel.add(res_day); res_panel.add(res_day_box); res_panel.add(res_room); res_panel.add(res_room_box); res_panel.add(res_enroll); res_panel.add(res_cancel); res_enroll.addActionListener(this); res_cancel.addActionListener(this); reserve_panel.add(res_panel); reserve_panel.setBounds(80, 160, 450, 250); reserve_panel.setBorder(loweredborder); frame.add(reserve_panel); frame.add(current_panel); frame.add(enroll_panel); // 객실 예약 현황 panel current_panel.setBounds(620, 160, 450, 250); current_panel.setBorder(loweredborder); current_panel.add(cur_panel); for (int i = 1; i < 11; i++) { table1[i] = new JLabel("10" + i); if (i == 10) { table1[i] = new JLabel("1" + i); } // 20개 라벨들의 테두리에 검은 선이 보이도록 border 생성 res_room_box.addItem(table1[i].getText()); check_room_box.addItem(table1[i].getText()); table1[i].setFont(new Font("돋움", Font.BOLD, 23)); table1[i].setBorder(new LineBorder(Color.black)); // 모든 라벨의 테두리에 검은 // 선이 보이게 추가 table1[i].setOpaque(true); // 라벨의 배경색을 보이게 해주는 것 table1[i].setBackground(Color.WHITE); // 배경색을 흰색으로 통일 table1[i].setHorizontalAlignment(JLabel.CENTER); // 라벨안의 호수 숫자를 가운데 // 정렬 cur_panel.add(table1[i]); // 패널에 라벨을 집어넣음 } for (int i = 1; i < 11; i++) { table2[i] = new JLabel("20" + i); if (i == 10) { table2[i] = new JLabel("2" + i); } // 20개 라벨들의 테두리에 검은 선이 보이도록 border 생성 res_room_box.addItem(table2[i].getText()); table2[i].setFont(new Font("돋움", Font.BOLD, 23)); check_room_box.addItem(table2[i].getText()); table2[i].setBorder(new LineBorder(Color.black)); // 모든 라벨의 테두리에 검은 // 선이 보이게 추가 table2[i].setOpaque(true); // 라벨의 배경색을 보이게 해주는 것 table2[i].setBackground(Color.WHITE); // 배경색을 흰색으로 통일 table2[i].setHorizontalAlignment(JLabel.CENTER); // 라벨안의 호수 숫자를 가운데 // 정렬 cur_panel.add(table2[i]); // 패널에 라벨을 집어넣음 } //////////////////////////////////////////////////////////////////////////////////////////// // 등록/조회 panel searchRegi_P = new JPanel(); searchRegi_P.setLayout(null); tabPanel = new JTabbedPane(); tabPanel.setBounds(30, 30, 1000, 300); // 고객tab guestTab = new JPanel(); guestTab.setBorder(new LineBorder(Color.black)); guestTab.setLayout(null); check_guestname = new JLabel("고객명"); check_guestname.setFont(new Font("돋움", Font.BOLD, 15)); check_guestname.setBounds(20, 50, 100, 50); // 고객이름입력란 check_guestname_Input = new TextField(10); check_guestname_Input.setBounds(150, 60, 150, 30); // 가입버튼 check_register = new JButton("회원가입"); check_register.addActionListener(this); check_register.setBounds(40, 150, 100, 30); check_register.setFont(new Font("돋움", Font.PLAIN, 15)); // 조회버튼 check_search = new JButton("조회"); check_search.addActionListener(this); check_search.setFont(new Font("돋움", Font.PLAIN, 15)); check_search.setBounds(190, 150, 100, 30); // 결과창 guest_textarea = new JTextArea(10, 20); guest_textarea.setBounds(500, 20, 450, 230); guest_textarea.setBorder(new LineBorder(Color.black)); guest_textarea.setEditable(false); guestTab.add(check_guestname); guestTab.add(check_guestname_Input); guestTab.add(check_register); guestTab.add(check_search); guestTab.add(guest_textarea); // 객실tab roomTab = new JPanel(); roomTab.setLayout(null); roomTab.setBorder(new LineBorder(Color.black)); check_room = new JLabel("객실"); check_room.setFont(new Font("돋움", Font.BOLD, 15)); check_room.setBounds(20, 50, 100, 50); check_room_box.setBounds(150, 60, 100, 30); check_room_box.addActionListener(this); room_textarea = new JTextArea(10, 20); room_textarea.setBounds(500, 20, 450, 230); room_textarea.setBorder(new LineBorder(Color.black)); room_textarea.setEditable(false); roomTab.add(check_room); roomTab.add(check_room_box); roomTab.add(room_textarea); // 직원 tab empTab = new JPanel(); empTab.setLayout(null); empTab.setBorder(new LineBorder(Color.black)); check_empname = new JLabel("직원명"); check_empname.setFont(new Font("돋움", Font.BOLD, 15)); check_empname.setBounds(20, 50, 100, 50); // 고객이름입력란 check_empname_Input = new TextField(10); check_empname_Input.setBounds(150, 60, 150, 30); // 가입버튼 check_empRegister = new JButton("직원등록"); check_empRegister.addActionListener(this); check_empRegister.setBounds(40, 150, 100, 30); check_empRegister.setFont(new Font("돋움", Font.PLAIN, 15)); // 조회버튼 check_empSearch = new JButton("조회"); check_empSearch.addActionListener(this); check_empSearch.setFont(new Font("돋움", Font.PLAIN, 15)); check_empSearch.setBounds(190, 150, 100, 30); // 결과창 emp_textarea = new JTextArea(10, 20); emp_textarea.setBounds(500, 20, 450, 230); emp_textarea.setBorder(new LineBorder(Color.black)); emp_textarea.setEditable(false); empTab.add(check_empname); empTab.add(check_empname_Input); empTab.add(check_empRegister); empTab.add(check_empSearch); empTab.add(emp_textarea); tabPanel.add("고객", guestTab); tabPanel.add("객실", roomTab); tabPanel.add("직원", empTab); searchRegi_P.add(tabPanel); searchRegi_P.setBounds(50, 450, 1050, 350);// 등록/조회 테두리 searchRegi_P.setBorder(loweredborder); frame.add(title); // title label 추가 ///// frame.add(frame_currentDateLabel);//현재시간 label 추 frame.add(searchRegi_P); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { if (e.getSource() == loginButton) { username = idInput.getText(); password = new String(pwdInput.getPassword()); connectDB(); try { hotel(); } catch (SQLException e1) { e1.printStackTrace(); } } if (e.getSource() == menuopen) { if (jfc.showOpenDialog(jmb) == JFileChooser.APPROVE_OPTION) { try { File SelectedFile = jfc.getSelectedFile(); try { readFile(SelectedFile); } catch (Exception e1) { JOptionPane.showMessageDialog(null, "파일을 읽어들이는 도중 문제가 발생했습니다. 다시 시도해 주세요."); } } catch (Exception e1) { JOptionPane.showMessageDialog(null, "메뉴오픈 에러"); } } } else if (e.getSource() == emp_p_cancel) { emp_frame.setVisible(false); } else if (e.getSource() == cust_cancel) { cust_frame.setVisible(false); } else if (e.getSource() == check_register) { cust_panel.setLayout(null); cust_frame.setTitle("회원가입"); cust_frame.setSize(400, 400); customer.setBounds(70, 50, 100, 30); cust_Input.setBounds(170, 50, 130, 30); cust_gender.setBounds(70, 100, 80, 30); cust_gender_box.setBounds(170, 100, 130, 30); cust_gender_box.addItem("남"); cust_gender_box.addItem("여"); cust_address.setBounds(70, 150, 80, 30); cust_address_box.setBounds(170, 150, 130, 30); cust_address_box.addItem("서울"); cust_address_box.addItem("경기"); cust_address_box.addItem("강원"); cust_call_Number.setBounds(70, 200, 60, 30); cust_call_Input.setBounds(170, 200, 130, 30); enroll_cust.setBounds(70, 260, 100, 35); enroll_cust.addActionListener(this); cust_cancel.setBounds(210, 260, 100, 35); cust_cancel.addActionListener(this); cust_panel.add(enroll_cust); cust_panel.add(customer); cust_panel.add(cust_Input); cust_panel.add(cust_call_Input); cust_panel.add(cust_call_Number); cust_panel.add(cust_gender); cust_panel.add(cust_address); cust_panel.add(cust_gender_box); cust_panel.add(cust_address_box); cust_panel.add(cust_cancel); cust_frame.add(cust_panel); cust_frame.setVisible(true); } else if (e.getSource() == check_empRegister) { emp_panel.setLayout(null); emp_frame.setTitle("회원가입"); emp_frame.setSize(400, 400); employee.setBounds(70, 50, 100, 30); emp_p_Input.setBounds(170, 50, 130, 30); emp_p_gender.setBounds(70, 100, 80, 30); emp_p_gender_box.setBounds(170, 100, 130, 30); emp_p_gender_box.addItem("남"); emp_p_gender_box.addItem("여"); emp_p_address.setBounds(70, 150, 80, 30); emp_p_address_box.setBounds(170, 150, 130, 30); emp_p_address_box.addItem("서울"); emp_p_address_box.addItem("경기"); emp_p_address_box.addItem("강원"); emp_p_call_Number.setBounds(70, 200, 60, 30); emp_p_call_Input.setBounds(170, 200, 130, 30); emp_p_enroll_cust.setBounds(70, 260, 100, 35); emp_p_enroll_cust.addActionListener(this); emp_p_cancel.setBounds(210, 260, 100, 35); emp_p_cancel.addActionListener(this); emp_panel.add(employee); emp_panel.add(emp_p_Input); emp_panel.add(emp_p_call_Input); emp_panel.add(emp_p_customer); emp_panel.add(emp_p_call_Number); emp_panel.add(emp_p_gender); emp_panel.add(emp_p_address); emp_panel.add(emp_p_gender_box); emp_panel.add(emp_p_address_box); emp_panel.add(emp_p_enroll_cust); emp_panel.add(emp_p_cancel); emp_frame.add(emp_panel); emp_frame.setVisible(true); } else if (e.getSource() == emp_p_enroll_cust) { try { String empname = emp_p_Input.getText(); String empgender = ((String) emp_p_gender_box.getSelectedItem()); String empaddress = ((String) emp_p_address_box.getSelectedItem()); String empcall = emp_p_call_Input.getText(); String sqlStr = "insert into staff values ('" + empname + "', '" + empgender + "' ,'" + empaddress + "' ,'" + empcall + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); dbTest.commit(); rs.close(); stmt.close(); } catch (SQLException x) { JOptionPane.showMessageDialog(null, (String) "직원등록을 할 수 없습니다.", "메시지", 2); // x.printStackTrace(); } } else if (e.getSource() == enroll_cust) { try { String custname = cust_Input.getText(); String custgender = ((String) cust_gender_box.getSelectedItem()); String custaddress = ((String) cust_address_box.getSelectedItem()); String custcall = cust_call_Input.getText(); String sqlStr = "insert into customer values ('" + custname + "', '" + custgender + "' ,'" + custaddress + "' ,'" + custcall + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); dbTest.commit(); rs.close(); stmt.close(); } catch (SQLException x) { JOptionPane.showMessageDialog(null, (String) "고객등록을 할 수 없습니다.", "메시지", 2); // x.printStackTrace(); } } else if (e.getSource() == check_search) { // 고객 조회버튼 try { int countT = 0; guest_textarea.setText(null); String custgender = ""; String custaddress = ""; String custcall = ""; String custname = check_guestname_Input.getText(); String sqlStr = "select C_NAME,C_GENDER,C_ADDRESS,C_PHONE from customer where (C_NAME = '" + custname + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); while (rs.next()) { custgender = rs.getString("C_GENDER"); custaddress = rs.getString("C_ADDRESS"); custcall = rs.getString("C_PHONE"); } rs.close(); stmt.close(); String sqlStr2 = "select sum(term) from reservation where c_name = '" + custname + "'"; PreparedStatement stmt2 = dbTest.prepareStatement(sqlStr2); ResultSet rs2 = stmt2.executeQuery(); while (rs2.next()) { countT = rs2.getInt("sum(term)"); } rs2.close(); stmt2.close(); String maxckout = ""; String sqlStr3 = "select max(checkout) from reservation where c_name = '" + custname + "'"; PreparedStatement stmt3 = dbTest.prepareStatement(sqlStr3); ResultSet rs3 = stmt3.executeQuery(); while (rs3.next()) { maxckout = rs3.getString("max(checkout)"); if (maxckout == null) { maxckout = ""; } } rs3.close(); stmt3.close(); String maxstf = ""; int ctcust = 0; String sqlStr4 = "select * from (select s_name,c_name,count(s_name) from reservation where c_name = '" + custname + "' group by c_name,s_name having count(s_name) > 0 order by count(s_name) desc) where rownum = 1"; PreparedStatement stmt4 = dbTest.prepareStatement(sqlStr4); ResultSet rs4 = stmt4.executeQuery(); while (rs4.next()) { maxstf = rs4.getString("S_NAME"); ctcust = rs4.getInt("COUNT(S_NAME)"); } rs4.close(); stmt4.close(); guest_textarea.append(" 고객명 : " + custname + " \n 성별 : " + custgender + "\n 주소 : " + custaddress + "\n 연락처 : " + custcall + " \n 총 투숙기간 : " + countT + "\n 최근 투숙일 : " + maxckout + "\n 객실전담직원(최다) : " + maxstf + "\t (" + ctcust + ")회"); } catch (SQLException x) { JOptionPane.showMessageDialog(null, (String) "등록/조회panel textarea오류", "메시지", 2); x.printStackTrace(); } } else if (e.getSource() == check_empSearch) { // 직원 조회버튼 try { emp_textarea.setText(null); String empgender = ""; String empaddress = ""; String empcall = ""; String empname = check_empname_Input.getText(); String sqlStr = "select S_NAME,S_GENDER,S_ADDRESS,S_PHONE from staff where (S_NAME = '" + empname + "')"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); while (rs.next()) { empgender = rs.getString("S_GENDER"); empaddress = rs.getString("S_ADDRESS"); empcall = rs.getString("S_PHONE"); } rs.close(); stmt.close(); String maxcust = ""; int ctstff = 0; String sqlStr2 = "select * from (select s_name,c_name,count(c_name) from reservation where s_name = '" + empname + "' group by c_name,s_name having count(c_name) > 0 order by count(c_name) desc) where rownum = 1"; PreparedStatement stmt2 = dbTest.prepareStatement(sqlStr2); ResultSet rs2 = stmt2.executeQuery(); while (rs2.next()) { maxcust = rs2.getString("C_NAME"); ctstff = rs2.getInt("COUNT(C_NAME)"); } rs2.close(); stmt2.close(); String sqlStr3 = "select * from (select s_name,count(roomno),roomno from reservation where s_name = '" + empname + "' group by s_name,roomno having count(roomno) > 0 order by count(roomno) desc) where rownum = 1"; PreparedStatement stmt3 = dbTest.prepareStatement(sqlStr3); ResultSet rs3 = stmt3.executeQuery(); String maxroom = ""; int ctroom = 0; while (rs3.next()) { maxroom = rs3.getString("roomno"); ctroom = rs3.getInt("count(roomno)"); } rs3.close(); stmt3.close(); emp_textarea.append(" 직원명 : " + empname + " \n 성별 : " + empgender + "\n 주소 : " + empaddress + "\n 연락처 : " + empcall + " \n 접대 고객(최다) : " + maxcust + "\t(" + ctstff + ")회" + "\n 관리객실(최다) : " + maxroom + "\t(" + ctroom + ")회"); } catch (SQLException x) { JOptionPane.showMessageDialog(null, (String) "등록/조회panel textarea오류", "메시지", 2); x.printStackTrace(); } } else if (e.getSource() == check_room_box) { // 객실 조회 체크박스 try { room_textarea.setText(null); String roomno = check_room_box.getSelectedItem() + ""; String person = ""; String type = ""; String sqlStr2 = "select ROOMNO,PERSON,TYPE from room where ROOMNO = '" + roomno + "'"; PreparedStatement stmt2 = dbTest.prepareStatement(sqlStr2); ResultSet rs2 = stmt2.executeQuery(); while (rs2.next()) { person = rs2.getString("PERSON"); type = rs2.getString("TYPE"); } rs2.close(); stmt2.close(); String sqlStr3 = "select CHECKIN,CHECKOUT from reservation where roomno = '" + roomno + "'"; PreparedStatement stmt3 = dbTest.prepareStatement(sqlStr3); ResultSet rs3 = stmt3.executeQuery(); String tempci = ""; String tempco = ""; String status = ""; while (rs3.next()) { tempci = rs3.getString("CHECKIN"); tempco = rs3.getString("CHECKOUT"); try { Date tod = new Date(); SimpleDateFormat sdf6 = new SimpleDateFormat("yyyyMMdd"); String todate = sdf6.format(tod); Date today = sdf6.parse(todate); Date tmpci = new Date(); Date tmpco = new Date(); SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); tmpci = sdf4.parse(tempci); tmpco = sdf4.parse(tempco); System.out.println(today); System.out.println(tmpci); System.out.println(tmpco); if (tmpci.compareTo(today) <= 0 && today.compareTo(tmpco) == -1) { status = "투숙중"; } else { status = "비어있음"; } } catch (Exception x) { x.printStackTrace(); } } rs3.close(); stmt3.close(); String sqlStr4 = "select * from (select s_name,count(roomno),roomno from reservation where roomno = " + roomno + " group by s_name,roomno having count(roomno) > 0 order by count(roomno) desc) where rownum = 1"; PreparedStatement stmt4 = dbTest.prepareStatement(sqlStr4); ResultSet rs4 = stmt4.executeQuery(); String sn = ""; int strm = 0; while (rs4.next()) { sn = rs4.getString("s_name"); strm = rs4.getInt("count(roomno)"); } rs4.close(); stmt4.close(); String sqlStr5 = "select * from (select c_name,count(roomno),roomno from reservation where roomno = " + roomno + "group by c_name,roomno having count(roomno) > 0 order by count(roomno) desc) where rownum = 1"; PreparedStatement stmt5 = dbTest.prepareStatement(sqlStr5); ResultSet rs5 = stmt5.executeQuery(); String cn = ""; int ctrm = 0; while (rs5.next()) { cn = rs5.getString("c_name"); ctrm = rs5.getInt("count(roomno)"); } rs5.close(); stmt5.close(); room_textarea.append(" 방번호 : " + roomno + " \n 수용인원 : " + person + "\n 타입 : " + type + "\n 상태 : " + status + " \n 투숙고객(최다) : " + cn + "\t (" + ctrm + ")회" + "\n 객실전담직원(최다) : " + sn + "\t (" + strm + ")회"); } catch (SQLException x) { JOptionPane.showMessageDialog(null, (String) "등록/조회panel textarea오류", "메시지", 2); x.printStackTrace(); } } else if (e.getSource() == res_enroll) { try { String custName = res_cust_Input.getText(); String oldcheckin = res_checkin_Input.getText(); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd"); Date checkIn = sdf2.parse(oldcheckin); // 텍스트박스에 입력한 날짜 String newcheckIn = sdf2.format(checkIn); String term = res_day_box.getSelectedItem() + ""; String roomno = res_room_box.getSelectedItem() + ""; Calendar inDate = Calendar.getInstance(); inDate.setTime(checkIn); inDate.add(Calendar.DATE, Integer.parseInt(term)); Date oldcheckOut = inDate.getTime(); SimpleDateFormat sdf3 = new SimpleDateFormat("yyyyMMdd"); String newcheckOut = sdf3.format(oldcheckOut); String staff_cus = ""; String sqlStr = "select s_name from staff order by DBMS_RANDOM.RANDOM"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); while (rs.next()) { staff_cus = rs.getString("s_name"); } rs.close(); stmt.close(); String sqlStr2 = "select c_name from customer where c_name = '" + custName + "'"; PreparedStatement stmt2 = dbTest.prepareStatement(sqlStr2); ResultSet rs2 = stmt2.executeQuery(); if (rs2.next() == false) {// 등록된 이름인지 확인 JOptionPane.showMessageDialog(null, (String) "먼저 회원등록을 해주세요!", "메시지", 2); } else {// db에 등록된 이름일때 String check_cust_name = ""; String c_checkin = ""; String c_checkout = ""; String c_checkterm = ""; String c_roomno = ""; String sqlStr3 = "select C_NAME from reservation where C_NAME = '" + custName + "'"; PreparedStatement stmt3 = dbTest.prepareStatement(sqlStr3); ResultSet rs3 = stmt3.executeQuery(); while (rs3.next()) { check_cust_name = rs3.getString("C_NAME"); } if (check_cust_name == "") {// reservation 테이블 안에 이름 없으면! String sqlStr4 = "insert into reservation values(res_seq.nextval,'" + custName + "','" + newcheckIn + "','" + newcheckOut + "','" + term + "','" + roomno + "','" + staff_cus + "')"; PreparedStatement stmt4 = dbTest.prepareStatement(sqlStr4); ResultSet rs4 = stmt4.executeQuery(); dbTest.commit(); rs4.close(); stmt4.close(); Date tod = new Date(); SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd"); String todate = sdf6.format(tod); Date today = sdf6.parse(todate); String temproom = ""; String tempin = ""; String tempout = ""; Date tempckin = new Date(); Date tempckout = new Date(); for (int i = 1; i < 11; i++) { String t1 = table1[i].getText(); String t2 = table2[i].getText(); String sqlStr5 = "select ROOMNO,CHECKIN,CHECKOUT from reservation"; PreparedStatement stmt5 = dbTest.prepareStatement(sqlStr5); ResultSet rs5 = stmt5.executeQuery(); while (rs5.next()) { temproom = rs5.getString("ROOMNO"); tempin = rs5.getString("CHECKIN"); tempckin = sdf6.parse(tempin); tempout = rs5.getString("CHECKOUT"); tempckout = sdf6.parse(tempout); if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t1))) { table1[i].setBackground(Color.yellow); break; } else if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t2))) { table2[i].setBackground(Color.yellow); break; } else { table1[i].setBackground(Color.white); table2[i].setBackground(Color.white); } } } } else {// reservation 테이블 안에 이름 있는 경우! String sqlStr4 = "select C_NAME,CHECKIN,CHECKOUT,TERM,ROOMNO from reservation where C_NAME = '" + custName + "'"; PreparedStatement stmt4 = dbTest.prepareStatement(sqlStr4); ResultSet rs4 = stmt4.executeQuery(); while (rs4.next()) { check_cust_name = rs4.getString("C_NAME"); c_checkin = rs4.getString("CHECKIN"); c_checkout = rs4.getString("CHECKOUT"); c_checkterm = rs4.getString("TERM"); c_roomno = rs4.getString("ROOMNO"); SimpleDateFormat sdf4 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date comp_in = sdf4.parse(c_checkin);// DB의 check-in // > // compareTo용 SimpleDateFormat sdf5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date comp_out = sdf5.parse(c_checkout);// DB의 // checkout // > // compareTo용 String upcheckIn = sdf2.format(comp_in); // yyyyMMdd String upcheckOut = sdf2.format(comp_out); // checkIn > a(입력한값-체크인) oldcheckOut > b(입력한값-체크아웃) // comp_in > c(db값) comp_out > d(db값) if ((checkIn.compareTo(comp_in) >= 0 && checkIn.compareTo(comp_out) <= 0 || comp_in.compareTo(checkIn) >= 0 && comp_in.compareTo(oldcheckOut) <= 0)) { // 기간중복될 때 JOptionPane.showMessageDialog(null, (String) "예약날짜가 겹쳐서 예약을 수정합니다.", "메시지", 2); String sqlStr5 = "insert into reservation values(res_seq.nextval,'" + check_cust_name + "','" + newcheckIn + "','" + newcheckOut + "','" + term + "','" + roomno + "','" + staff_cus + "')"; PreparedStatement stmt5 = dbTest.prepareStatement(sqlStr5); ResultSet rs5 = stmt5.executeQuery(); rs5.close(); stmt5.close(); dbTest.commit(); String sqlStr6 = "delete from reservation where C_NAME = '" + check_cust_name + "' and CHECKIN = '" + upcheckIn + "' and CHECKOUT = '" + upcheckOut + "'"; PreparedStatement stmt6 = dbTest.prepareStatement(sqlStr6); ResultSet rs6 = stmt6.executeQuery(); rs6.close(); stmt6.close(); dbTest.commit(); String sqlStr7 = "delete from reservation where (ROWID > (select min(ROWID) from reservation where checkin = '" + newcheckIn + "') and checkin = '" + newcheckIn + "')"; PreparedStatement stmt7 = dbTest.prepareStatement(sqlStr7); ResultSet rs7 = stmt7.executeQuery(); dbTest.commit(); rs7.close(); stmt7.close(); dbTest.commit(); // 테이블 색 변경하기 Date tod = new Date(); SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd"); String todate = sdf6.format(tod); Date today = sdf6.parse(todate); String temproom = ""; String tempin = ""; String tempout = ""; Date tempckin = new Date(); Date tempckout = new Date(); for (int i = 1; i < 11; i++) { String t1 = table1[i].getText(); String t2 = table2[i].getText(); String sqlStr8 = "select ROOMNO,CHECKIN,CHECKOUT from reservation"; PreparedStatement stmt8 = dbTest.prepareStatement(sqlStr8); ResultSet rs8 = stmt8.executeQuery(); while (rs8.next()) { temproom = rs8.getString("ROOMNO"); tempin = rs8.getString("CHECKIN"); tempckin = sdf6.parse(tempin); tempout = rs8.getString("CHECKOUT"); tempckout = sdf6.parse(tempout); if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t1))) { table1[i].setBackground(Color.yellow); break; } else if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t2))) { table2[i].setBackground(Color.yellow); break; } else { table1[i].setBackground(Color.white); table2[i].setBackground(Color.white); } } } } else if ((oldcheckOut.compareTo(comp_in) == -1 && checkIn.compareTo(comp_in) == -1) || (oldcheckOut.compareTo(comp_out) == 1 && checkIn.compareTo(comp_out) == 1)) { String sqlStr5 = "insert into reservation values(res_seq.nextval,'" + check_cust_name + "','" + newcheckIn + "','" + newcheckOut + "'," + term + "," + roomno + ",'" + staff_cus + "')"; dbTest.commit(); PreparedStatement stmt5 = dbTest.prepareStatement(sqlStr5); ResultSet rs5 = stmt5.executeQuery(); String sqlStr6 = "delete from reservation where (ROWID > (select min(ROWID) from reservation where checkin = '" + newcheckIn + "') and checkin = '" + newcheckIn + "')"; PreparedStatement stmt6 = dbTest.prepareStatement(sqlStr6); ResultSet rs6 = stmt6.executeQuery(); dbTest.commit(); rs6.close(); stmt6.close(); rs5.close(); stmt5.close(); Date tod = new Date(); SimpleDateFormat sdf6 = new SimpleDateFormat("yyyy-MM-dd"); String todate = sdf6.format(tod); Date today = sdf6.parse(todate); String temproom = ""; String tempin = ""; String tempout = ""; Date tempckin = new Date(); Date tempckout = new Date(); for (int i = 1; i < 11; i++) { String t1 = table1[i].getText(); String t2 = table2[i].getText(); String sqlStr7 = "select ROOMNO,CHECKIN,CHECKOUT from reservation"; PreparedStatement stmt7 = dbTest.prepareStatement(sqlStr7); ResultSet rs7 = stmt7.executeQuery(); while (rs7.next()) { temproom = rs7.getString("ROOMNO"); tempin = rs7.getString("CHECKIN"); tempckin = sdf6.parse(tempin); tempout = rs7.getString("CHECKOUT"); tempckout = sdf6.parse(tempout); if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t1))) { table1[i].setBackground(Color.yellow); break; } else if ((tempckin.compareTo(today) <= 0 && today.compareTo(tempckout) == -1) && (temproom.equals(t2))) { table2[i].setBackground(Color.yellow); break; } else { table1[i].setBackground(Color.white); table2[i].setBackground(Color.white); } } } } } } rs3.close(); stmt3.close(); } rs2.close(); stmt2.close(); } catch (SQLException | ParseException x) { JOptionPane.showMessageDialog(null, (String) "예약 등록/변경 오류", "메시지", 2); x.printStackTrace(); } } else if (e.getSource() == res_cancel) { try { String custName = res_cust_Input.getText(); String oldcheckin = res_checkin_Input.getText(); String term = res_day_box.getSelectedItem() + ""; String roomno = res_room_box.getSelectedItem() + ""; String sqlStr = "delete from reservation where C_NAME = '" + custName + "' and CHECKIN = '" + oldcheckin + "' and roomno = '" + roomno + "'"; PreparedStatement stmt = dbTest.prepareStatement(sqlStr); ResultSet rs = stmt.executeQuery(); } catch (Exception x) { x.printStackTrace(); } } } private void connectDB() { try { Class.forName("oracle.jdbc.OracleDriver"); dbTest = DriverManager.getConnection("jdbc:oracle:thin:" + "@localhost:1521:XE", username, password); System.out.println("데이터베이스접속 성공 - id: " + username); } catch (SQLException e) { e.printStackTrace(); System.out.println("패패"); } catch (Exception e) { System.out.println("Exception:" + e); } } public static void main(String[] argv) { new TermP(); } }
package com.own.hibernate; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; //OneToMany Mapping @Entity @Table(name="STUDENT_ADDRESS") public class Address { @Id @GeneratedValue private int addressId; private String addressDetails; @OneToMany(cascade=CascadeType.ALL, mappedBy="address") private Set<Student> students = new HashSet<>(); public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } public int getAddressId() { return addressId; } public void setAddressId(int addressId) { this.addressId = addressId; } public String getAddressDetails() { return addressDetails; } public void setAddressDetails(String addressDetails) { this.addressDetails = addressDetails; } }
package palamarchuk.bcalendargroups.dialogs; import android.app.AlertDialog; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import com.daimajia.androidanimations.library.attention.ShakeAnimator; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import palamarchuk.bcalendargroups.GroupAssignmentActions; import palamarchuk.bcalendargroups.QueryMaster; import palamarchuk.bcalendargroups.R; import palamarchuk.bcalendargroups.fragments.FragmentHelper; import palamarchuk.bcalendargroups.pager.GroupEvents; public class SimpleEditText extends AlertDialog.Builder implements QueryMaster.OnCompleteListener { private Context context; private String eventID; private String userID; public SimpleEditText(Context context, String eventID, String userID) { super(context); this.context = context; this.eventID = eventID; this.userID = userID; } @Override public AlertDialog show() { LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); final EditText editText = (EditText) layoutInflater.inflate(R.layout.simple_edit_text, null); AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setView(editText); /** * positive handler beside */ builder.setPositiveButton(context.getString(R.string.ok), null); builder.setNegativeButton(context.getString(R.string.cancel), null); final AlertDialog alertDialog = builder.create(); alertDialog.show(); alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text = editText.getText().toString(); if (text.isEmpty()) { ShakeAnimator animator = new ShakeAnimator(); animator.animate(editText); } else { send(text); } } }); alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alertDialog.dismiss(); } }); return null; } @Override public void complete(String serverResponse) { try { JSONObject json = new JSONObject(serverResponse); if (QueryMaster.isSuccess(json)) { QueryMaster.toast(context, context.getString(R.string.added)); if (context instanceof GroupEvents) { FragmentHelper.updateFragment(((GroupEvents) context).getSupportFragmentManager()); } } else { QueryMaster.toast(context, "error add user note"); } } catch (JSONException e) { e.printStackTrace(); QueryMaster.alert(context, QueryMaster.SERVER_RETURN_INVALID_DATA); } } @Override public void error(int errorCode) { QueryMaster.alert(context, QueryMaster.ERROR_MESSAGE); } private void send(String text) { try { GroupAssignmentActions.addUserNote(context, this, eventID, userID, text); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } } }
package test; import com.ljh.dto.User; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @Author laijinhan * @date 2020/9/24 10:20 下午 */ public class myTest { @Test public void test(){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); User user = context.getBean("user", User.class); System.out.println(user.name); } }
package me.leaver.bloger.app.mvp.model; /** * Created by zhiyuan.lzy on 2016/3/19. */ public class CookieValue { private String cookie; public CookieValue() { } public String getCookie() { return cookie; } public void setCookie(String cookie) { this.cookie = cookie; } @Override public String toString() { return "CookieValue{" + "cookie='" + cookie + '\'' + '}'; } }
package com.don.blacklist.app.Model; import java.util.ArrayList; import java.util.List; /** * Created by donpironet on 28/04/14. */ public class Conversations { private String mNumber; private String mId; private List<SmsObjects> mSmsObjectsList; public List<SmsObjects> getSmsObjectsList() { return mSmsObjectsList; } public void addTextMessage(SmsObjects sms) { if(mSmsObjectsList == null) mSmsObjectsList = new ArrayList<SmsObjects>(); mSmsObjectsList.add(sms); } public String getNumber() { return mNumber; } public void setNumber(String number) { this.mNumber = number; } public String getId() { return mId; } public void setId(String id) { this.mId = id; } }
package com.taim.backendservice.configuration; import com.taim.backendservice.exception.InternalServerErrorException; import com.taim.backendservice.exception.ResourceNotFoundException; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; import org.springframework.stereotype.Component; import org.springframework.web.client.ResponseErrorHandler; import java.io.IOException; import java.nio.charset.Charset; @Component public class RestTemplateErrorHandler implements ResponseErrorHandler { @Override public boolean hasError(ClientHttpResponse clientHttpResponse) throws IOException { return clientHttpResponse.getStatusCode().is4xxClientError() || clientHttpResponse.getStatusCode().is5xxServerError(); } @Override public void handleError(ClientHttpResponse clientHttpResponse) throws IOException { String errorEntity = IOUtils.toString(clientHttpResponse.getBody(), Charset.forName("UTF-8")); switch (clientHttpResponse.getStatusCode()) { case NOT_FOUND: throw new ResourceNotFoundException(errorEntity); default: throw new InternalServerErrorException(errorEntity); } } }
package com.min.edu.model; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.min.edu.dto.MemberDTO; @Service public class MemberServiceImpl implements MemberIService { @Autowired private MemberIDao dao; @Override public boolean signUpMember(MemberDTO dto) { return dao.signUpMember(dto); } @Override public int idDuplicateCheck(String id) { return dao.idDuplicateCheck(id); } @Override public MemberDTO loginMember(Map<String, String> map) { return dao.loginMember(map); } }
package co.yoyu.sidebar.view; import java.util.ArrayList; import java.util.List; import wei.mark.standout.StandOutWindow; import wei.mark.standout.Utils; import wei.mark.standout.constants.StandOutFlags; import wei.mark.standout.ui.Window; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Process; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import co.yoyu.sidebar.ContentAdapter; import co.yoyu.sidebar.FlowAdapter; import co.yoyu.sidebar.R; import co.yoyu.sidebar.cache.LocalImageCache; import co.yoyu.sidebar.db.AppInfoCacheDB; import co.yoyu.sidebar.db.AppInfoModel; import co.yoyu.sidebar.drag.DragController; import co.yoyu.sidebar.drag.DragLayer; import co.yoyu.sidebar.handler.HandlerDragController; import co.yoyu.sidebar.handler.HandlerDragLayer; import co.yoyu.sidebar.handler.HandlerWindowDragController; import co.yoyu.sidebar.utils.Constant; import co.yoyu.sidebar.utils.ParseUtils; /** * */ public class SideBar extends StandOutWindow implements OnGestureListener { public static final int WINDOW_ID_SIDE_BAR = 1; public static final int WINDOW_ID_SIDE_BAR_HANDLER = 2; public static final int CODE_SHOW_SIDE_BAR_WINDOW = 6; public static final int CODE_SHOW_SIDE_BAR_HANDLER_WINDOW = 7; private PackageManager mPackageManager; private WindowManager mWindowManager; private ArrayList<AppInfoModel> mFlowData = new ArrayList<AppInfoModel>(); private ArrayList<AppInfoModel> mContentData = new ArrayList<AppInfoModel>(); private FlowAdapter mFlowAdapter = null; private ContentAdapter mContentAdapter = null; private LayoutInflater mInflater; private SideBarContentPanel mContentPanel; private SideBarFlowPanel mFlowPanel; private TextView mEditButton; private SideBarLinearLayout mSideBarLinearLayout; private ImageView mLeftDrag; private ImageView mRightDrag; private ImageView mWindowLeftDrag; private ImageView mWindowRightDrag; private View mFlowList; private DragLayer mDragLayer; private DragController mDragController; /**handler in Window body dragLayer*/ private HandlerDragLayer mHandlerDragLayer; /**handler in Window dragLayer*/ private HandlerDragLayer mWindowHandlerDragLayer; private HandlerDragController mWindowHandlerController; private HandlerWindowDragController mHandlerWindowController; private static final long MSG_DELAY_TIME = 3000L; private static final int MSG_LEFT_EXPEND_TO_NORMAL = 1; private static final int MSG_RIGHT_EXPEND_TO_NORMAL = 2; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch(msg.what) { case MSG_LEFT_EXPEND_TO_NORMAL: leftExpendToNormal(); break; case MSG_RIGHT_EXPEND_TO_NORMAL: rightExpendToNormal(); break; } } }; /**WindowId*/ private int mWindowID; /**HandlerWindowId*/ private int mHandlerWindowID; //正常模式 public static final int MODE_NORMAL = 0; //拖拽块模式 public static final int MODE_DRAG = 1; //编辑模式 public static final int MODE_EDIT = 2; //拖拽块展开模式 public static final int MODE_EXPEND = 3; //拖拽块展开且拖拽模式 public static final int MODE_EXPEND_DRAG = 4; //编辑模式 拖拽 public static final int MODE_EDIT_DRAG = 5; private int mMode = MODE_NORMAL; //window body view private View mWindowBody; private View mHandlerWindowBody; public static final int POSITION_LEFT_HALF = 0; public static final int POSITION_RIGHT_HALF = 1; private int mPosition = POSITION_LEFT_HALF; private Animation mLeftEditExpanAnimation; /** * Helper for detecting touch gestures. */ private GestureDetector mGestureDetector; public static void showSidebar(Context context) { sendData(context, SideBar.class, DISREGARD_ID, CODE_SHOW_SIDE_BAR_WINDOW,null, null, DISREGARD_ID); } public static void showSideBarHandler(Context context) { sendData(context, SideBar.class, DISREGARD_ID, CODE_SHOW_SIDE_BAR_HANDLER_WINDOW,null, null, DISREGARD_ID); } @Override public void onCreate() { super.onCreate(); mPackageManager = getPackageManager(); mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); mInflater = LayoutInflater.from(this); mDragController = new DragController(this); mHandlerWindowController = new HandlerWindowDragController(this); mHandlerWindowController.setSideBar(this); mGestureDetector = new GestureDetector(this, this); mLeftEditExpanAnimation = AnimationUtils.loadAnimation(this, R.anim.left_to_expand); registerBroadCastReceiver(); } @Override public String getAppName() { return "Sidebar"; } @Override public int getAppIcon() { return R.drawable.ic_launcher; } public int getPosition(){ return mPosition; } /** * create two window attach View * one is body view the other is handler view * */ @Override public void createAndAttachView(final int id, FrameLayout frame) { if(id == WINDOW_ID_SIDE_BAR) { mWindowID = id; // inflate the Window Body view ,it's invisable by default. mWindowBody = (FrameLayout) mInflater.inflate(R.layout.sidebar_frame, frame, true); mWindowBody.setOnTouchListener(null); mDragLayer = (DragLayer) mWindowBody.findViewById(R.id.drag_layer); mDragLayer.setDragController(mDragController); mDragLayer.setSideBar(this); mSideBarLinearLayout = (SideBarLinearLayout) mWindowBody.findViewById(R.id.sidebar); mFlowList = mDragLayer.findViewById(R.id.sidebar_content); // setup content panel ui and data mContentPanel = (SideBarContentPanel) mSideBarLinearLayout.findViewById(R.id.appgrid); mContentPanel.setDragController(mDragController); mContentPanel.setSideBar(this); loadContentData(); mContentAdapter = new ContentAdapter(this, R.layout.app_row, mContentData); mContentPanel.setAdapter(mContentAdapter); // setup flow panel ui and data mFlowPanel = (SideBarFlowPanel) mSideBarLinearLayout.findViewById(R.id.flow); mFlowPanel.setDragController(mDragController); mFlowPanel.setSideBar(this); loadFlowData(); mFlowAdapter = new FlowAdapter(this, mFlowData); mFlowPanel.setAdapter(mFlowAdapter); mDragController.addDropTarget(mContentPanel); mDragController.addDropTarget(mFlowPanel); // setup edit button mEditButton = (TextView) mSideBarLinearLayout.findViewById(R.id.edit); mEditButton.setOnClickListener(mEditClickListener); mHandlerDragLayer = (HandlerDragLayer) mWindowBody.findViewById(R.id.handler_drag_layer); mHandlerDragLayer.setSideBar(this); mHandlerDragLayer.setWindowDragControl(mHandlerWindowController); mLeftDrag = (ImageView) mHandlerDragLayer.findViewById(R.id.preview_left); mLeftDrag.setOnTouchListener(mDragTouchListener); mRightDrag = (ImageView) mHandlerDragLayer.findViewById(R.id.preview_right); mRightDrag.setOnTouchListener(mDragTouchListener); // asyn load content data asynLoadContentData(); } else { mHandlerWindowID = id; FrameLayout windowBody = (FrameLayout) mInflater.inflate(R.layout.sidebar_handler, frame, true); windowBody.setOnTouchListener(null); mWindowHandlerController = new HandlerDragController(this); mWindowHandlerDragLayer = (HandlerDragLayer) windowBody.findViewById(R.id.window_handler_drag_layer); mWindowHandlerDragLayer.setDragController(mWindowHandlerController); mWindowHandlerDragLayer.setSideBar(this); mWindowLeftDrag = (ImageView) mWindowHandlerDragLayer.findViewById(R.id.window_preview_left); mWindowLeftDrag.setOnTouchListener(mDragTouchListener); mWindowRightDrag = (ImageView) mWindowHandlerDragLayer.findViewById(R.id.window_preview_right); mWindowRightDrag.setOnTouchListener(mDragTouchListener); int margin = getResources().getDimensionPixelSize(R.dimen.sidesar_handler_height); mWindowHandlerController.setSideBar(this, margin / 2); } } @Override public StandOutLayoutParams getParams(int id, Window window) { if(id == mWindowID) { return new StandOutLayoutParams(id, StandOutLayoutParams.WRAP_CONTENT, StandOutLayoutParams.MATCH_PARENT, 0, 0); } int margin = getResources().getDimensionPixelSize(R.dimen.sidesar_handler_height); int y = (mWindowManager.getDefaultDisplay().getHeight() - margin) /2; return new StandOutLayoutParams(id, StandOutLayoutParams.WRAP_CONTENT, StandOutLayoutParams.WRAP_CONTENT, 0, y); } @Override public int getFlags(int id) { return super.getFlags(id) | StandOutFlags.FLAG_ADD_FUNCTIONALITY_DROP_DOWN_DISABLE | StandOutFlags.FLAG_BODY_MOVE_ENABLE; } @Override public void onReceiveData(int id, int requestCode, Bundle data, Class<? extends StandOutWindow> fromCls, int fromId) { switch (requestCode) { case CODE_SHOW_SIDE_BAR_WINDOW: show(WINDOW_ID_SIDE_BAR); break; case CODE_SHOW_SIDE_BAR_HANDLER_WINDOW: show(WINDOW_ID_SIDE_BAR_HANDLER); break; default: break; } } @Override public boolean onTouchBody(final int id, final Window window, final View view, MotionEvent event) { removeCloseExpendMessage(); if(id == mWindowID && (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_OUTSIDE)) { doBackOperate(); } if(!Utils.isSet(window.flags, StandOutFlags.FLAG_WINDOW_MOVE_ENABLE)) { return false; } if (event.getAction() == MotionEvent.ACTION_MOVE) { final StandOutLayoutParams params = (StandOutLayoutParams) window.getLayoutParams(); if (mPosition == POSITION_RIGHT_HALF && params.x < mWindowManager.getDefaultDisplay().getWidth() / 2 - mFlowList.getWidth()) { // not mPosition = POSITION_LEFT_HALF; changeHandlerPosition(mRightDrag, mLeftDrag); mLeftDrag.setVisibility(View.VISIBLE); mRightDrag.setVisibility(View.GONE); mFlowList.setVisibility(View.VISIBLE); mFlowList.setBackgroundResource(R.drawable.bar_left); StandOutLayoutParams originalParams = getParams(id, window); params.width = originalParams.width; params.height = originalParams.height; mSideBarLinearLayout.removeAllViews(); setLeftHandlerDragLayerPosition(); System.out.println("AddView"); mSideBarLinearLayout.addView(mFlowList); mSideBarLinearLayout.addView(mHandlerDragLayer); mSideBarLinearLayout.addView(mContentPanel); mContentPanel.setVisibility(View.GONE); mSideBarLinearLayout.requestLayout(); mSideBarLinearLayout.invalidate(); updateViewLayout(id, params); } else if(mPosition == POSITION_LEFT_HALF && params.x >= mWindowManager.getDefaultDisplay().getWidth() / 2 - mFlowList.getWidth()) { mPosition = POSITION_RIGHT_HALF; changeHandlerPosition(mLeftDrag, mRightDrag); mLeftDrag.setVisibility(View.GONE); mRightDrag.setVisibility(View.VISIBLE); mFlowList.setVisibility(View.VISIBLE); mFlowList.setBackgroundResource(R.drawable.bar_right); StandOutLayoutParams originalParams = getParams(id, window); params.width = originalParams.width; params.height = originalParams.height; mSideBarLinearLayout.removeAllViews(); mContentPanel.setVisibility(View.GONE); mSideBarLinearLayout.addView(mHandlerDragLayer); mSideBarLinearLayout.addView(mContentPanel); mSideBarLinearLayout.addView(mFlowList); mSideBarLinearLayout.setTopView(mHandlerDragLayer); //set handler position setRightHandlerDragLayerPosition(); mSideBarLinearLayout.requestLayout(); mSideBarLinearLayout.invalidate(); updateViewLayout(id, params); }//end if } else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) { doActionUp(id, window); }//end if return false; } private void setLeftHandlerDragLayerPosition() { ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = (int)getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = 0; } private void setRightHandlerDragLayerPosition() { ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = (int)getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); } void doBackOperate() { if(mPosition == POSITION_LEFT_HALF && mMode == MODE_EXPEND) { leftExpendToNormal(); } else if(mPosition == POSITION_RIGHT_HALF && mMode == MODE_EXPEND) { rightExpendToNormal(); } } private void changeHandlerPosition(ImageView oldView, ImageView newView) { FrameLayout.LayoutParams oldParams = (FrameLayout.LayoutParams) oldView.getLayoutParams(); int topMargin = oldParams.topMargin; FrameLayout.LayoutParams newParams = (FrameLayout.LayoutParams) newView.getLayoutParams(); newParams.topMargin = topMargin; } /** * TODO 拖动结束的时候设置 * * @author user * @date 2013-6-3 * @return void */ private void doActionUp(final int id, final Window window) { getWindow().removeFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); getHandlerWindow().removeFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); final StandOutLayoutParams params = (StandOutLayoutParams) window.getLayoutParams(); // if touch edge,这个时候是大块的 if (params.x <= - mFlowList.getWidth()) { //TO LEFT NORMAL expendDragToLeftNormal(id, params, window); } else if (params.x > - mFlowList.getWidth() && params.x <= mWindowManager.getDefaultDisplay().getWidth() / 2- mFlowList.getWidth()) { //TO LEFT EXPEND expendDragToLeftExpend(id, params, window); } else if (params.x > mWindowManager.getDefaultDisplay().getWidth() / 2- mFlowList.getWidth() && params.x <= mWindowManager.getDefaultDisplay().getWidth() - mFlowList.getWidth()) { //TO RIGHT EXPEND expendDragToRightExpend(id, params, window); } else { //TO RIGHT NORMAL expendDragToRightNormal(id, params, window); } } public String getPersistentNotificationMessage(int id) { return "Click to close all windows."; } public Intent getPersistentNotificationIntent(int id) { return StandOutWindow.getCloseAllIntent(this, SideBar.class); } private OnTouchListener mDragTouchListener = new OnTouchListener() { public boolean onTouch(View v, MotionEvent ev) { if(ev.getAction() == MotionEvent.ACTION_DOWN) { mHandlerWindowController.dispatchTouch(ev); mWindowHandlerController.dispatchTouch(ev); } boolean retValue = mGestureDetector.onTouchEvent(ev); return retValue; } }; private OnClickListener mEditClickListener = new OnClickListener() { @Override public void onClick(View v) { removeCloseExpendMessage(); if(mContentPanel.isShown()){ editToExpend(); } else { expendToEdit(); }//end if } }; private void loadFlowData() { mFlowData.clear(); mFlowData = AppInfoCacheDB.getInstance(SideBar.this).getAllFlowPanelItems(); } private void loadContentData() { mContentData.clear(); } private void asynLoadContentData() { new Thread(new Runnable() { @Override public void run() { ArrayList<AppInfoModel> contentPanelItems = AppInfoCacheDB.getInstance(SideBar.this).getAllContentPanelItems(); if (contentPanelItems.size() > 0) { mContentData.clear(); for (AppInfoModel appInfoModel : contentPanelItems) { final AppInfoModel model = appInfoModel; mHandler.post(new Runnable() { @Override public void run() { mContentData.add(model); mContentAdapter.notifyDataSetChanged(); }// end run });// end post }// end for } else { final List<ResolveInfo> systemInfo = ParseUtils.getAllApps(SideBar.this); for (ResolveInfo resolveApp : systemInfo) { final AppInfoModel appInfoModel = new AppInfoModel(); appInfoModel.packageName = resolveApp.activityInfo.packageName; appInfoModel.className = resolveApp.activityInfo.name; appInfoModel.title = resolveApp.loadLabel(mPackageManager).toString(); appInfoModel.iconkey = resolveApp.activityInfo.packageName + appInfoModel.title; appInfoModel.container = Constant.CONTAINER_CONTENT_PANEL; long result = AppInfoCacheDB.getInstance(SideBar.this).insertSiderBarItems(appInfoModel); if (result == -1) continue; BitmapDrawable bitmapDrawable = (BitmapDrawable) resolveApp .loadIcon(mPackageManager); LocalImageCache.getInstance(SideBar.this).put(appInfoModel.iconkey, bitmapDrawable.getBitmap()); mHandler.post(new Runnable() { @Override public void run() { mContentData.add(appInfoModel); mContentAdapter.notifyDataSetChanged(); } }); } } } }).start(); } //when destory clear all database data and save new data from listView @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); unRigisterBroadcastReceiver(); if(mFlowAdapter!=null) mFlowAdapter.onDestory(); AppInfoCacheDB.getInstance(this).deleteAllFlowPanelItems(); if(mFlowPanel!=null){ ArrayList<AppInfoModel> list = (ArrayList<AppInfoModel>) ((FlowAdapter)mFlowPanel.getAdapter()).getActivityInfoList(); for(AppInfoModel model:list){ model.container = Constant.CONTAINER_FLOW_PANEL; try { AppInfoCacheDB.getInstance(this).insertSiderBarItems(model); } catch (Exception e) { e.printStackTrace(); } } } } public void setMode(int mode) { this.mMode = mode; } public int getMode() { return mMode; } public Window getWindow() { return super.getWindow(mWindowID); } public Window getHandlerWindow() { return super.getWindow(mHandlerWindowID); } public View getWindowBody() { return mWindowBody; } @Override public boolean onDown(MotionEvent arg0) { // TODO Auto-generated method stub return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { System.out.println("velocityX="+velocityX); if (mMode == MODE_NORMAL) { if(mPosition == POSITION_RIGHT_HALF) { if(velocityX < 0) { rightNormalToExpend(); }//end if } else { if(velocityX > 0) { leftNormalToExpend(); }//end if }//end if return true; } else if(mMode == MODE_EXPEND) { if(mPosition == POSITION_RIGHT_HALF) { if(velocityX > 0) { rightExpendToNormal(); }//end if } else { if(velocityX < 0) { leftExpendToNormal(); }//end if }//end if }//end if return false; } @Override public void onLongPress(MotionEvent arg0) { if(mMode == MODE_NORMAL) { normalToDrag(); } else if(mMode == MODE_EXPEND) { expendToExpendDrag(); }//end if } @Override public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent arg0) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent arg0) { if(mPosition == POSITION_LEFT_HALF) { if (mMode == MODE_NORMAL) { leftNormalToExpend(); } else if (mMode == MODE_EXPEND) { leftExpendToNormal(); }//end if } else { if (mMode == MODE_NORMAL) { rightNormalToExpend(); } else if (mMode == MODE_EXPEND) { rightExpendToNormal(); } }//end if return true; } private void expendToEdit() { mEditButton.setText(R.string.edit_button_state_ok); mHandlerDragLayer.setVisibility(View.GONE); if(mPosition == POSITION_RIGHT_HALF){ mFlowList.setBackgroundResource(R.drawable.bar_right); mContentPanel.setVisibility(View.VISIBLE); mSideBarLinearLayout.setBackgroundResource(R.drawable.multiwindow_edit_bg); StandOutLayoutParams layoutParams = (StandOutLayoutParams)getWindow(mWindowID).getLayoutParams(); layoutParams.x = 0; layoutParams.y = 0; updateViewLayout(mWindowID, layoutParams); mMode = MODE_EDIT; getWindow(mWindowID).removeFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); } else { mFlowList.setBackgroundResource(R.drawable.bar_left); mLeftEditExpanAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation arg0) { } @Override public void onAnimationRepeat(Animation arg0) { } @Override public void onAnimationEnd(Animation arg0) { mContentPanel.setVisibility(View.VISIBLE); mSideBarLinearLayout.setBackgroundResource(R.drawable.multiwindow_edit_bg); mSideBarLinearLayout.requestLayout(); mMode = MODE_EDIT; getWindow(mWindowID).removeFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); } }); mContentPanel.startAnimation(mLeftEditExpanAnimation); } removeCloseExpendMessage(); } //edit state to expend private void editToExpend() { mEditButton.setText(R.string.edit_button_state_edit); mContentPanel.setVisibility(View.GONE); mSideBarLinearLayout.setBackgroundResource(0); mMode = MODE_EXPEND; mHandlerDragLayer.setVisibility(View.VISIBLE); getWindow(mWindowID).addFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); if(mPosition == POSITION_RIGHT_HALF){ StandOutLayoutParams layoutParams = (StandOutLayoutParams)getWindow(mWindowID).getLayoutParams(); layoutParams.y = 0; layoutParams.x = mWindowManager.getDefaultDisplay().getWidth() - mFlowList.getWidth() - mRightDrag.getWidth() -getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); updateViewLayout(mWindowID, layoutParams); mFlowList.setBackgroundResource(R.drawable.bar_right); sendCloseRightExpendMessage(); } else { sendCloseLeftExpendMessage(); mFlowList.setBackgroundResource(R.drawable.bar_left); } } //normal state to handler drag state private void normalToDrag() { Window window = getWindow(mHandlerWindowID); mMode = MODE_DRAG; window.addFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); mWindowHandlerController.startDrag(); removeCloseExpendMessage(); } //handler expend state to handler expend drag state private void expendToExpendDrag() { Window window = getWindow(mWindowID); mMode = MODE_EXPEND_DRAG; window.addFlag(StandOutFlags.FLAG_WINDOW_MOVE_ENABLE); mHandlerWindowController.startDrag(); removeCloseExpendMessage(); } //expend drag to left expend private void expendDragToLeftExpend(int id, StandOutLayoutParams params, Window window) { mLeftDrag.setVisibility(View.VISIBLE); mRightDrag.setVisibility(View.GONE); mFlowList.setVisibility(View.VISIBLE); mFlowList.setBackgroundResource(R.drawable.bar_left); StandOutLayoutParams originalParams = getParams(id, window); params.y = 0; params.x = 0; params.width = originalParams.width; params.height = originalParams.height; updateViewLayout(id, params); setMode(MODE_EXPEND); sendCloseLeftExpendMessage(); } //expend drag to left normal private void expendDragToLeftNormal(int id, StandOutLayoutParams params, Window window) { mLeftDrag.setVisibility(View.VISIBLE); Window handlerWindow = getHandlerWindow(); StandOutLayoutParams handlerParams = handlerWindow.getLayoutParams(); handlerParams.y = ((FrameLayout.LayoutParams)mLeftDrag.getLayoutParams()).topMargin; updateViewLayout(mHandlerWindowID, handlerParams); mHandlerDragLayer.setVisibility(View.GONE); mRightDrag.setVisibility(View.GONE); mFlowList.setVisibility(View.GONE); params.y = 0; params.x = 0; updateViewLayout(id, params); mWindowHandlerDragLayer.setVisibility(View.VISIBLE); mWindowLeftDrag.setVisibility(View.VISIBLE); setMode(MODE_NORMAL); removeCloseExpendMessage(); } //expend drag to right expend private void expendDragToRightExpend(int id, StandOutLayoutParams params, Window window) { mLeftDrag.setVisibility(View.GONE); mRightDrag.setVisibility(View.VISIBLE); mFlowList.setVisibility(View.VISIBLE); mFlowList.setBackgroundResource(R.drawable.bar_right); StandOutLayoutParams originalParams = getParams(id, window); params.y = 0; params.x = mWindowManager.getDefaultDisplay().getWidth() - mFlowList.getWidth() - mRightDrag.getWidth() -getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); params.width = originalParams.width; params.height = originalParams.height; updateViewLayout(id, params); setMode(MODE_EXPEND); sendCloseRightExpendMessage(); } //expend drag to right normal private void expendDragToRightNormal(int id, StandOutLayoutParams params, Window window) { mFlowList.setVisibility(View.GONE); mLeftDrag.setVisibility(View.GONE); mRightDrag.setVisibility(View.VISIBLE); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = 0; StandOutLayoutParams originalParams = getParams(id, window); params.y = 0; params.x = mWindowManager.getDefaultDisplay().getWidth() - mRightDrag.getWidth(); params.width = originalParams.width; params.height = originalParams.height; updateViewLayout(id, params); setMode(MODE_NORMAL); removeCloseExpendMessage(); } public void leftExpendToNormal() { final StandOutLayoutParams params = (StandOutLayoutParams) getWindow(mHandlerWindowID).getLayoutParams(); mWindowHandlerDragLayer.setVisibility(View.VISIBLE); mWindowLeftDrag.setVisibility(View.VISIBLE); mWindowRightDrag.setVisibility(View.INVISIBLE); mDragLayer.setVisibility(View.INVISIBLE); mHandlerDragLayer.setVisibility(View.INVISIBLE); mFlowList.setVisibility(View.INVISIBLE); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = 0; params.x = 0; mMode = MODE_NORMAL; updateViewLayout(mHandlerWindowID, params); getHandlerWindow().requestFocus(); removeCloseExpendMessage(); } private void leftNormalToExpend() { final StandOutLayoutParams handlerParams = (StandOutLayoutParams) getWindow(mHandlerWindowID).getLayoutParams(); final StandOutLayoutParams params = (StandOutLayoutParams) this.getParams(mWindowID, getWindow()); mDragLayer.setVisibility(View.VISIBLE); mHandlerDragLayer.setVisibility(View.VISIBLE); mWindowHandlerDragLayer.setVisibility(View.INVISIBLE); mFlowList.setVisibility(View.VISIBLE); handlerParams.x = 0; updateViewLayout(mHandlerWindowID, handlerParams); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = (int)getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).topMargin = handlerParams.y; params.x = 0; params.y = 0; updateViewLayout(mWindowID, params); mMode = MODE_EXPEND; sendCloseLeftExpendMessage(); } public void rightExpendToNormal() { final StandOutLayoutParams params = (StandOutLayoutParams) getWindow(mHandlerWindowID).getLayoutParams(); mWindowHandlerDragLayer.setVisibility(View.VISIBLE); mWindowLeftDrag.setVisibility(View.INVISIBLE); mWindowRightDrag.setVisibility(View.VISIBLE); mDragLayer.setVisibility(View.INVISIBLE); mHandlerDragLayer.setVisibility(View.INVISIBLE); mFlowList.setVisibility(View.INVISIBLE); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = 0; mMode = MODE_NORMAL; params.x = mWindowManager.getDefaultDisplay().getWidth() - mRightDrag.getWidth(); updateViewLayout(mHandlerWindowID, params); getHandlerWindow().requestFocus(); removeCloseExpendMessage(); } private void rightNormalToExpend() { final StandOutLayoutParams handlerParams = (StandOutLayoutParams) getWindow(mHandlerWindowID).getLayoutParams(); final StandOutLayoutParams params = (StandOutLayoutParams) this.getParams(mWindowID, getWindow()); mDragLayer.setVisibility(View.VISIBLE); mHandlerDragLayer.setVisibility(View.VISIBLE); mWindowHandlerDragLayer.setVisibility(View.INVISIBLE); mFlowList.setVisibility(View.VISIBLE); updateViewLayout(mHandlerWindowID, handlerParams); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).leftMargin = 0; ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).rightMargin = (int)getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); ((LinearLayout.LayoutParams)mHandlerDragLayer.getLayoutParams()).topMargin = handlerParams.y; mMode = MODE_EXPEND; params.y = 0; params.x = mWindowManager.getDefaultDisplay().getWidth() - mFlowList.getWidth() - mRightDrag.getWidth() -getResources().getDimensionPixelSize(R.dimen.flow_handler_left_margin); updateViewLayout(mWindowID, params); sendCloseRightExpendMessage(); } public boolean onKeyEvent(int id, Window window, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: if(mPosition == POSITION_LEFT_HALF && mMode == MODE_EXPEND) { leftExpendToNormal(); } else if(mPosition == POSITION_RIGHT_HALF && mMode == MODE_EXPEND) { rightExpendToNormal(); } else if(mMode == MODE_EDIT) { editToExpend(); return true; }//end if break; } } else if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_BACK: if (event.isLongPress()) { SideBar.this.stopSelf(); android.os.Process.killProcess(Process.myPid()); } break; default: break; } } return false; } /** * TODO * @author zhangf * @date 2013-6-17 * @return void */ public void notifyDataSize(int count) { // TODO Auto-generated method stub } private void registerBroadCastReceiver(){ IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_LOCALE_CHANGED); SideBar.this.registerReceiver(mConfigChangeReceiver, intentFilter); } BroadcastReceiver mConfigChangeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context arg0, Intent arg1) { // TODO Auto-generated method stub mContentAdapter.chageLocal(); mFlowAdapter.chageLoacal(); mEditButton.setText(R.string.edit_button_state_edit); } }; private void unRigisterBroadcastReceiver(){ unregisterReceiver(mConfigChangeReceiver); } /** * close left handler */ private void sendCloseLeftExpendMessage() { removeCloseExpendMessage(); mHandler.sendEmptyMessageDelayed(MSG_LEFT_EXPEND_TO_NORMAL, MSG_DELAY_TIME); } private void removeCloseExpendMessage() { if(mHandler.hasMessages(MSG_LEFT_EXPEND_TO_NORMAL)) { mHandler.removeMessages(MSG_LEFT_EXPEND_TO_NORMAL); } if(mHandler.hasMessages(MSG_RIGHT_EXPEND_TO_NORMAL)) { mHandler.removeMessages(MSG_RIGHT_EXPEND_TO_NORMAL); } } private void sendCloseRightExpendMessage() { removeCloseExpendMessage(); mHandler.sendEmptyMessageDelayed(MSG_RIGHT_EXPEND_TO_NORMAL, MSG_DELAY_TIME); } }
package com.github.colinjeremie.justpickafilm.activities; import android.content.Intent; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.Menu; import android.view.MenuItem; import com.github.colinjeremie.justpickafilm.MyApplication; import com.github.colinjeremie.justpickafilm.R; import com.github.colinjeremie.justpickafilm.adapters.MovieAdapter; import com.github.colinjeremie.justpickafilm.models.Movie; import com.github.colinjeremie.justpickafilm.models.User; import java.util.ArrayList; import java.util.Random; public class MainActivity extends AppCompatActivity implements MovieAdapter.MovieItemListener, SearchView.OnQueryTextListener { private User mUser; private RecyclerView mRecyclerView; private MovieAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mUser = ((MyApplication)getApplication()).user; mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setHasFixedSize(true); StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, 1); mRecyclerView.setLayoutManager(manager); ArrayList<Movie> dummyData = new ArrayList<>(); for (int i = 0; i < 10; i++){ Movie tmp = new Movie(); tmp.setTitle("title " + i); dummyData.add(tmp); } mAdapter = new MovieAdapter(this, this, dummyData); mRecyclerView.setAdapter(mAdapter); } @Override public void onMovieShared(Movie movie) { String title = movie.getTitle(); title = title == null ? "" : title; Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.movie_shared_text, title)); sendIntent.setType("text/plain"); startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to))); } @Override public void onMovieAddToFavorites(Movie movie) { movie.setUserId(mUser.getId()); movie.update(); mUser.addMovie(movie); } @Override public void onMovieRemoveFromFavorites(Movie movie) { movie.setUserId(null); movie.update(); mUser.removeMovie(movie); } @Override public void onMovieClicked(Movie movie) { Intent intent = new Intent(this, MovieDetailActivity.class); intent.putExtra(MovieDetailActivity.MOVIE, movie); startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_home, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(this); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.action_random_research) { pickRandomFilm(); } return super.onOptionsItemSelected(item); } private void pickRandomFilm() { int min = 0, max = mAdapter.getItemCount() - 1; if (max > 0) { Random rand = new Random(); int position = rand.nextInt((max - min) + 1) + min; if (position >= 0 && position < max){ Movie movie = mAdapter.getItem(position); if (movie != null) { onMovieClicked(movie); } } } } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { mAdapter.filter(newText); return true; } }
/* Nicholas King, CSC 131-03, Assignment 2 * This program uses command line arguments to log start and stop times of particular task and saves the information in a text file title "tm.txt" * List of acceptable command line arguments can be found in TM.md provided */ import java.time.*; import java.time.temporal.ChronoUnit; import java.io.*; import java.sql.Time; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.LocalDateTime; import java.util.*; import java.util.concurrent.TimeUnit; import javax.sound.sampled.Line; import java.time.*; public class TM { public static void main(String[] args) throws IOException { String fileName = "tm.txt"; TaskLog log = new TaskLog(fileName); LinkedList<TaskLogEntry> entries = new LinkedList<TaskLogEntry>(); switch(args[0]) { case "start" : log.writeLine(LocalDateTime.now() + "\t" + args[1] + "\t" + "start"); break; case "stop" : log.writeLine(LocalDateTime.now() + "\t" + args[1] + "\t" + "stop"); break; case "describe" : String[] taskDescription = Arrays.copyOfRange(args, 2, args.length); if (args[3] == null) log.writeLine(LocalDateTime.now() + "\t" + args[1] + "\t" + "describe" + "\t" + args[2]); log.writeLine(LocalDateTime.now() + "\t" + args[1] + "\t" + "describe" + "\t" + args[2] + "\t" + args[3]); break; case "size" : log.writeLine(LocalDateTime.now() + "\t" + args[1] + "\t" + "size" + "\t" + args[2] + "\t"); break; case "summary" : entries = log.read(); if (args.length > 1) { Task task = new Task(args[1], entries); System.out.print(task); } else { System.out.println(summary(entries)); } case "rename" : cmdRename(args); break; case "delete" : cmdRename(args); break; default : usage(); break; } } private static void usage() { String s = ""; s += "To use this program enter one of the following commands with <your input here>\n"; s += "start/stop <task name> to start or stop a task\n"; s += "describe <task name> <description> <(optional) S/M/L> to add a description to a task\n"; s += "size <task name> <S/M/L> to add a size description to a task\n"; s += "summary <task> to view information from a particular task\n"; s += "summary to view information from all tasks\n"; } static StringBuilder summary(LinkedList<TaskLogEntry> entries) { TreeSet<String> taskNames = new TreeSet<String>(); TreeSet<String> smallTasks = new TreeSet<String>(); TreeSet<String> mediumTasks = new TreeSet<String>(); TreeSet<String> largeTasks = new TreeSet<String>(); long totalSecondsForAllTasks = 0; long totalSecondsOnTask = 0; int sCount = 0, mCount = 0, lCount = 0; long sMin, sMax, sAvg, mMin = 0, mMax, mAvg, lMin, lMax, lAvg; StringBuilder summaryText = new StringBuilder(); for (TaskLogEntry entry : entries) { if (!entry.name.equals("DELETED")) { taskNames.add(entry.name); } } for (String taskName : taskNames) { Task task = new Task(taskName, entries); totalSecondsForAllTasks += task.elapsedSeconds; if (task.size.equals("S")) { smallTasks.add(task.name); sCount++; } if (task.size.equals("M")) { mediumTasks.add(task.name); mCount++; } if (task.size.equals("L")) { largeTasks.add(task.name); lCount++; } summaryText.append(task + "\n"); } summaryText.append("Total time spent on all tasks = " + toHoursMinutesSeconds(totalSecondsForAllTasks)); if (sCount >= 2) { taskStats(smallTasks, "S", entries); } if (mCount >= 2) { taskStats(mediumTasks, "M", entries); } if (lCount >= 2) { taskStats(largeTasks, "L", entries); } return summaryText; } static String toHoursMinutesSeconds(long totalSeconds) { long hours = TimeUnit.SECONDS.toHours(totalSeconds); long minutes = TimeUnit.SECONDS.toMinutes(totalSeconds) - (TimeUnit.SECONDS.toHours(totalSeconds) * 60); long seconds = TimeUnit.SECONDS.toSeconds(totalSeconds) - (TimeUnit.SECONDS.toMinutes(totalSeconds) *60); String s = (Long.toString(hours) + ":" + Long.toString(minutes) + ":" + Long.toString(seconds)); return s; } static void taskStats(TreeSet<String> tasks, String size, LinkedList<TaskLogEntry> entries){ TreeSet<String> taskNames = new TreeSet<String>(); long totalTime; long min = 999999999; long max = 0; long avg = 0; Task minTask; Task maxTask; for (TaskLogEntry entry : entries) taskNames.add(entry.name); for (String taskName : tasks) { Task task = new Task(taskName, entries); if (task.elapsedSeconds < min) min = task.elapsedSeconds; if (task.elapsedSeconds > max) max = task.elapsedSeconds; } avg = (min + max) /2; String s = ""; s += "Minimum time on "+size+" task : " + toHoursMinutesSeconds(min) + "\n"; s += "Maximum time on "+size+" task : " + toHoursMinutesSeconds(max) + "\n"; s += "Average time on "+size+" task : " + toHoursMinutesSeconds(avg) + "\n"; s += "\n"; System.out.print(s); } private static void cmdRename(String args[]) { Scanner sc = new Scanner(System.in); String oldText = ""; if (args[0].equalsIgnoreCase("rename")) { oldText = args[1]; String newText = args[2];; rename("tm.txt", oldText, newText); System.out.println("Task " + oldText + " now appears as " + newText + " in tm.txt"); } else if (args[0].equalsIgnoreCase("delete")){ oldText = args[1]; String newText = ""; rename("tm.txt", oldText, newText); } } //code adapted from http://javaconceptoftheday.com/modify-replace-specific-string-in-text-file-in-java/ //on 2/22/18 static void rename(String filePath, String oldString, String newString) { File fileToBeModified = new File("tm.txt"); String oldContent = ""; BufferedReader reader = null; FileWriter writer = null; if (!newString.equals("")) { try { reader = new BufferedReader(new FileReader(fileToBeModified)); //Reading all the lines of input text file into oldContent String line = reader.readLine(); while (line != null){ oldContent = oldContent + line + System.lineSeparator(); line = reader.readLine(); } //Replacing oldString with newString in the oldContent String newContent = oldContent.replaceAll(oldString, newString); //Rewriting the input text file with newContent writer = new FileWriter(fileToBeModified); writer.write(newContent); } catch (IOException e) { e.printStackTrace(); } finally { try { //Closing the resources reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } else if (newString.equals("")) { try { reader = new BufferedReader(new FileReader(fileToBeModified)); //Reading all the lines of input text file into oldContent String line = reader.readLine(); while (line != null){ oldContent = oldContent + line + System.lineSeparator(); line = reader.readLine(); } //Replacing oldString with newString in the oldContent String newContent = oldContent.replaceAll(oldString, "DELETED"); //Rewriting the input text file with newContent writer = new FileWriter(fileToBeModified); writer.write(newContent); } catch (IOException e) { e.printStackTrace(); } finally { try { //Closing the resources reader.close(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("Task has been flagged as \"DELETED TASK\" in tm.txt"); } } } class TaskStats{ TaskStats(TreeSet<String> tasks, LinkedList<TaskLogEntry> entries){ TreeSet<String> taskNames = new TreeSet<String>(); long totalTime; long min = 999999999; long max = 0; long avg = 0; Task minTask; Task maxTask; for (TaskLogEntry entry : entries) taskNames.add(entry.name); for (String taskName : tasks) { Task task = new Task(taskName, entries); if (task.elapsedSeconds < min) min = task.elapsedSeconds; if (task.elapsedSeconds > max) max = task.elapsedSeconds; } avg = (min + max) /2; } } class TaskLog{ String fileName; TaskLog(String fileName){ this.fileName = fileName; } void writeLine(String line) { try { PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true)); outFile.println(line); outFile.close(); } catch(Exception e) { System.out.println("Error with tm.txt file."); } } /*void writeLine(String line, String[] description) { try { list.add(line); for (int i = 0; i < description.length; i++){ list.add(description[i]); } List<String> list = new ArrayList<>(Arrays.asList(description)); String formattedString = list.toString().replace(",", "").replace("[", "").replace("]", "").trim(); PrintWriter outFile = new PrintWriter(new FileWriter(fileName, true)); outFile.println(form.format("%s \t %s", line, formattedString)); outFile.close(); } catch(Exception e) { System.out.println("Error with tm.txt file."); } }*/ LinkedList<TaskLogEntry> read() throws IOException{ LinkedList<TaskLogEntry> entries = new LinkedList<TaskLogEntry>(); BufferedReader in = new BufferedReader(new FileReader(fileName)); String line = in.readLine(); while (line != null) { entries.add(new TaskLogEntry(line)); line = in.readLine(); } in.close(); return entries; } } class TaskLogEntry{ LocalDateTime timeStamp; String name; String command; String size; String data; TaskLogEntry(String line) { StringTokenizer stock = new StringTokenizer(line, "\t"); timeStamp = LocalDateTime.parse(stock.nextToken()); name = stock.nextToken(); command = stock.nextToken(); while (stock.hasMoreTokens()) { if (command.equals("size")) { size = stock.nextToken(); data = ""; } else if (command.equals("describe")){ data = stock.nextToken(); if (stock.hasMoreTokens()) size = stock.nextToken(); } } } } class TaskDuration{ LocalDateTime start, stop; long elapsedSeconds; TaskDuration(LocalDateTime start,LocalDateTime stop) { this.start = start; this.stop = stop; this.elapsedSeconds = elapsedSeconds(this.start, this.stop); } long elapsedSeconds(LocalDateTime start, LocalDateTime stop) { elapsedSeconds=ChronoUnit.SECONDS.between(start,stop); return elapsedSeconds; } } class Task{ String name; String description = ""; String size = ""; long elapsedSeconds; LinkedList<TaskDuration> durations; Task(String name, LinkedList<TaskLogEntry> entries) { LocalDateTime lastStart = null; this.name = name; durations = new LinkedList<TaskDuration>(); for (TaskLogEntry entry : entries) { if (entry.name.equals(this.name)) { switch (entry.command){ case "start" : lastStart = entry.timeStamp; break; case "stop" : if (lastStart != null) addDuration(lastStart, entry.timeStamp); lastStart = null; break; case "describe" : if (entry.data != null) description += entry.data + " / "; size = entry.size; break; case "size" : size = entry.size; break; } } } } void addDuration(LocalDateTime lastStart, LocalDateTime stopTime) { this.elapsedSeconds += ChronoUnit.SECONDS.between(lastStart, stopTime); durations.add(new TaskDuration (lastStart, stopTime)); } public String toString() { String s = ""; s = s + "Summary for task : " + name + "\n"; s = s + "Description : " + this.description + "\n"; s = s + "Size of task : " + size + "\n"; s = s + "Total Time on Task \t: " + TimeUtil.elapsedTime(elapsedSeconds) + "\n"; return s; } } class TimeUtil{ static long totalSeconds; TimeUtil(long totalSeconds){ this.totalSeconds = totalSeconds; } static String elapsedTime(long totalSeconds) { DateFormat df = new SimpleDateFormat("HH:mm:ss"); long hours = TimeUnit.SECONDS.toHours(totalSeconds); long minutes = TimeUnit.SECONDS.toMinutes(totalSeconds) - (TimeUnit.SECONDS.toHours(totalSeconds) * 60); long seconds = TimeUnit.SECONDS.toSeconds(totalSeconds) - (TimeUnit.SECONDS.toMinutes(totalSeconds) *60); String s = (Long.toString(hours) + ":" + Long.toString(minutes) + ":" + Long.toString(seconds)); return s; } }
package com.SearchHouse.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.SearchHouse.dao.UserInfoDao; import com.SearchHouse.pojo.User1; import com.SearchHouse.service.UserService; @Service public class UserInfoServiceImpl implements UserService { @Autowired UserInfoDao userinfodao; public UserInfoDao getUserinfodao() { return userinfodao; } public void setUserinfodao(UserInfoDao userinfodao) { this.userinfodao = userinfodao; } @Override public void addUserInfo(User1 user) { // TODO Auto-generated method stub userinfodao.addUserInfo(user); } @Override public void deleteUserInfo(String userId) { // TODO Auto-generated method stub userinfodao.deleteUserInfo(userId); } @Override public void updateUserInfo(User1 user) { // TODO Auto-generated method stub userinfodao.updateUserInfo(user); } @Override public User1 getUserById(String userId) { // TODO Auto-generated method stub return userinfodao.getUserById(userId); } @Override public List<User1> getAllUsers() { // TODO Auto-generated method stub return userinfodao.getAllUsers(); } }
import java.util.ArrayList; import java.util.HashMap; public class TrimaBinarySearchTree { /** * Given an upper and lower bound, trim the tree based on the bounds Input: * Input: 3 / \ 0 4 \ 2 / 1 L = 1 R = 3 Output: 3 / 2 / 1 */ public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public TreeNode trimBST(TreeNode root, int L, int R) { if (root == null) return null; if (root.val == L) { root.left = null; root.right = trimBST(root.right, L, R); } if (root.val == R) { root.right = null; root.left = trimBST(root.left, L, R); } if (root.val < L) { return trimBST(root.right, L, R); } if (root.val > R) { return trimBST(root.left, L, R); } if (root.val < R && root.val > L) { root.right = trimBST(root.right, L, R); root.left = trimBST(root.left, L, R); } return root; } /** * Three cases behind it, needed to be found out. * 1 Problem: Why cant set root to trimBST(root.right/left, L, R) in case that val is out of bound. */ }
package com.anton.kth_laboration_1; import android.util.Log; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.IOException; import java.io.InputStream; import java.sql.Time; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; /** * Created by Anton on 2016-11-14. */ public class CurrencyParser { private XmlPullParser parser; private ArrayList<Currency> currencies; private Calendar loadDate; public CurrencyParser() throws XmlPullParserException{ this.parser = XmlPullParserFactory.newInstance().newPullParser(); } public Calendar parse(InputStream xmlStream, ArrayList<Currency> currencies) throws Exception{ parser.setInput(xmlStream, null); this.currencies = currencies; int parseEvt = parser.getEventType(); while(parseEvt != XmlPullParser.END_DOCUMENT){ switch(parseEvt){ case XmlPullParser.END_DOCUMENT: break; case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: String tag = parser.getName(); if(tag.equalsIgnoreCase("cube")){ parseCurrency(); } break; case XmlPullParser.END_TAG: break; case XmlPullParser.TEXT: break; default: break; } parseEvt = parser.next(); } xmlStream.close(); Log.d("","Parsing complete"); return loadDate; } private void parseCurrency() throws IOException, XmlPullParserException{ try{ int parseEvent; String name; do{ parseEvent = parser.next(); name=parser.getName(); if(parseEvent == XmlPullParser.START_TAG){ if(name.equalsIgnoreCase("cube")){ if(parser.getAttributeCount() > 0){ if(parser.getAttributeName(0).equalsIgnoreCase("time")){ //This is the cube containing currency cubes. DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); try { loadDate = Calendar.getInstance(); loadDate.setTime(formatter.parse(parser.getAttributeValue(0))); Log.d("", "TIME = " + loadDate.getTime()); } catch (ParseException e) { e.printStackTrace(); } }else{ //This is a cube containing a currency double rate = 0; String currency = ""; if(parser.getAttributeName(0).equalsIgnoreCase("currency")){ currency = parser.getAttributeValue(0); } if(parser.getAttributeName(1).equalsIgnoreCase("rate")){ rate = Double.parseDouble(parser.getAttributeValue(1)); } if(rate>0 && !currency.equalsIgnoreCase("")){ currencies.add(new Currency(currency, rate)); Log.d("", "Size = " + currencies.size()); } } } } } }while(parseEvent != XmlPullParser.END_TAG || name.equalsIgnoreCase("cube")); Log.d("", "Done parsing cube"); }catch(Exception e){ e.printStackTrace(); Log.d("", e.getMessage()); } } }
package DuckHunt.Main; import DuckHunt.Other.GameGlobalVariables; import DuckHunt.Request.OpponentCameraFeed; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class HandleUDP extends Thread { private DatagramSocket listen = null; @Override public void run() { // try { // listen = new DatagramSocket(GameGlobalVariables.getInstance().getPort()+1); // } catch (SocketException e) { // e.printStackTrace(); // } while (true){ try { listen = new DatagramSocket(GameGlobalVariables.getInstance().getPort()+1); byte[] recvBuf = new byte[100000]; DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length); System.out.println("listening packet"); listen.receive(packet); System.out.println("got packet"); ByteArrayInputStream byteStream = new ByteArrayInputStream(recvBuf); ObjectInputStream is = new ObjectInputStream(byteStream); OpponentCameraFeed opponentCameraFeed = (OpponentCameraFeed) is.readObject(); GameGlobalVariables.getInstance().getGAMER().sendUDP(opponentCameraFeed.getGroup(),opponentCameraFeed.getFrom(), packet); listen.close(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); }finally { // listen.close(); } } } }
package bib.test; import bib.Lexique; import bib.iterateurs.IterateurLexique; /** * Created by Gauthier on 20/03/2017. */ public class TestLexique { public static void main(String[] args) { Lexique lex = new Lexique(5); lex.ajouter("mot"); lex.ajouter("mots"); lex.ajouter("maux"); lex.ajouter("Meaux"); System.out.println("Affichage avec itération"); for(String s:lex){ System.out.println(s); } System.out.println(lex); System.out.println("Affichage avec IterateurLexique :"); IterateurLexique itLex = lex.iterator2(); while (itLex.hasNext()){ System.out.println(itLex.next()); } } }
package com.ai.platform.agent.web.main; public class JettyConstant { public static final String JETTY_CONFIG_PROPERTY_FILE_NAME = "jetty.properties"; }
package eight.animal; public class Dog extends Animal { public Dog(String imePsa) { super(imePsa); } @Override public void playSound() { System.out.println("Waw waw.."); } }
package kr.waytech.attendancecheck_beacon.activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.ArrayList; import kr.waytech.attendancecheck_beacon.R; import kr.waytech.attendancecheck_beacon.server.ClassData; import kr.waytech.attendancecheck_beacon.server.NoticeData; import kr.waytech.attendancecheck_beacon.server.SelectNoticeDB; public class NoticeActivity extends AppCompatActivity { public static final String INTENT_CLASS = "INTENTCLASSNOTI"; private static final int GET_STRING = 1; private TextView text; private TextView tvClass; private static int num=0; private ProgressDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notice); Intent intent = getIntent(); final ClassData data = (ClassData) intent.getSerializableExtra(INTENT_CLASS); Button button = (Button) findViewById(R.id.button); text = (TextView) findViewById(R.id.text2); tvClass = (TextView) findViewById(R.id.tvClass); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in = new Intent(NoticeActivity.this, NoticeWriteActivity.class); in.putExtra(INTENT_CLASS, data); startActivityForResult(in, GET_STRING); } }); tvClass.setText("--- " + data.getClassName() + " ---"); if (!intent.getBooleanExtra(ClassListActivity.INTENT_ISEDU, false)) { button.setVisibility(View.GONE); } dialog = new ProgressDialog(this); dialog.show(); new SelectNoticeDB(mHandler).execute(data.getClassName()); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if(dialog.isShowing()) dialog.dismiss(); switch (msg.what) { case SelectNoticeDB.HANDLE_SELECT_OK: ArrayList<NoticeData> data = (ArrayList<NoticeData>) msg.obj; String str = ""; for(int i = 0; i < data.size() ; i++){ num++; str += "[" + (i+1) + "] " + data.get(i).getValue() + "\n"; } text.setText(str); break; case SelectNoticeDB.HANDLE_SELECT_FAIL: break; } } }; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == RESULT_OK) { String str = data.getStringExtra("INPUT_TEXT"); String str2 = text.getText().toString(); num++; text.setText(str2 + "[" + num + "] " + str ); } else { text.setText(""); } } } }
package com.team3.bra; import android.os.StrictMode; import java.sql.*; import java.util.Vector; public class JDBC { static String url = "jdbc:mysql://phpmyadmin.in.cs.ucy.ac.cy"; static String username = "broadway"; static String database = "`broadway`"; static String password = "929K6sb7mAbDrahH"; private static Connection conn = null; /** * Returns if the connection to the DB is active. * * @return if the connection to the DB is active. */ public static boolean isConnected() { return (conn != null); } /** * Returns a resultSet form a stored procedure and its needed arguments. * * @param procedure * the stored procedure to call. * @param arguments * the arguments needed by the stored procedure. * @return the resultSet of the stored procedure that was called. */ private static ResultSet getResultSetFromProcedure(String procedure, String[] arguments) { try { String erotimatika = ""; int totalArgs = 0; if (arguments != null) { totalArgs = arguments.length; for (int i = 0; i < totalArgs; i++) if (i == totalArgs - 1) erotimatika += "?"; else erotimatika += "?,"; } CallableStatement cstmt = conn.prepareCall("{call " + procedure + "(" + erotimatika + ")}"); int i; for (i = 1; i < totalArgs + 1; i++) cstmt.setString(i, arguments[i - 1]); ResultSet rs = cstmt.executeQuery(); SQLWarning sqlwarn = cstmt.getWarnings(); while (sqlwarn != null) { System.out.println(sqlwarn.getMessage()); sqlwarn = sqlwarn.getNextWarning(); } if (procedure.equals("userlogin")) { try { arguments[0] = cstmt.getString(1); } catch (Exception e2) { System.out.println("Access Denied."); return null; } } return rs; } catch (Exception e) { System.out.println("Get rs: " + e.getMessage()); e.printStackTrace(); return null; } } /** * Returns a two dimensional vector as translated from a DB resultSet. * * @param rs * the resultSet to translate. * @return the two dimensional vector representation of the resultSet to * translate. */ private static Vector<Vector<Object>> resultSetToVector(ResultSet rs) { try { Vector<Vector<Object>> rows = new Vector<Vector<Object>>(); if (rs == null) { return rows; } ResultSetMetaData metaData = rs.getMetaData(); int cols = metaData.getColumnCount(); Vector<String> firstRow = new Vector<String>(); for (int i = 0; i < cols; i++) firstRow.addElement(metaData.getColumnLabel(i + 1)); while (rs.next()) { Vector<Object> row = new Vector<Object>(); for (int i = 0; i < cols; i++) row.addElement(rs.getObject(i + 1)); rows.addElement(row); } return rows; } catch (Exception e) { System.out.println("RStoV: " + e.getMessage()); return null; } } /** * Returns a two dimensional vector as translated from a resultSet of a * stored procedure and its needed arguments. * * @param procedure * the stored procedure to call. * @param arguments * the arguments needed by the stored procedure. * @return the two dimensional vector representation of the stored procedure * resultSet. */ public static Vector<Vector<Object>> callProcedure(String procedure, String[] arguments) { return resultSetToVector(getResultSetFromProcedure(database + "." + procedure, arguments)); } /** * The function that establishes the connection to the Broadway Restaurant * DB. * * @return if the connection has been established correctly. */ public static boolean establishConnection() { System.out.println("Connecting database..."); try { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { System.out.println("Class forname error: " + e.getMessage()); return false; } try { conn = DriverManager.getConnection(url, username, password); System.out.println("Database connected!"); return true; } catch (SQLException e) { System.out.println(e.getMessage() + " " + e.getSQLState() + " " + e.getErrorCode()); return false; } } }
package com.example.david.foodadviser; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import static android.R.attr.id; import static android.R.attr.name; /** * Created by David on 2017. 10. 23.. */ public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME= "FoodAdviser.db"; public static final String TABLE_NAME= "Foods_table"; public static final String COL_1= "Name"; public static final String COL_2= "Recipe"; public static final String COL_3= "Ingredients"; public static final String COL_4= "Rating"; public static final String COL_5= "Favourite"; public static final String COL_6= "LastMade"; public static final String COL_7= "Picture"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table Foods_table (NAME TEXT PRIMARY KEY, RECIPE TEXT, INGREDIENTS TEXT, RATING REAL, FAVOURITE INTEGER, LASTMADE INTEGER, PICTURE BLOB)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } public boolean insertData(String name,String recipe,String ingredients) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_1,name); contentValues.put(COL_2,recipe); contentValues.put(COL_3,ingredients); long result = db.insert(TABLE_NAME,null ,contentValues); if(result == -1) return false; else return true; } public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); Cursor res = db.rawQuery("select * from "+TABLE_NAME,null); return res; } public boolean updateData(String id,String name,String recipe,String ingredients) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_1,name); contentValues.put(COL_2,recipe); contentValues.put(COL_3,ingredients); db.update(TABLE_NAME, contentValues, "NAME = ?",new String[] { name }); return true; } public Integer deleteData (String name) { SQLiteDatabase db = this.getWritableDatabase(); return db.delete(TABLE_NAME, "name = ?",new String[] {String.valueOf(name)}); } }
package com.dromedicas.jaxrs.service; import java.util.HashMap; import java.util.Map; import org.codehaus.jackson.annotate.JsonAnyGetter; import org.codehaus.jackson.annotate.JsonAnySetter; import org.codehaus.jackson.annotate.JsonIgnore; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.annotate.JsonPropertyOrder; import org.codehaus.jackson.map.annotate.JsonSerialize; @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) @JsonPropertyOrder({ "diaoperativo", "vendedor", "vtageneral", "vtaespecial", "surezinc" }) public class VentaAlInstanteDetalle { @JsonProperty("diaoperativo") private String diaoperativo; @JsonProperty("vendedor") private String vendedor; @JsonProperty("vtageneral") private String vtageneral; @JsonProperty("vtaespecial") private String vtaespecial; @JsonProperty("surezinc") private String surezinc; @JsonIgnore private Map<String, Object> additionalProperties = new HashMap<String, Object>(); @JsonProperty("diaoperativo") public String getDiaoperativo() { return diaoperativo; } @JsonProperty("diaoperativo") public void setDiaoperativo(String diaoperativo) { this.diaoperativo = diaoperativo; } @JsonProperty("vendedor") public String getVendedor() { return vendedor; } @JsonProperty("vendedor") public void setVendedor(String vendedor) { this.vendedor = vendedor; } @JsonProperty("vtageneral") public String getVtageneral() { return vtageneral; } @JsonProperty("vtageneral") public void setVtageneral(String vtageneral) { this.vtageneral = vtageneral; } @JsonProperty("vtaespecial") public String getVtaespecial() { return vtaespecial; } @JsonProperty("vtaespecial") public void setVtaespecial(String vtaespecial) { this.vtaespecial = vtaespecial; } @JsonProperty("surezinc") public String getSurezinc() { return surezinc; } @JsonProperty("surezinc") public void setSurezinc(String surezinc) { this.surezinc = surezinc; } @JsonAnyGetter public Map<String, Object> getAdditionalProperties() { return this.additionalProperties; } @JsonAnySetter public void setAdditionalProperty(String name, Object value) { this.additionalProperties.put(name, value); } }
package org.xitikit.examples.java.mysql.logwatch.data; import org.springframework.data.repository.CrudRepository; /** * Copyright ${year} * * @author J. Keith Hoopes */ public interface BlockedIpv4Repository extends CrudRepository<BlockedIpv4, Integer>{ }
package pl.rpolak.generator.name; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Rafal.Polak */ public class NameTest { public NameTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testEquals() { //given Name name1 = null; Name name2 = null; //when name1 = new Name("Adam", "Nowak"); name2 = new Name("Adam", "Nowak"); //then assertTrue(name1.equals(name2) && name2.equals(name1)); assertTrue(name1.hashCode() == name2.hashCode()); } @Test public void shouldReturnSettedNameSurname(){ //given String name = "Jan"; Name data = new Name("TEST", "TEST"); //when data.setName(name); //then assertNotNull(data); assertEquals(data.getName(), name); } @Test public void shouldReturnSettedSurname(){ //given String surname = "Kowalski"; Name data = new Name("TEST", "TEST"); //when data.setSurname(surname); //then assertNotNull(data); assertEquals(data.getSurname(), surname); } }
package dk.webbies.tscreate.evaluation; import dk.webbies.tscreate.evaluation.DeclarationEvaluator.EvaluationQueueElement; import java.util.*; /** * Created by Erik Krogh Kristensen on 16-12-2015. * * Is used to create a lot of sub-callbacks, and when all those are done, the main callback is executed. */ public class WhenAllDone { private final EvaluationQueueElement callback; private PriorityQueue<EvaluationQueueElement> queue; private int notDoneCounter = 0; boolean ran = false; public WhenAllDone(EvaluationQueueElement callback, PriorityQueue<EvaluationQueueElement> queue) { this.callback = callback; this.queue = queue; } public Runnable newSubCallback() { notDoneCounter++; return () -> { queue.add(new EvaluationQueueElement(callback.depth, () -> { if (ran) { throw new RuntimeException("Has already run"); } notDoneCounter--; if (notDoneCounter == 0) { callback.runnable.run(); ran = true; } })); }; } }
/** * <copyright> * </copyright> * * $Id$ */ package ssl; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EReference; /** * <!-- begin-user-doc --> * The <b>Package</b> for the model. * It contains accessors for the meta objects to represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @see ssl.SslFactory * @model kind="package" * @generated */ public interface SslPackage extends EPackage { /** * The package name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNAME = "ssl"; /** * The package namespace URI. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_URI = "ssl"; /** * The package namespace name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ String eNS_PREFIX = "ssl"; /** * The singleton instance of the package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ SslPackage eINSTANCE = ssl.impl.SslPackageImpl.init(); /** * The meta object id for the '{@link ssl.impl.SpecificationImpl <em>Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.SpecificationImpl * @see ssl.impl.SslPackageImpl#getSpecification() * @generated */ int SPECIFICATION = 0; /** * The feature id for the '<em><b>Testcases</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION__TESTCASES = 0; /** * The number of structural features of the '<em>Specification</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int SPECIFICATION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link ssl.impl.TestcaseImpl <em>Testcase</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.TestcaseImpl * @see ssl.impl.SslPackageImpl#getTestcase() * @generated */ int TESTCASE = 1; /** * The feature id for the '<em><b>Given</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TESTCASE__GIVEN = 0; /** * The feature id for the '<em><b>When</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TESTCASE__WHEN = 1; /** * The feature id for the '<em><b>Then</b></em>' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TESTCASE__THEN = 2; /** * The number of structural features of the '<em>Testcase</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int TESTCASE_FEATURE_COUNT = 3; /** * The meta object id for the '{@link ssl.impl.GivenImpl <em>Given</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.GivenImpl * @see ssl.impl.SslPackageImpl#getGiven() * @generated */ int GIVEN = 2; /** * The feature id for the '<em><b>Testcase</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int GIVEN__TESTCASE = 0; /** * The feature id for the '<em><b>Conditions</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int GIVEN__CONDITIONS = 1; /** * The number of structural features of the '<em>Given</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int GIVEN_FEATURE_COUNT = 2; /** * The meta object id for the '{@link ssl.impl.WhenImpl <em>When</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.WhenImpl * @see ssl.impl.SslPackageImpl#getWhen() * @generated */ int WHEN = 3; /** * The feature id for the '<em><b>Testcase</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int WHEN__TESTCASE = 0; /** * The feature id for the '<em><b>Actions</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int WHEN__ACTIONS = 1; /** * The number of structural features of the '<em>When</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int WHEN_FEATURE_COUNT = 2; /** * The meta object id for the '{@link ssl.impl.ThenImpl <em>Then</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ThenImpl * @see ssl.impl.SslPackageImpl#getThen() * @generated */ int THEN = 4; /** * The feature id for the '<em><b>Testcase</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int THEN__TESTCASE = 0; /** * The feature id for the '<em><b>Observations</b></em>' containment reference list. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int THEN__OBSERVATIONS = 1; /** * The number of structural features of the '<em>Then</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int THEN_FEATURE_COUNT = 2; /** * The meta object id for the '{@link ssl.impl.ConditionImpl <em>Condition</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ConditionImpl * @see ssl.impl.SslPackageImpl#getCondition() * @generated */ int CONDITION = 5; /** * The feature id for the '<em><b>Given</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CONDITION__GIVEN = 0; /** * The number of structural features of the '<em>Condition</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CONDITION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link ssl.impl.CheckVariableEqualsVariableImpl <em>Check Variable Equals Variable</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckVariableEqualsVariableImpl * @see ssl.impl.SslPackageImpl#getCheckVariableEqualsVariable() * @generated */ int CHECK_VARIABLE_EQUALS_VARIABLE = 6; /** * The feature id for the '<em><b>Given</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_VARIABLE__GIVEN = CONDITION__GIVEN; /** * The feature id for the '<em><b>First Variable Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_VARIABLE__FIRST_VARIABLE_NAME = CONDITION_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Second Variable Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_VARIABLE__SECOND_VARIABLE_NAME = CONDITION_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Check Variable Equals Variable</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_VARIABLE_FEATURE_COUNT = CONDITION_FEATURE_COUNT + 2; /** * The meta object id for the '{@link ssl.impl.CheckVariableEqualsTimeImpl <em>Check Variable Equals Time</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckVariableEqualsTimeImpl * @see ssl.impl.SslPackageImpl#getCheckVariableEqualsTime() * @generated */ int CHECK_VARIABLE_EQUALS_TIME = 7; /** * The feature id for the '<em><b>Given</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_TIME__GIVEN = CONDITION__GIVEN; /** * The feature id for the '<em><b>First Variable Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_TIME__FIRST_VARIABLE_NAME = CONDITION_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Time</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_TIME__TIME = CONDITION_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Check Variable Equals Time</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_VARIABLE_EQUALS_TIME_FEATURE_COUNT = CONDITION_FEATURE_COUNT + 2; /** * The meta object id for the '{@link ssl.impl.CheckModeImpl <em>Check Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckModeImpl * @see ssl.impl.SslPackageImpl#getCheckMode() * @generated */ int CHECK_MODE = 8; /** * The feature id for the '<em><b>Given</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_MODE__GIVEN = CONDITION__GIVEN; /** * The feature id for the '<em><b>Mode</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_MODE__MODE = CONDITION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Check Mode</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_MODE_FEATURE_COUNT = CONDITION_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.CheckLabelImpl <em>Check Label</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckLabelImpl * @see ssl.impl.SslPackageImpl#getCheckLabel() * @generated */ int CHECK_LABEL = 9; /** * The feature id for the '<em><b>Given</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_LABEL__GIVEN = CONDITION__GIVEN; /** * The feature id for the '<em><b>Label Type</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_LABEL__LABEL_TYPE = CONDITION_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_LABEL__VALUE = CONDITION_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Check Label</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int CHECK_LABEL_FEATURE_COUNT = CONDITION_FEATURE_COUNT + 2; /** * The meta object id for the '{@link ssl.impl.ActionImpl <em>Action</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ActionImpl * @see ssl.impl.SslPackageImpl#getAction() * @generated */ int ACTION = 10; /** * The feature id for the '<em><b>When</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int ACTION__WHEN = 0; /** * The number of structural features of the '<em>Action</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int ACTION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link ssl.impl.EntersModeImpl <em>Enters Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.EntersModeImpl * @see ssl.impl.SslPackageImpl#getEntersMode() * @generated */ int ENTERS_MODE = 11; /** * The feature id for the '<em><b>When</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int ENTERS_MODE__WHEN = ACTION__WHEN; /** * The feature id for the '<em><b>Mode</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int ENTERS_MODE__MODE = ACTION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Enters Mode</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int ENTERS_MODE_FEATURE_COUNT = ACTION_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.PressButtonImpl <em>Press Button</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.PressButtonImpl * @see ssl.impl.SslPackageImpl#getPressButton() * @generated */ int PRESS_BUTTON = 12; /** * The feature id for the '<em><b>When</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PRESS_BUTTON__WHEN = ACTION__WHEN; /** * The feature id for the '<em><b>Button</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PRESS_BUTTON__BUTTON = ACTION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Press Button</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int PRESS_BUTTON_FEATURE_COUNT = ACTION_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.ObservationImpl <em>Observation</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObservationImpl * @see ssl.impl.SslPackageImpl#getObservation() * @generated */ int OBSERVATION = 13; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVATION__THEN = 0; /** * The number of structural features of the '<em>Observation</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVATION_FEATURE_COUNT = 1; /** * The meta object id for the '{@link ssl.impl.ObserveModeImpl <em>Observe Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveModeImpl * @see ssl.impl.SslPackageImpl#getObserveMode() * @generated */ int OBSERVE_MODE = 14; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_MODE__THEN = OBSERVATION__THEN; /** * The feature id for the '<em><b>Mode</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_MODE__MODE = OBSERVATION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Observe Mode</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_MODE_FEATURE_COUNT = OBSERVATION_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.ObserveButtonImpl <em>Observe Button</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveButtonImpl * @see ssl.impl.SslPackageImpl#getObserveButton() * @generated */ int OBSERVE_BUTTON = 15; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_BUTTON__THEN = OBSERVATION__THEN; /** * The feature id for the '<em><b>Button</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_BUTTON__BUTTON = OBSERVATION_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_BUTTON__NAME = OBSERVATION_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Observe Button</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_BUTTON_FEATURE_COUNT = OBSERVATION_FEATURE_COUNT + 2; /** * The meta object id for the '{@link ssl.impl.ObserveOutputImpl <em>Observe Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveOutputImpl * @see ssl.impl.SslPackageImpl#getObserveOutput() * @generated */ int OBSERVE_OUTPUT = 16; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_OUTPUT__THEN = OBSERVATION__THEN; /** * The feature id for the '<em><b>Label Type</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_OUTPUT__LABEL_TYPE = OBSERVATION_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Observe Output</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_OUTPUT_FEATURE_COUNT = OBSERVATION_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.ObserveLabelValueImpl <em>Observe Label Value</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveLabelValueImpl * @see ssl.impl.SslPackageImpl#getObserveLabelValue() * @generated */ int OBSERVE_LABEL_VALUE = 17; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VALUE__THEN = OBSERVE_OUTPUT__THEN; /** * The feature id for the '<em><b>Label Type</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VALUE__LABEL_TYPE = OBSERVE_OUTPUT__LABEL_TYPE; /** * The feature id for the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VALUE__VALUE = OBSERVE_OUTPUT_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Observe Label Value</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VALUE_FEATURE_COUNT = OBSERVE_OUTPUT_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.ObserveLabelVariableImpl <em>Observe Label Variable</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveLabelVariableImpl * @see ssl.impl.SslPackageImpl#getObserveLabelVariable() * @generated */ int OBSERVE_LABEL_VARIABLE = 18; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VARIABLE__THEN = OBSERVE_OUTPUT__THEN; /** * The feature id for the '<em><b>Label Type</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VARIABLE__LABEL_TYPE = OBSERVE_OUTPUT__LABEL_TYPE; /** * The feature id for the '<em><b>Variable Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VARIABLE__VARIABLE_NAME = OBSERVE_OUTPUT_FEATURE_COUNT + 0; /** * The number of structural features of the '<em>Observe Label Variable</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_LABEL_VARIABLE_FEATURE_COUNT = OBSERVE_OUTPUT_FEATURE_COUNT + 1; /** * The meta object id for the '{@link ssl.impl.ObserveVariableChangeImpl <em>Observe Variable Change</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveVariableChangeImpl * @see ssl.impl.SslPackageImpl#getObserveVariableChange() * @generated */ int OBSERVE_VARIABLE_CHANGE = 19; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_VARIABLE_CHANGE__THEN = OBSERVATION__THEN; /** * The feature id for the '<em><b>Variable Name</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_VARIABLE_CHANGE__VARIABLE_NAME = OBSERVATION_FEATURE_COUNT + 0; /** * The feature id for the '<em><b>Unit</b></em>' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_VARIABLE_CHANGE__UNIT = OBSERVATION_FEATURE_COUNT + 1; /** * The number of structural features of the '<em>Observe Variable Change</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_VARIABLE_CHANGE_FEATURE_COUNT = OBSERVATION_FEATURE_COUNT + 2; /** * The meta object id for the '{@link ssl.impl.ObserveRingImpl <em>Observe Ring</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveRingImpl * @see ssl.impl.SslPackageImpl#getObserveRing() * @generated */ int OBSERVE_RING = 20; /** * The feature id for the '<em><b>Then</b></em>' container reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_RING__THEN = OBSERVATION__THEN; /** * The number of structural features of the '<em>Observe Ring</em>' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated * @ordered */ int OBSERVE_RING_FEATURE_COUNT = OBSERVATION_FEATURE_COUNT + 0; /** * The meta object id for the '{@link ssl.LabelType <em>Label Type</em>}' enum. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.LabelType * @see ssl.impl.SslPackageImpl#getLabelType() * @generated */ int LABEL_TYPE = 21; /** * The meta object id for the '{@link ssl.UnitOfTime <em>Unit Of Time</em>}' enum. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.UnitOfTime * @see ssl.impl.SslPackageImpl#getUnitOfTime() * @generated */ int UNIT_OF_TIME = 22; /** * Returns the meta object for class '{@link ssl.Specification <em>Specification</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Specification</em>'. * @see ssl.Specification * @generated */ EClass getSpecification(); /** * Returns the meta object for the containment reference list '{@link ssl.Specification#getTestcases <em>Testcases</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Testcases</em>'. * @see ssl.Specification#getTestcases() * @see #getSpecification() * @generated */ EReference getSpecification_Testcases(); /** * Returns the meta object for class '{@link ssl.Testcase <em>Testcase</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Testcase</em>'. * @see ssl.Testcase * @generated */ EClass getTestcase(); /** * Returns the meta object for the containment reference '{@link ssl.Testcase#getGiven <em>Given</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Given</em>'. * @see ssl.Testcase#getGiven() * @see #getTestcase() * @generated */ EReference getTestcase_Given(); /** * Returns the meta object for the containment reference '{@link ssl.Testcase#getWhen <em>When</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>When</em>'. * @see ssl.Testcase#getWhen() * @see #getTestcase() * @generated */ EReference getTestcase_When(); /** * Returns the meta object for the containment reference '{@link ssl.Testcase#getThen <em>Then</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference '<em>Then</em>'. * @see ssl.Testcase#getThen() * @see #getTestcase() * @generated */ EReference getTestcase_Then(); /** * Returns the meta object for class '{@link ssl.Given <em>Given</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Given</em>'. * @see ssl.Given * @generated */ EClass getGiven(); /** * Returns the meta object for the container reference '{@link ssl.Given#getTestcase <em>Testcase</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Testcase</em>'. * @see ssl.Given#getTestcase() * @see #getGiven() * @generated */ EReference getGiven_Testcase(); /** * Returns the meta object for the containment reference list '{@link ssl.Given#getConditions <em>Conditions</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Conditions</em>'. * @see ssl.Given#getConditions() * @see #getGiven() * @generated */ EReference getGiven_Conditions(); /** * Returns the meta object for class '{@link ssl.When <em>When</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>When</em>'. * @see ssl.When * @generated */ EClass getWhen(); /** * Returns the meta object for the container reference '{@link ssl.When#getTestcase <em>Testcase</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Testcase</em>'. * @see ssl.When#getTestcase() * @see #getWhen() * @generated */ EReference getWhen_Testcase(); /** * Returns the meta object for the containment reference list '{@link ssl.When#getActions <em>Actions</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Actions</em>'. * @see ssl.When#getActions() * @see #getWhen() * @generated */ EReference getWhen_Actions(); /** * Returns the meta object for class '{@link ssl.Then <em>Then</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Then</em>'. * @see ssl.Then * @generated */ EClass getThen(); /** * Returns the meta object for the container reference '{@link ssl.Then#getTestcase <em>Testcase</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Testcase</em>'. * @see ssl.Then#getTestcase() * @see #getThen() * @generated */ EReference getThen_Testcase(); /** * Returns the meta object for the containment reference list '{@link ssl.Then#getObservations <em>Observations</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Observations</em>'. * @see ssl.Then#getObservations() * @see #getThen() * @generated */ EReference getThen_Observations(); /** * Returns the meta object for class '{@link ssl.Condition <em>Condition</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Condition</em>'. * @see ssl.Condition * @generated */ EClass getCondition(); /** * Returns the meta object for the container reference '{@link ssl.Condition#getGiven <em>Given</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Given</em>'. * @see ssl.Condition#getGiven() * @see #getCondition() * @generated */ EReference getCondition_Given(); /** * Returns the meta object for class '{@link ssl.CheckVariableEqualsVariable <em>Check Variable Equals Variable</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Check Variable Equals Variable</em>'. * @see ssl.CheckVariableEqualsVariable * @generated */ EClass getCheckVariableEqualsVariable(); /** * Returns the meta object for the attribute '{@link ssl.CheckVariableEqualsVariable#getFirstVariableName <em>First Variable Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>First Variable Name</em>'. * @see ssl.CheckVariableEqualsVariable#getFirstVariableName() * @see #getCheckVariableEqualsVariable() * @generated */ EAttribute getCheckVariableEqualsVariable_FirstVariableName(); /** * Returns the meta object for the attribute '{@link ssl.CheckVariableEqualsVariable#getSecondVariableName <em>Second Variable Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Second Variable Name</em>'. * @see ssl.CheckVariableEqualsVariable#getSecondVariableName() * @see #getCheckVariableEqualsVariable() * @generated */ EAttribute getCheckVariableEqualsVariable_SecondVariableName(); /** * Returns the meta object for class '{@link ssl.CheckVariableEqualsTime <em>Check Variable Equals Time</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Check Variable Equals Time</em>'. * @see ssl.CheckVariableEqualsTime * @generated */ EClass getCheckVariableEqualsTime(); /** * Returns the meta object for the attribute '{@link ssl.CheckVariableEqualsTime#getFirstVariableName <em>First Variable Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>First Variable Name</em>'. * @see ssl.CheckVariableEqualsTime#getFirstVariableName() * @see #getCheckVariableEqualsTime() * @generated */ EAttribute getCheckVariableEqualsTime_FirstVariableName(); /** * Returns the meta object for the attribute '{@link ssl.CheckVariableEqualsTime#getTime <em>Time</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Time</em>'. * @see ssl.CheckVariableEqualsTime#getTime() * @see #getCheckVariableEqualsTime() * @generated */ EAttribute getCheckVariableEqualsTime_Time(); /** * Returns the meta object for class '{@link ssl.CheckMode <em>Check Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Check Mode</em>'. * @see ssl.CheckMode * @generated */ EClass getCheckMode(); /** * Returns the meta object for the attribute '{@link ssl.CheckMode#getMode <em>Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Mode</em>'. * @see ssl.CheckMode#getMode() * @see #getCheckMode() * @generated */ EAttribute getCheckMode_Mode(); /** * Returns the meta object for class '{@link ssl.CheckLabel <em>Check Label</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Check Label</em>'. * @see ssl.CheckLabel * @generated */ EClass getCheckLabel(); /** * Returns the meta object for the attribute '{@link ssl.CheckLabel#getLabelType <em>Label Type</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Label Type</em>'. * @see ssl.CheckLabel#getLabelType() * @see #getCheckLabel() * @generated */ EAttribute getCheckLabel_LabelType(); /** * Returns the meta object for the attribute '{@link ssl.CheckLabel#getValue <em>Value</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Value</em>'. * @see ssl.CheckLabel#getValue() * @see #getCheckLabel() * @generated */ EAttribute getCheckLabel_Value(); /** * Returns the meta object for class '{@link ssl.Action <em>Action</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Action</em>'. * @see ssl.Action * @generated */ EClass getAction(); /** * Returns the meta object for the container reference '{@link ssl.Action#getWhen <em>When</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>When</em>'. * @see ssl.Action#getWhen() * @see #getAction() * @generated */ EReference getAction_When(); /** * Returns the meta object for class '{@link ssl.EntersMode <em>Enters Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Enters Mode</em>'. * @see ssl.EntersMode * @generated */ EClass getEntersMode(); /** * Returns the meta object for the attribute '{@link ssl.EntersMode#getMode <em>Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Mode</em>'. * @see ssl.EntersMode#getMode() * @see #getEntersMode() * @generated */ EAttribute getEntersMode_Mode(); /** * Returns the meta object for class '{@link ssl.PressButton <em>Press Button</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Press Button</em>'. * @see ssl.PressButton * @generated */ EClass getPressButton(); /** * Returns the meta object for the attribute '{@link ssl.PressButton#getButton <em>Button</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Button</em>'. * @see ssl.PressButton#getButton() * @see #getPressButton() * @generated */ EAttribute getPressButton_Button(); /** * Returns the meta object for class '{@link ssl.Observation <em>Observation</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observation</em>'. * @see ssl.Observation * @generated */ EClass getObservation(); /** * Returns the meta object for the container reference '{@link ssl.Observation#getThen <em>Then</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Then</em>'. * @see ssl.Observation#getThen() * @see #getObservation() * @generated */ EReference getObservation_Then(); /** * Returns the meta object for class '{@link ssl.ObserveMode <em>Observe Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Mode</em>'. * @see ssl.ObserveMode * @generated */ EClass getObserveMode(); /** * Returns the meta object for the attribute '{@link ssl.ObserveMode#getMode <em>Mode</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Mode</em>'. * @see ssl.ObserveMode#getMode() * @see #getObserveMode() * @generated */ EAttribute getObserveMode_Mode(); /** * Returns the meta object for class '{@link ssl.ObserveButton <em>Observe Button</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Button</em>'. * @see ssl.ObserveButton * @generated */ EClass getObserveButton(); /** * Returns the meta object for the attribute '{@link ssl.ObserveButton#getButton <em>Button</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Button</em>'. * @see ssl.ObserveButton#getButton() * @see #getObserveButton() * @generated */ EAttribute getObserveButton_Button(); /** * Returns the meta object for the attribute '{@link ssl.ObserveButton#getName <em>Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Name</em>'. * @see ssl.ObserveButton#getName() * @see #getObserveButton() * @generated */ EAttribute getObserveButton_Name(); /** * Returns the meta object for class '{@link ssl.ObserveOutput <em>Observe Output</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Output</em>'. * @see ssl.ObserveOutput * @generated */ EClass getObserveOutput(); /** * Returns the meta object for the attribute '{@link ssl.ObserveOutput#getLabelType <em>Label Type</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Label Type</em>'. * @see ssl.ObserveOutput#getLabelType() * @see #getObserveOutput() * @generated */ EAttribute getObserveOutput_LabelType(); /** * Returns the meta object for class '{@link ssl.ObserveLabelValue <em>Observe Label Value</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Label Value</em>'. * @see ssl.ObserveLabelValue * @generated */ EClass getObserveLabelValue(); /** * Returns the meta object for the attribute '{@link ssl.ObserveLabelValue#getValue <em>Value</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Value</em>'. * @see ssl.ObserveLabelValue#getValue() * @see #getObserveLabelValue() * @generated */ EAttribute getObserveLabelValue_Value(); /** * Returns the meta object for class '{@link ssl.ObserveLabelVariable <em>Observe Label Variable</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Label Variable</em>'. * @see ssl.ObserveLabelVariable * @generated */ EClass getObserveLabelVariable(); /** * Returns the meta object for the attribute '{@link ssl.ObserveLabelVariable#getVariableName <em>Variable Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Variable Name</em>'. * @see ssl.ObserveLabelVariable#getVariableName() * @see #getObserveLabelVariable() * @generated */ EAttribute getObserveLabelVariable_VariableName(); /** * Returns the meta object for class '{@link ssl.ObserveVariableChange <em>Observe Variable Change</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Variable Change</em>'. * @see ssl.ObserveVariableChange * @generated */ EClass getObserveVariableChange(); /** * Returns the meta object for the attribute '{@link ssl.ObserveVariableChange#getVariableName <em>Variable Name</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Variable Name</em>'. * @see ssl.ObserveVariableChange#getVariableName() * @see #getObserveVariableChange() * @generated */ EAttribute getObserveVariableChange_VariableName(); /** * Returns the meta object for the attribute '{@link ssl.ObserveVariableChange#getUnit <em>Unit</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Unit</em>'. * @see ssl.ObserveVariableChange#getUnit() * @see #getObserveVariableChange() * @generated */ EAttribute getObserveVariableChange_Unit(); /** * Returns the meta object for class '{@link ssl.ObserveRing <em>Observe Ring</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Observe Ring</em>'. * @see ssl.ObserveRing * @generated */ EClass getObserveRing(); /** * Returns the meta object for enum '{@link ssl.LabelType <em>Label Type</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for enum '<em>Label Type</em>'. * @see ssl.LabelType * @generated */ EEnum getLabelType(); /** * Returns the meta object for enum '{@link ssl.UnitOfTime <em>Unit Of Time</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for enum '<em>Unit Of Time</em>'. * @see ssl.UnitOfTime * @generated */ EEnum getUnitOfTime(); /** * Returns the factory that creates the instances of the model. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the factory that creates the instances of the model. * @generated */ SslFactory getSslFactory(); /** * <!-- begin-user-doc --> * Defines literals for the meta objects that represent * <ul> * <li>each class,</li> * <li>each feature of each class,</li> * <li>each enum,</li> * <li>and each data type</li> * </ul> * <!-- end-user-doc --> * @generated */ interface Literals { /** * The meta object literal for the '{@link ssl.impl.SpecificationImpl <em>Specification</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.SpecificationImpl * @see ssl.impl.SslPackageImpl#getSpecification() * @generated */ EClass SPECIFICATION = eINSTANCE.getSpecification(); /** * The meta object literal for the '<em><b>Testcases</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference SPECIFICATION__TESTCASES = eINSTANCE.getSpecification_Testcases(); /** * The meta object literal for the '{@link ssl.impl.TestcaseImpl <em>Testcase</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.TestcaseImpl * @see ssl.impl.SslPackageImpl#getTestcase() * @generated */ EClass TESTCASE = eINSTANCE.getTestcase(); /** * The meta object literal for the '<em><b>Given</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference TESTCASE__GIVEN = eINSTANCE.getTestcase_Given(); /** * The meta object literal for the '<em><b>When</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference TESTCASE__WHEN = eINSTANCE.getTestcase_When(); /** * The meta object literal for the '<em><b>Then</b></em>' containment reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference TESTCASE__THEN = eINSTANCE.getTestcase_Then(); /** * The meta object literal for the '{@link ssl.impl.GivenImpl <em>Given</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.GivenImpl * @see ssl.impl.SslPackageImpl#getGiven() * @generated */ EClass GIVEN = eINSTANCE.getGiven(); /** * The meta object literal for the '<em><b>Testcase</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference GIVEN__TESTCASE = eINSTANCE.getGiven_Testcase(); /** * The meta object literal for the '<em><b>Conditions</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference GIVEN__CONDITIONS = eINSTANCE.getGiven_Conditions(); /** * The meta object literal for the '{@link ssl.impl.WhenImpl <em>When</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.WhenImpl * @see ssl.impl.SslPackageImpl#getWhen() * @generated */ EClass WHEN = eINSTANCE.getWhen(); /** * The meta object literal for the '<em><b>Testcase</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference WHEN__TESTCASE = eINSTANCE.getWhen_Testcase(); /** * The meta object literal for the '<em><b>Actions</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference WHEN__ACTIONS = eINSTANCE.getWhen_Actions(); /** * The meta object literal for the '{@link ssl.impl.ThenImpl <em>Then</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ThenImpl * @see ssl.impl.SslPackageImpl#getThen() * @generated */ EClass THEN = eINSTANCE.getThen(); /** * The meta object literal for the '<em><b>Testcase</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference THEN__TESTCASE = eINSTANCE.getThen_Testcase(); /** * The meta object literal for the '<em><b>Observations</b></em>' containment reference list feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference THEN__OBSERVATIONS = eINSTANCE.getThen_Observations(); /** * The meta object literal for the '{@link ssl.impl.ConditionImpl <em>Condition</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ConditionImpl * @see ssl.impl.SslPackageImpl#getCondition() * @generated */ EClass CONDITION = eINSTANCE.getCondition(); /** * The meta object literal for the '<em><b>Given</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference CONDITION__GIVEN = eINSTANCE.getCondition_Given(); /** * The meta object literal for the '{@link ssl.impl.CheckVariableEqualsVariableImpl <em>Check Variable Equals Variable</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckVariableEqualsVariableImpl * @see ssl.impl.SslPackageImpl#getCheckVariableEqualsVariable() * @generated */ EClass CHECK_VARIABLE_EQUALS_VARIABLE = eINSTANCE.getCheckVariableEqualsVariable(); /** * The meta object literal for the '<em><b>First Variable Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_VARIABLE_EQUALS_VARIABLE__FIRST_VARIABLE_NAME = eINSTANCE.getCheckVariableEqualsVariable_FirstVariableName(); /** * The meta object literal for the '<em><b>Second Variable Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_VARIABLE_EQUALS_VARIABLE__SECOND_VARIABLE_NAME = eINSTANCE.getCheckVariableEqualsVariable_SecondVariableName(); /** * The meta object literal for the '{@link ssl.impl.CheckVariableEqualsTimeImpl <em>Check Variable Equals Time</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckVariableEqualsTimeImpl * @see ssl.impl.SslPackageImpl#getCheckVariableEqualsTime() * @generated */ EClass CHECK_VARIABLE_EQUALS_TIME = eINSTANCE.getCheckVariableEqualsTime(); /** * The meta object literal for the '<em><b>First Variable Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_VARIABLE_EQUALS_TIME__FIRST_VARIABLE_NAME = eINSTANCE.getCheckVariableEqualsTime_FirstVariableName(); /** * The meta object literal for the '<em><b>Time</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_VARIABLE_EQUALS_TIME__TIME = eINSTANCE.getCheckVariableEqualsTime_Time(); /** * The meta object literal for the '{@link ssl.impl.CheckModeImpl <em>Check Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckModeImpl * @see ssl.impl.SslPackageImpl#getCheckMode() * @generated */ EClass CHECK_MODE = eINSTANCE.getCheckMode(); /** * The meta object literal for the '<em><b>Mode</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_MODE__MODE = eINSTANCE.getCheckMode_Mode(); /** * The meta object literal for the '{@link ssl.impl.CheckLabelImpl <em>Check Label</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.CheckLabelImpl * @see ssl.impl.SslPackageImpl#getCheckLabel() * @generated */ EClass CHECK_LABEL = eINSTANCE.getCheckLabel(); /** * The meta object literal for the '<em><b>Label Type</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_LABEL__LABEL_TYPE = eINSTANCE.getCheckLabel_LabelType(); /** * The meta object literal for the '<em><b>Value</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute CHECK_LABEL__VALUE = eINSTANCE.getCheckLabel_Value(); /** * The meta object literal for the '{@link ssl.impl.ActionImpl <em>Action</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ActionImpl * @see ssl.impl.SslPackageImpl#getAction() * @generated */ EClass ACTION = eINSTANCE.getAction(); /** * The meta object literal for the '<em><b>When</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference ACTION__WHEN = eINSTANCE.getAction_When(); /** * The meta object literal for the '{@link ssl.impl.EntersModeImpl <em>Enters Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.EntersModeImpl * @see ssl.impl.SslPackageImpl#getEntersMode() * @generated */ EClass ENTERS_MODE = eINSTANCE.getEntersMode(); /** * The meta object literal for the '<em><b>Mode</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute ENTERS_MODE__MODE = eINSTANCE.getEntersMode_Mode(); /** * The meta object literal for the '{@link ssl.impl.PressButtonImpl <em>Press Button</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.PressButtonImpl * @see ssl.impl.SslPackageImpl#getPressButton() * @generated */ EClass PRESS_BUTTON = eINSTANCE.getPressButton(); /** * The meta object literal for the '<em><b>Button</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute PRESS_BUTTON__BUTTON = eINSTANCE.getPressButton_Button(); /** * The meta object literal for the '{@link ssl.impl.ObservationImpl <em>Observation</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObservationImpl * @see ssl.impl.SslPackageImpl#getObservation() * @generated */ EClass OBSERVATION = eINSTANCE.getObservation(); /** * The meta object literal for the '<em><b>Then</b></em>' container reference feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EReference OBSERVATION__THEN = eINSTANCE.getObservation_Then(); /** * The meta object literal for the '{@link ssl.impl.ObserveModeImpl <em>Observe Mode</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveModeImpl * @see ssl.impl.SslPackageImpl#getObserveMode() * @generated */ EClass OBSERVE_MODE = eINSTANCE.getObserveMode(); /** * The meta object literal for the '<em><b>Mode</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_MODE__MODE = eINSTANCE.getObserveMode_Mode(); /** * The meta object literal for the '{@link ssl.impl.ObserveButtonImpl <em>Observe Button</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveButtonImpl * @see ssl.impl.SslPackageImpl#getObserveButton() * @generated */ EClass OBSERVE_BUTTON = eINSTANCE.getObserveButton(); /** * The meta object literal for the '<em><b>Button</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_BUTTON__BUTTON = eINSTANCE.getObserveButton_Button(); /** * The meta object literal for the '<em><b>Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_BUTTON__NAME = eINSTANCE.getObserveButton_Name(); /** * The meta object literal for the '{@link ssl.impl.ObserveOutputImpl <em>Observe Output</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveOutputImpl * @see ssl.impl.SslPackageImpl#getObserveOutput() * @generated */ EClass OBSERVE_OUTPUT = eINSTANCE.getObserveOutput(); /** * The meta object literal for the '<em><b>Label Type</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_OUTPUT__LABEL_TYPE = eINSTANCE.getObserveOutput_LabelType(); /** * The meta object literal for the '{@link ssl.impl.ObserveLabelValueImpl <em>Observe Label Value</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveLabelValueImpl * @see ssl.impl.SslPackageImpl#getObserveLabelValue() * @generated */ EClass OBSERVE_LABEL_VALUE = eINSTANCE.getObserveLabelValue(); /** * The meta object literal for the '<em><b>Value</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_LABEL_VALUE__VALUE = eINSTANCE.getObserveLabelValue_Value(); /** * The meta object literal for the '{@link ssl.impl.ObserveLabelVariableImpl <em>Observe Label Variable</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveLabelVariableImpl * @see ssl.impl.SslPackageImpl#getObserveLabelVariable() * @generated */ EClass OBSERVE_LABEL_VARIABLE = eINSTANCE.getObserveLabelVariable(); /** * The meta object literal for the '<em><b>Variable Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_LABEL_VARIABLE__VARIABLE_NAME = eINSTANCE.getObserveLabelVariable_VariableName(); /** * The meta object literal for the '{@link ssl.impl.ObserveVariableChangeImpl <em>Observe Variable Change</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveVariableChangeImpl * @see ssl.impl.SslPackageImpl#getObserveVariableChange() * @generated */ EClass OBSERVE_VARIABLE_CHANGE = eINSTANCE.getObserveVariableChange(); /** * The meta object literal for the '<em><b>Variable Name</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_VARIABLE_CHANGE__VARIABLE_NAME = eINSTANCE.getObserveVariableChange_VariableName(); /** * The meta object literal for the '<em><b>Unit</b></em>' attribute feature. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ EAttribute OBSERVE_VARIABLE_CHANGE__UNIT = eINSTANCE.getObserveVariableChange_Unit(); /** * The meta object literal for the '{@link ssl.impl.ObserveRingImpl <em>Observe Ring</em>}' class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.impl.ObserveRingImpl * @see ssl.impl.SslPackageImpl#getObserveRing() * @generated */ EClass OBSERVE_RING = eINSTANCE.getObserveRing(); /** * The meta object literal for the '{@link ssl.LabelType <em>Label Type</em>}' enum. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.LabelType * @see ssl.impl.SslPackageImpl#getLabelType() * @generated */ EEnum LABEL_TYPE = eINSTANCE.getLabelType(); /** * The meta object literal for the '{@link ssl.UnitOfTime <em>Unit Of Time</em>}' enum. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see ssl.UnitOfTime * @see ssl.impl.SslPackageImpl#getUnitOfTime() * @generated */ EEnum UNIT_OF_TIME = eINSTANCE.getUnitOfTime(); } } //SslPackage
package com.example.jiyushi1.dis.activity.seller; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.jiyushi1.dis.R; import com.example.jiyushi1.dis.ws.local.HttpDBServer; import java.util.HashMap; import java.util.Map; public class SellerPassword extends Activity { private TextView warnning; private EditText oldPassword; private EditText newPassword; private EditText retype; private Bundle bd; private Handler handler; private ProgressDialog progressDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_seller_password); oldPassword = (EditText) findViewById(R.id.etOldPassword); newPassword = (EditText) findViewById(R.id.etNewPassword); retype = (EditText) findViewById(R.id.etRetype); warnning =(TextView) findViewById(R.id.tvWarn); handler = new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what == 2){ String result = (String)msg.obj; Toast.makeText(SellerPassword.this,result, Toast.LENGTH_LONG).show(); if (result.compareTo("Change Password Successful") == 0) { finish(); } progressDialog.dismiss(); } } }; retype.addTextChangedListener(retypeWatcher); Button submit = (Button) findViewById(R.id.btSellerPasswordSubmit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String oldP = oldPassword.getText().toString(); String newP = newPassword.getText().toString(); bd = getIntent().getExtras(); String username = bd.getString("username"); Map<String, String> params = new HashMap<String, String>(); params.put("oldpassword", oldP); params.put("newpassword", newP); params.put("username", username); params.put("usertype", "Seller"); progressDialog = ProgressDialog.show(SellerPassword.this, "Connecting", "Connecting to Server"); HttpConnectDB util = new HttpConnectDB(params, "utf-8", 8); util.start(); } }); Button cancel = (Button) findViewById(R.id.btSellerPasswordCancel); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } TextWatcher retypeWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (newPassword.getText().toString().compareTo(retype.getText().toString()) != 0){ warnning.setText("Not Same!"); } else{ warnning.setText("Good job!"); } } @Override public void afterTextChanged(Editable s) { } }; private class HttpConnectDB extends HttpDBServer { HttpConnectDB(Map<String, String> params, String encode,int requestType){ super(params,encode,requestType); } @Override public void run() { super.run(); Message message = Message.obtain(); message.what = 2; message.obj = super.getResult(); handler.sendMessage(message); } } }
package example.lgcode.launchstatus.models; import com.squareup.otto.Bus; import example.lgcode.launchstatus.dtos.LaunchDTO; /** * Created by leojg on 3/3/17. */ public class LaunchDetailModel { private LaunchDTO launch; private Bus bus; public LaunchDetailModel(LaunchDTO launch, Bus bus) { this.launch = launch; this.bus = bus; } public LaunchDTO getLaunch() { return launch; } }
package com.trump.auction.back.util.sys; import java.util.Map; import java.util.Properties; import org.apache.xmlbeans.impl.common.ConcurrentReaderHashMap; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; /** * <p> * 扩展spring property placeholder,获取props配置 * </p> * @author Owen.Yuan 2017/7/24. */ public class AppPropertyConfigurer extends PropertyPlaceholderConfigurer { private static Map<String, Object> PROPS = new ConcurrentReaderHashMap(); @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); for ( Object keyItem : props.keySet() ) { String key = keyItem.toString().trim(); String value = props.getProperty( key ); AppPropertyConfigurer.PROPS.put( key, value ); } } public static Object getProperty(String name) { return AppPropertyConfigurer.PROPS.get( name ); } public static String getPropertyAsString(String name) { Object property = getProperty( name ); return property == null ? null : property.toString().trim(); } }
/* * Copyright 2002-2019 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.web.servlet.view.feed; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.rometools.rome.feed.rss.Channel; import com.rometools.rome.feed.rss.Description; import com.rometools.rome.feed.rss.Item; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.junit.jupiter.api.Test; import org.springframework.core.testfixture.xml.XmlContent; import org.springframework.web.testfixture.servlet.MockHttpServletRequest; import org.springframework.web.testfixture.servlet.MockHttpServletResponse; import static org.assertj.core.api.Assertions.assertThat; /** * @author Arjen Poutsma */ public class RssFeedViewTests { private final AbstractRssFeedView view = new MyRssFeedView(); @Test public void render() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); Map<String, String> model = new LinkedHashMap<>(); model.put("2", "This is entry 2"); model.put("1", "This is entry 1"); view.render(model, request, response); assertThat(response.getContentType()).as("Invalid content-type").isEqualTo("application/rss+xml"); String expected = "<rss version=\"2.0\">" + "<channel><title>Test Feed</title>" + "<link>https://example.com</link>" + "<description>Test feed description</description>" + "<item><title>2</title><description>This is entry 2</description></item>" + "<item><title>1</title><description>This is entry 1</description></item>" + "</channel></rss>"; assertThat(XmlContent.of(response.getContentAsString())).isSimilarToIgnoringWhitespace(expected); } private static class MyRssFeedView extends AbstractRssFeedView { @Override protected void buildFeedMetadata(Map<String, Object> model, Channel channel, HttpServletRequest request) { channel.setTitle("Test Feed"); channel.setDescription("Test feed description"); channel.setLink("https://example.com"); } @Override protected List<Item> buildFeedItems(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { List<Item> items = new ArrayList<>(); for (String name : model.keySet()) { Item item = new Item(); item.setTitle(name); Description description = new Description(); description.setValue((String) model.get(name)); item.setDescription(description); items.add(item); } return items; } } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.common.util; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.ow2.proactive.scheduler.common.util.SchedulerLoggers; public class LinuxShellExecuter { static Logger logger = ProActiveLogger.getLogger(SchedulerLoggers.UTIL); static public Process executeShellScript(File file, Shell shell) throws IOException { if (!file.exists() || !file.canRead()) { throw new IOException("Read error on : " + file); } return executeShellScript(new FileInputStream(file), shell); } static public Process executeShellScript(InputStream input, Shell shell) throws IOException { InputStreamReader isr = new InputStreamReader(input); BufferedReader in = new BufferedReader(isr); Process pshell = Runtime.getRuntime().exec(shell.command()); PrintWriter out = new PrintWriter(new OutputStreamWriter(pshell.getOutputStream())); try { String line; while ((line = in.readLine()) != null) { if (logger.isDebugEnabled()) { logger.debug("[SHELL SCRIPT] " + line); } out.println(line); } in.close(); } catch (IOException ex) { } if (logger.isDebugEnabled()) { logger.debug("[SHELL SCRIPT] exit"); } out.println("exit"); out.flush(); out.close(); return pshell; } }
import becker.robots.City; import becker.robots.Direction; import becker.robots.Robot; import becker.robots.Thing; import becker.robots.Wall; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author katop7929 */ public class Quiz1 { /** * @param args the command line arguments */ public static void main(String[] args) { //create a city City kpl = new City(); //create a robot Robot obama = new Robot(kpl,4,0,Direction.EAST); //create walls new Wall(kpl,4,2,Direction.WEST); new Wall(kpl,4,2,Direction.NORTH); new Wall(kpl,3,3,Direction.WEST); new Wall(kpl,2,4,Direction.WEST); new Wall(kpl,2,4,Direction.NORTH); new Wall(kpl,2,5,Direction.NORTH); new Wall(kpl,3,3,Direction.NORTH); new Wall(kpl,2,5,Direction.EAST); new Wall(kpl,3,6,Direction.EAST); new Wall(kpl,4,7,Direction.EAST); new Wall(kpl,3,6,Direction.NORTH); new Wall(kpl,4,7,Direction.NORTH); //make things new Thing(kpl,4,1); new Thing(kpl,3,2); new Thing(kpl,2,3); new Thing(kpl,1,4); //get robot to move obama.move(); obama.pickThing(); obama.turnLeft(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.pickThing(); obama.turnLeft(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.pickThing(); obama.turnLeft(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.pickThing(); obama.move(); obama.putThing(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.putThing(); obama.turnLeft(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.putThing(); obama.turnLeft(); obama.move(); obama.turnLeft(); obama.turnLeft(); obama.turnLeft(); obama.move(); obama.putThing(); obama.turnLeft(); obama.move(); } }
package L5_ExerciciosFuncoes.L5_Player; import L5_ExerciciosFuncoes.Ex01_L5; import java.util.Scanner; public class Ex01_L5_Player { public static void main(String[] args) { Scanner myScr = new Scanner(System.in); int numeroDeRepeticoes = myScr.nextInt(); Ex01_L5 ex01_L5 = new Ex01_L5(); String estruturaS = ex01_L5.montarEstrutura(numeroDeRepeticoes); System.out.print(estruturaS); } }
package com.bnrc.ui.refresh; import android.content.Context; import android.graphics.Color; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; public abstract class OverScrollHeaderLayout extends FrameLayout implements IPullRefreshLayout { protected Context mContext; protected View mContentView; protected int mViewHeight; public OverScrollHeaderLayout(Context context) { super(context); initView(context); } public OverScrollHeaderLayout(Context context, AttributeSet attrs) { super(context, attrs); initView(context); } protected final void initView(Context context) { mContext = context; mContentView = getContentView(context); addView(mContentView); mContentView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); mViewHeight = mContentView.getMeasuredHeight(); hide(); } protected View getContentView(Context context) { LinearLayout content = new LinearLayout(context); content.setOrientation(LinearLayout.VERTICAL); content.setBackgroundColor(Color.TRANSPARENT); return content; } public int getViewHeight() { Log.d("", "RJZ header getviewheight " + mViewHeight); return mViewHeight; } public void hide() { setVisibility(View.INVISIBLE); } public void show() { setVisibility(View.VISIBLE); } }
public class Lol { public String $a_clumsy__String; public void someMethod() { if("1" == "1") { } } }
package Helpers; import java.sql.*; /** * La classe DbTable estente ogni file del package Dbtable e contiene tutte le funzioni principali che permettono di interagire con il DBMS */ public class DbTable { protected String name; protected String sql; /** Metodi DML (insert, update , delete) */ public void insert(String campi){ sql="insert into " + name + " values("+ campi +")"; } public void update(String info){ sql="update "+ name + " set " + info; } public void delete(){ sql="delete from "+name; } /**Metodi select*/ /** Seleziono tutte le tuple della tabella */ public void select(){ sql="SELECT * FROM " + name; } /** Seleziono solo alcuni campi della tabella */ public void select(String campo) { sql="SELECT " +campo+ " FROM " + name;} /**Metodi per il completamento della query*/ /** Aggiungo alla query la clausola where */ public void where(String clausola){ sql=sql + " WHERE " + clausola; } /** Aggiungo alla query la clausola order by */ public void order(String clausola){ sql = sql + "ORDER BY " + clausola; } /** Metodi di esecuzione della query */ public int count(ResultSet risultato){ int i=0; try { while (risultato.next()) { i++; } } catch(Exception e){ System.out.println(e); } return i; } /** Utilizzata per l'esecuzione di una query di tipo insert che non contiene un attributo di tipo AUTO_INCREMENT nel database */ public boolean execute(){ Connector connector= new Connector(); Connection db = connector.connect(); boolean check = false; sql = sql + ";"; try { PreparedStatement query = db.prepareStatement(sql); query.executeUpdate(); check=true; } catch (Exception e) { System.out.println(e); check=false; } connector.disconnect(); return check; } /** Utilizzata per l'esecuzione di una query di tipo insert che contiene un attributo di tipo AUTO_INCREMENT nel database */ public int executeForKey(){ Connector connector= new Connector(); Connection db = connector.connect(); sql = sql + ";"; int generated_key = 0; try { Statement query = db.createStatement(); query.executeUpdate(sql,Statement.RETURN_GENERATED_KEYS); ResultSet rs = query.getGeneratedKeys(); try { rs.next(); generated_key = rs.getInt("GENERATED_KEY"); } catch (Exception e) { System.out.println("C'è un errore:" + e); } } catch (Exception e) { System.out.println(e); } connector.disconnect(); return generated_key; } /**Utilizzata per l'esecuzione di query da cui si deve estrapolare dati dal database */ public ResultSet fetch(){ ResultSet risultato=null; Connector connector= new Connector(); Connection db = connector.connect(); sql = sql + ";"; try { Statement query = db.createStatement(); risultato=query.executeQuery(sql); } catch (Exception e) { System.out.println(e); } return risultato; } }
package userServlet; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.beanutils.BeanUtils; import domain.Order; import domain.OrderItem; import domain.Product; import domain.User; import service.OrderService; import utils.IdUtils; public class CreatOrderServlet extends HttpServlet { private static final long serialVersionUID = 1L; public CreatOrderServlet() { super(); } @SuppressWarnings("unchecked") protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); HttpSession session = request.getSession(); User user = (User) session.getAttribute("sUser"); System.out.println("CreatOrderServlet"+user); // 2.从购物车中获取商品信息 Map<Product, Integer> cart = (Map<Product, Integer>)session.getAttribute("cart"); // 3.将数据封装到订单对象中 Order order = new Order(); Map<String , String[]> map = request.getParameterMap(); try { BeanUtils.populate(order,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } order.setId(IdUtils.creatId());// 封装订单id order.setUser(user);// 封装用户信息到订单. System.out.println("CreatOrderServlet"+order); for (Product p : cart.keySet()) { OrderItem item = new OrderItem(); item.setOrderid(order); item.setBuynum(cart.get(p)); item.setP(p); order.getOrderItems().add(item); } // 4.调用service中添加订单操作. OrderService service = new OrderService(); service.addOrder(order); System.out.println("service.addOrders数据库成功"); // request.getRequestDispatcher("/client/orderlist.jsp").forward(request, response); response.sendRedirect(request.getContextPath() + "/admin/js/createOrderSuccess.jsp"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
package com.pelephone_mobile.mypelephone.ui.activities; /** * Created by Gali.Issachar on 20/10/13. */ /** * */ import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Point; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.provider.BaseColumns; import android.provider.ContactsContract; import android.util.Log; import android.view.Display; import android.view.WindowManager; import android.widget.Toast; //import com.google.analytics.tracking.android.Tracker; import com.pelephone_mobile.mypelephone.network.interfaces.IMPRestGetResponseListener; import com.pelephone_mobile.mypelephone.network.rest.MPRequestUrlBuilder; import com.pelephone_mobile.mypelephone.network.rest.RestRequests; import com.pelephone_mobile.mypelephone.network.rest.pojos.BannersList; import com.pelephone_mobile.mypelephone.network.rest.pojos.BannersListPersonal; import com.pelephone_mobile.mypelephone.network.rest.pojos.LongTokenItem; import com.pelephone_mobile.mypelephone.network.rest.pojos.MainMenuItem; import com.pelephone_mobile.mypelephone.network.rest.pojos.MainScreenDataItem; import com.pelephone_mobile.mypelephone.network.rest.pojos.NormalLoginItem; import com.pelephone_mobile.mypelephone.network.rest.pojos.RegisteredServicesItem; import com.pelephone_mobile.mypelephone.services.MPService; import com.pelephone_mobile.mypelephone.ui.activities.dialogs.DialogSessionEndedActivity; import com.pelephone_mobile.mypelephone.ui.interfaces.IMPOnServiceConnectedListener; import com.pelephone_mobile.mypelephone.utils.AppUtils; import com.pelephone_mobile.songwaiting.global.SWGlobal; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Base Activity, that extends SherlockFragmentActivity and provides connection * to SWService. * * @author Galit.Feller */ public abstract class MPBaseActivity extends AnalyticsBaseActivity { /* protected final String LOAD_MAIN_URL = "http://10.174.10.35/PonlineService/PeleponeOnlineAppServices.svc/Menu?userType=1"; */ protected final int NAVIGATE_TO_GOOGLE_PLAY_REQUEST = 2; private final int CONNECTION_PROBLEM_REQUEST = 5; protected MPService mMPService = null; protected ServiceConnection mServiceConnection = null; protected boolean mServiceConnected = false; protected IMPOnServiceConnectedListener mIMPOnServiceConnectedListener = null; protected static final String tag = "MainActivity"; public RestRequests mRestRequests = null; protected boolean is3g = false; protected boolean isWifi = false; public static List<MainMenuItem> listDataHeader; public static HashMap<String, List<MainMenuItem>> listDataChild; //public static boolean isAlive = false; /* public boolean isBannerLoaded = false; public boolean isRegisteredServicesLoaded = false;*/ public static final int CONNECTION_CONNECT_TIMEOUT = 10 * 1000; private static final String TAG = "MPBaseActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(this.mConnReceiver, new IntentFilter( ConnectivityManager.CONNECTIVITY_ACTION)); mRestRequests = new RestRequests(); //initialize rest request initServiceConnection(); initContentView(); // Added by michae - 02.09.2015 registerReceiver(exitAppReceiver, new IntentFilter(SWGlobal.EXIT_APP)); } protected void startNetworking() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo(); if( networkInfo != null ) { if (networkInfo.isConnected()) { ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); // For 3G check is3g = manager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE) .isConnectedOrConnecting(); // For WiFi Check isWifi = manager.getNetworkInfo( ConnectivityManager.TYPE_WIFI) .isConnectedOrConnecting(); if (isWifi || is3g) { //getToken(); onServiceConnected(); updateData(); } else { } //mPopNoInternet.dismiss(); } } } private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { // Changed by Michael 14.02.2016 boolean isSplashActivity = MPBaseActivity.this instanceof SplashScreenActivity; if( !isSplashActivity ) startNetworking(); } }; public boolean isOnline() { ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo netInfo = cm.getActiveNetworkInfo(); if (netInfo != null && netInfo.isConnectedOrConnecting()) { return true; } return false; } protected void updateData() { } public static String getStringContent(String urlString) { URL url; try { // int downloadedSize = 0; Log.v("getStringContent", urlString); url = new URL(urlString); // create the new connection Log.v("getStringContent", "Create connection"); HttpURLConnection urlConnection = (HttpURLConnection) url .openConnection(); Log.v("getStringContent", "Connection opened"); // set up some things on the connection urlConnection.setRequestMethod("GET"); // urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(CONNECTION_CONNECT_TIMEOUT); urlConnection.setReadTimeout(CONNECTION_CONNECT_TIMEOUT); Log.v("getStringContent", "Connecting..."); urlConnection.connect(); Log.v("getStringContent", "Connecting done"); int retCode = urlConnection.getResponseCode(); if (retCode < 200 || retCode >= 300) { Log.v("getStringContent", "FileNotFoundException"); throw new FileNotFoundException(urlConnection.getURL() .toString() + " responsed " + String.valueOf(urlConnection.getResponseCode())); } // this will be used in reading the data from the internet InputStream inputStream = null; inputStream = urlConnection.getInputStream(); InputStreamReader reader = new InputStreamReader(inputStream); // this is the total size of the file // int totalSize = urlConnection.getContentLength() + // downloadedSize; // this will be used to write the downloaded data into the file we // created StringWriter sw = new StringWriter(); // create a buffer... char[] buffer = new char[1024]; int bufferLength = 0; // used to store a temporary size of the // buffer // now, read through the input buffer and write the contents to the // file while ((bufferLength = reader.read(buffer)) > 0 && !Thread.currentThread().isInterrupted()) { // add the data in the buffer to the file in the file output // stream (the file on the sd card sw.write(buffer, 0, bufferLength); } return sw.toString(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onStart() { if (mServiceConnection != null) { Intent intent; intent = new Intent(this, MPService.class); // getApplicationContext() added by Michael 14.07.2015 mServiceConnected = getApplicationContext().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); } super.onStart(); } /** * Must be overridden in derived activity. * <p/> * View initialization of current activity. <br> * Called from onCreate(). */ protected abstract void initContentView(); /** * Must be overridden in derived activity. * <p/> * Called when service connection established. <br> * Running in background thread. */ protected abstract void onServiceConnected(); /** * Service connection initialization. */ protected void initServiceConnection() { mServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mServiceConnected = false; mMPService = null; } @Override public void onServiceConnected(ComponentName cn, IBinder binder) { mMPService = ((MPService.MPServiceBinder) binder).getService(); // MPBaseActivity.this.onServiceConnected(); if (mIMPOnServiceConnectedListener != null) { mIMPOnServiceConnectedListener .onServiceConnected(mMPService); } } }; } @Override protected void onStop() { if (mServiceConnected && mServiceConnection != null) { // getApplicationContext() added by Michael 14.07.2015 getApplicationContext().unbindService(mServiceConnection); mServiceConnected = false; } super.onStop(); } /** * @return the mKBoxService */ public MPService getMPService() { return mMPService; } /** * @return the mServiceConnected */ public boolean isServiceConnected() { return mServiceConnected; } /** * @return the mISWOnServiceConnectedListener */ public IMPOnServiceConnectedListener getIMPOnServiceConnectedListener() { return mIMPOnServiceConnectedListener; } /** * @param listener the ISWOnServiceConnectedListener to set */ public void setIMPOnServiceConnectedListener( IMPOnServiceConnectedListener listener) { if (mServiceConnected && mMPService != null && listener != null) { listener.onServiceConnected(mMPService); } this.mIMPOnServiceConnectedListener = listener; } @Override public void onResume() { super.onResume(); //isAlive = true; } private String getContactDisplayNameByNumber(String number) { Uri uri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); String name = ""; ContentResolver contentResolver = getContentResolver(); Cursor contactLookup = contentResolver.query(uri, new String[]{ BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null); try { if (contactLookup != null && contactLookup.getCount() > 0) { contactLookup.moveToNext(); name = contactLookup.getString(contactLookup .getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); } } finally { if (contactLookup != null) { contactLookup.close(); } } return name; } @Override public void onPause() { getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); super.onPause(); } @Override protected void onDestroy() { //isAlive = false; unregisterReceiver(mConnReceiver); unregisterReceiver(exitAppReceiver); super.onDestroy(); } @SuppressWarnings("deprecation") public int getScreenWidth() { int width = 0; Display display = getWindowManager().getDefaultDisplay(); try { width = display.getWidth(); } catch (java.lang.NoSuchMethodError ignore) { } return width; } @SuppressWarnings("deprecation") public int getScreenHeight() { int height = 0; Display display = getWindowManager().getDefaultDisplay(); try { height = display.getHeight(); } catch (java.lang.NoSuchMethodError ignore) { } return height; } protected void prepareMenuListData(List<MainMenuItem> mainMenuList) { // List of the headers listDataHeader = new ArrayList<MainMenuItem>(); // List that maps header to array of child elements listDataChild = new HashMap<String, List<MainMenuItem>>(); // For internal use of this method. HashMap<String, String> listChildKey = new HashMap<String, String>(); for (MainMenuItem menuItem : mainMenuList) { String parentId = menuItem.parentCategoryId; // int sortOrder = Integer.valueOf(menuItem.sortOrder); if (menuItem.id.equals(parentId)) { // listDataHeader.add(new MainMenuParentItem(menuItem.id, menuItem.name, menuItem.imageURL)); listDataHeader.add(menuItem); listChildKey.put(menuItem.name, parentId); } else { if (listDataChild.get(parentId) != null) { listDataChild.get(parentId).add(menuItem); } else { List<MainMenuItem> childrenList = new ArrayList<MainMenuItem>(); listDataChild.put(parentId, childrenList); listDataChild.get(parentId).add(menuItem); } } } for (int i = 0; i < listChildKey.size(); i++) { String parentName = listDataHeader.get(i).name; String parentId = listChildKey.get(parentName); List<MainMenuItem> childObject = new ArrayList<MainMenuItem>(); childObject = listDataChild.get(parentId); if (childObject != null) { Collections.sort(childObject); } listDataChild.remove(parentId); listDataChild.put(parentName, childObject); } // Sort headers list Collections.sort(listDataHeader); // Sort children list within headers array if(listDataChild != null && listDataChild.size() > 0) { for (Map.Entry<String, List<MainMenuItem>> cursor : listDataChild.entrySet()) { if(cursor.getValue() != null) { Collections.sort(cursor.getValue()); } } } /* MainMenuItem settingsMenuItem = new MainMenuItem(); settingsMenuItem.id = AppUtils.MENU_SERVICE_SETTINGS; settingsMenuItem.name = getString(R.string.settings); listDataHeader.add(settingsMenuItem);*/ } protected void getLongToken(IMPRestGetResponseListener listener) { String shortToken = ((SWGlobal)getApplication()).getShortToken(); String url = MPRequestUrlBuilder.getLongTokenUrl(shortToken); mRestRequests.getAndParse(listener, url, NormalLoginItem.class, ""); } protected void longTokenResponse(LongTokenItem item, IMPRestGetResponseListener listener) { if (item.responseError == null) { ((SWGlobal) getApplication()).setLongToken(item.longToken); getMainScreenData(listener, null);/*Todo change normalLoginItem*/ } else { // finish();/*Todo handle with errors*/ exit(); } } protected void getMainScreenData(IMPRestGetResponseListener listener, NormalLoginItem item) { String url = MPRequestUrlBuilder.getMainScreenDataUrl(item); String longToken = item.longToken; mRestRequests.getAndParse(listener, url, MainScreenDataItem.class, longToken); } protected void loadMainActivity(MainScreenDataItem item) { ((SWGlobal) getApplication()).setMainScreenDataItem(item); prepareMenuListData(item.menuList); Intent intent = new Intent(getApplicationContext(), MainPageActivity.class); //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.putExtra(AppUtils.MENU_LIST, (ArrayList<MainMenuItem>) item.menuList); intent.putExtra(AppUtils.MENU_HEADER_LIST, (ArrayList<MainMenuItem>) listDataHeader); intent.putExtra(AppUtils.MENU_CHILDREN_LIST, listDataChild); // intent.putExtra(AppUtils.MENU_CHILD_KEY_LIST, listChildKey); startActivity(intent); // finish(); exit(); } protected void getBanners(IMPRestGetResponseListener restListener) { int userType = ((SWGlobal) getApplication()).getUserDetailsItem().userType; String url = MPRequestUrlBuilder.getBannersByCategoryUrl(AppUtils.MENU_MAIN_CATEGORY_CODE, userType); String longToken = ((SWGlobal) getApplication()).getUserDetailsItem().longToken; mRestRequests.getAndParse(restListener, url, BannersList.class, longToken); } protected void getPersonalBanners(IMPRestGetResponseListener restListener) { int userType = ((SWGlobal) getApplication()).getUserDetailsItem().userType; String subscriberNumber = ((SWGlobal) getApplication()).getUserDetailsItem().subscriberNumber; String url = MPRequestUrlBuilder.getPersonalBannersByCategoryUrl(AppUtils.MENU_PERSONAL_CATEGORY_CODE, userType, subscriberNumber); String longToken = ((SWGlobal) getApplication()).getUserDetailsItem().longToken; mRestRequests.getAndParse(restListener, url, BannersListPersonal.class, longToken); } public void getRegisteredServices(IMPRestGetResponseListener restListener) { String longToken = ((SWGlobal) getApplication()).getUserDetailsItem().longToken; String url = MPRequestUrlBuilder.getRegisteredServicesUrl(); mRestRequests.getAndParse(restListener, url, RegisteredServicesItem.class, longToken); } protected int getVersionCode() { PackageInfo pInfo = null; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); Log.i("versionCode", String.valueOf(pInfo.versionCode)); return pInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return 1; } protected String getVersionName() { PackageInfo pInfo = null; try { pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); Log.i("versionName", pInfo.versionName); return pInfo.versionName; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return "1.0"; } protected void navigateToGooglePlay(String appPackageName) { try { startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)), NAVIGATE_TO_GOOGLE_PLAY_REQUEST); } catch (android.content.ActivityNotFoundException anfe) { startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appPackageName)), NAVIGATE_TO_GOOGLE_PLAY_REQUEST); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == DialogSessionEndedActivity.SESSION_ENDED_KEY) { if (resultCode == DialogSessionEndedActivity.DISCONNECT) { // finish(); exit(); } else if (resultCode == DialogSessionEndedActivity.CONNECT){ Intent intent = new Intent(getApplicationContext(),SplashScreenActivity.class); startActivity(intent); // finish(); exit(); } } else if (requestCode == CONNECTION_PROBLEM_REQUEST){ // finish(); exit(); } } public void sessionEnded(){ Intent intent = new Intent(MPBaseActivity.this,DialogSessionEndedActivity.class); startActivityForResult(intent, DialogSessionEndedActivity.SESSION_ENDED_KEY); } // Added by Michael - 02.09.2015 private BroadcastReceiver exitAppReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(intent.getAction() != null) { if(intent.getAction().equals(SWGlobal.EXIT_APP) ) { exit(); } } } }; public void exit() { finish(); } }