index
int64 0
4.83k
| file_id
stringlengths 5
10
| content
stringlengths 110
32.8k
⌀ | repo
stringlengths 7
108
| path
stringlengths 8
198
| token_length
int64 37
8.19k
| original_comment
stringlengths 11
5.72k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | prompt
stringlengths 62
32.8k
| Inclusion
stringclasses 4
values |
---|---|---|---|---|---|---|---|---|---|---|
1,685 | 55988_1 | package com.crm.qa.pages;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.qa.base.TestBase;
public class EntrepreneursPageFree extends TestBase{
//Page factory OR Object Repository
@FindBy(xpath="//input[@id='filter-search-input']")
WebElement findEntrepreneur;
@FindBy(xpath="//span[@class='material-icons clear-icon']")
WebElement clickCancel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/button")
WebElement workingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/div/form/div[4]/label")
WebElement selectWorkingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/button")
WebElement descipline;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/div/form/div[7]/label")
WebElement selectDescipline;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/button")
WebElement areaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/div/form/div[8]/label")
WebElement selectAreaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-skills-btn\"]")
WebElement skills;
@FindBy(xpath="//input[@placeholder='Zoek een vaardigheid']")
WebElement enterSkill;
@FindBy(xpath="//*[@id=\"result-list-31667\"]/a/div[2]/span/span")
WebElement selectSkill;
@FindBy(xpath="/html/body/div[1]/main/div/nav/div[2]/div/div[4]/div/form/div[1]/div/div/div[2]/a/div[2]/span/span")
WebElement selectSkillToolTip;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/button")
WebElement clickApplyFilter;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/a[2]")
WebElement clickResetFilter;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select")
WebElement clickSortingDropDown;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[3]")
WebElement selectSortingZtoA;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[2]")
WebElement selectSortingAtoZ;
//Initialization
public EntrepreneursPageFree() {
PageFactory.initElements(Driver, this);
}
//Actions
public void enterEntrepreneur(String value) {
findEntrepreneur.sendKeys(value);
}
public void clickCancel() {
clickCancel.click();
}
public void clickWorkingThinkingDropDown() {
workingThinkingLevel.click();
}
public void selectWorkingThinkingLevel() {
selectWorkingThinkingLevel.click();
}
public void clickDesciplineDropDown() {
descipline.click();
}
public void selectDescipline() {
selectDescipline.click();
}
public void clickAreaOfInterestDropDown() {
areaOfInterest.click();
}
public void selectAreaOfInterest() {
selectAreaOfInterest.click();
}
public void clickSkillsTab() {
skills.click();
}
public void enterSkill() {
enterSkill.click();
}
public void enterSkill(String value) {
enterSkill.sendKeys(value);
}
public void selectSkillToolTip() {
//selectSkillToolTip.click();
enterSkill.sendKeys(Keys.TAB);
}
public void clickApplyFilter() {
clickApplyFilter.click();
}
public void clickResetFilter() {
clickResetFilter.click();
}
public void clickSortingDropDown() {
clickSortingDropDown.click();
}
public void selectSortingZtoA() {
selectSortingZtoA.click();
}
public void selectSortingAtoZ() {
selectSortingAtoZ.click();
}
}
| TarunBtn/FreeCRMTestOne | FreeCRMTestOne/src/main/java/com/crm/qa/pages/EntrepreneursPageFree.java | 1,319 | //input[@placeholder='Zoek een vaardigheid']") | line_comment | nl | package com.crm.qa.pages;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.crm.qa.base.TestBase;
public class EntrepreneursPageFree extends TestBase{
//Page factory OR Object Repository
@FindBy(xpath="//input[@id='filter-search-input']")
WebElement findEntrepreneur;
@FindBy(xpath="//span[@class='material-icons clear-icon']")
WebElement clickCancel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/button")
WebElement workingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-werkdenkniveau\"]/div/form/div[4]/label")
WebElement selectWorkingThinkingLevel;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/button")
WebElement descipline;
@FindBy(xpath="//*[@id=\"dropdown-vakgebied\"]/div/form/div[7]/label")
WebElement selectDescipline;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/button")
WebElement areaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-interessegebied\"]/div/form/div[8]/label")
WebElement selectAreaOfInterest;
@FindBy(xpath="//*[@id=\"dropdown-skills-btn\"]")
WebElement skills;
@FindBy(xpath="//input[@placeholder='Zoek een<SUF>
WebElement enterSkill;
@FindBy(xpath="//*[@id=\"result-list-31667\"]/a/div[2]/span/span")
WebElement selectSkill;
@FindBy(xpath="/html/body/div[1]/main/div/nav/div[2]/div/div[4]/div/form/div[1]/div/div/div[2]/a/div[2]/span/span")
WebElement selectSkillToolTip;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/button")
WebElement clickApplyFilter;
@FindBy(xpath="//*[@id=\"dropdown-skills\"]/div/form/div[4]/a[2]")
WebElement clickResetFilter;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select")
WebElement clickSortingDropDown;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[3]")
WebElement selectSortingZtoA;
@FindBy(xpath="//*[@id=\"assignment-sorting\"]/div/select/option[2]")
WebElement selectSortingAtoZ;
//Initialization
public EntrepreneursPageFree() {
PageFactory.initElements(Driver, this);
}
//Actions
public void enterEntrepreneur(String value) {
findEntrepreneur.sendKeys(value);
}
public void clickCancel() {
clickCancel.click();
}
public void clickWorkingThinkingDropDown() {
workingThinkingLevel.click();
}
public void selectWorkingThinkingLevel() {
selectWorkingThinkingLevel.click();
}
public void clickDesciplineDropDown() {
descipline.click();
}
public void selectDescipline() {
selectDescipline.click();
}
public void clickAreaOfInterestDropDown() {
areaOfInterest.click();
}
public void selectAreaOfInterest() {
selectAreaOfInterest.click();
}
public void clickSkillsTab() {
skills.click();
}
public void enterSkill() {
enterSkill.click();
}
public void enterSkill(String value) {
enterSkill.sendKeys(value);
}
public void selectSkillToolTip() {
//selectSkillToolTip.click();
enterSkill.sendKeys(Keys.TAB);
}
public void clickApplyFilter() {
clickApplyFilter.click();
}
public void clickResetFilter() {
clickResetFilter.click();
}
public void clickSortingDropDown() {
clickSortingDropDown.click();
}
public void selectSortingZtoA() {
selectSortingZtoA.click();
}
public void selectSortingAtoZ() {
selectSortingAtoZ.click();
}
}
| False |
592 | 52480_0 | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| Gentlemannerss/digicoachindezorg_backend | src/main/java/com/digicoachindezorg/digicoachindezorg_backend/config/GlobalCorsConfiguration.java | 323 | /*
CORS (Cross Origin Resource Sharing) is een instelling die zorgt dat de frontend en de backend met elkaar kunnen
communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080).
De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten.
Vergeet niet om in de security config ook de ".cors()" optie aan te zetten.
*/ | block_comment | nl | package com.digicoachindezorg.digicoachindezorg_backend.config;
/*
CORS (Cross Origin<SUF>*/
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GlobalCorsConfiguration
{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
}
};
}
}
| True |
2,513 | 192651_6 | package com.rida.behaviours;
import com.rida.agents.DriverAgent;
import com.rida.tools.Consts;
import com.rida.tools.DriverDescription;
import com.rida.tools.Graph;
import com.rida.tools.Helper;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.List;
/**
* Поведение пассажира
*/
public class ServerPassengerBehaviour extends TickerBehaviour {
private static final Logger LOG = LoggerFactory.getLogger(ServerPassengerBehaviour.class);
private static final long serialVersionUID = -4274531231778761295L;
private DriverAgent driverAgent;
private boolean sendedRequests = false;
private Set<DriverDescription> potentialChauffeurs = new HashSet<>();
private boolean waitForConfirm = false;
private AID expectedChauffeur = null;
private double initialCost = Double.NaN;
private Set<DriverDescription> passengersToAttempt = null;
private Set<DriverDescription> agreedPassengers = null;
private Set<DriverDescription> disagreedPassengers = null;
private Set<AID> badPassengers = new HashSet<>();
private boolean deleted = false;
private boolean failToTryChauffeurFlag = false;
public ServerPassengerBehaviour(Agent a, long period) {
super(a, period);
}
private boolean containsPotentialChauffeurByAID(AID aid) {
for (DriverDescription dd : potentialChauffeurs) {
if (dd.getName().equals(aid.getName())) {
return true;
}
}
return false;
}
private void becomeChaufferAndInformAll() {
driverAgent.becomeChauffeur();
LOG.info("chauffeur now!");
sendMessage(null, ACLMessage.INFORM, Consts.IMCHAUFFER_ID, potentialChauffeurs);
// LOG.info(" inform about new chauffeur other potential chauffeurs");
sendMessage(null, ACLMessage.INFORM, Consts.IMCHAUFFER_ID, driverAgent.getSetPotentialPassengers());
// LOG.info("inform about new chauffeur gother potential passengers");
potentialChauffeurs.clear();
if (waitForConfirm)
throw new IllegalStateException("WHAAAAAAAAAAT!!");
}
private void removePotentialChauffeur(AID aid) {
for (DriverDescription dd : potentialChauffeurs) {
if (dd.getName().equals(aid.getName())) {
potentialChauffeurs.remove(dd);
return;
}
}
// throw new IllegalStateException("not found potential chauffer while removing " + aid.getLocalName());
}
private boolean shouldBeChauffeur(Set<DriverDescription> currentPassengers) {
// HashSet<DriverDescription> currentPassengers = new HashSet<>();
// for(DriverDescription dd : _currentPassengers) {
// if (!badPassengers.contains(dd.getAid())) {
// currentPassengers.add(dd);
// }
// }
Set<DriverDescription> passengers = Helper.getBestPassengers(driverAgent, currentPassengers);
if (passengers == null || passengers.isEmpty())
return false;
boolean flag = (Helper.calcBestSetProfit(passengers, driverAgent.getMapGraph(), driverAgent.getDescription().getTrip()) > 0f);
if (flag) {
passengersToAttempt = new HashSet<>(passengers);
agreedPassengers = new HashSet<>();
disagreedPassengers = new HashSet<>();
}
return flag;
}
private double calcCost() {
Graph g = driverAgent.getMapGraph();
int from = driverAgent.getDescription().getTrip().getFrom();
int to = driverAgent.getDescription().getTrip().getTo();
double cost = g.bfs(from, to);
Random rand = new Random();
cost += cost * 0.00001 * (rand.nextInt() % 200 - 100);
return cost;
}
private void checkBecomeChauffeur() {
if (potentialChauffeurs.isEmpty() && passengersToAttempt == null) {
if (waitForConfirm)
throw new IllegalStateException();
becomeChaufferAndInformAll();
LOG.info("chauffeur because there is no one good driver");
}
}
private void sendRequests() {
sendedRequests = true;
potentialChauffeurs = driverAgent.getGoodTrips();
double cost = calcCost();
initialCost = cost;
ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
cfp.setContent(String.valueOf(cost));
cfp.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription driver : potentialChauffeurs) {
cfp.addReceiver(driver.getAid());
LOG.info(" send a message to " + driver.getAid().getLocalName() + " with cost " + cost);
}
driverAgent.send(cfp);
}
private void receiveRejectFromPotentialChauffeurs() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REJECT_PROPOSAL),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
replyOnRejectFromPotentialChauffeurs(msg);
}
}
private void replyOnRejectFromPotentialChauffeurs(ACLMessage message) {
AID senderAID = message.getSender();
ACLMessage newMsg = message.createReply();
double newCost = Double.parseDouble(message.getContent());
newCost *= Consts.PASSANGER_COEF_NEW_COST;
if (newCost > Consts.PASSANGER_COEF_LIMIT * initialCost) {
removePotentialChauffeur(senderAID);
if (!containsPotentialChauffeurByAID(senderAID))
return;
newMsg.setContent("Too expensive");
newMsg.setPerformative(ACLMessage.REFUSE);
LOG.info(" refuse because this guy - " + senderAID.getLocalName() + " too expensive");
if (potentialChauffeurs.isEmpty()) {
becomeChaufferAndInformAll();
LOG.info(" chauffeur because other chauffeurs are too expensive or rejected my proposal");
return;
}
} else {
newMsg.setContent(String.valueOf(newCost));
newMsg.setPerformative(ACLMessage.CFP);
LOG.info(" new cost(" + newCost + ") for chauffeur " + senderAID.getLocalName());
}
driverAgent.send(newMsg);
}
private void receiveRequestFromPotentialPassengers() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CFP),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg = null;
double currentCost;
List<ACLMessage> messages = new LinkedList<>();
while ((msg = myAgent.receive(mt)) != null) {
AID driverAID = msg.getSender();
boolean flag = driverAgent.addPotentialPassengerByName(driverAID);
if (flag) {
currentCost = Double.parseDouble(msg.getContent());
driverAgent.setCostToPotentialPassenger(driverAID, currentCost);
messages.add((ACLMessage) msg.clone());
LOG.info(" got msg CFP from potential passenger " + msg.getSender().getLocalName());
}
}
if (!messages.isEmpty() && passengersToAttempt == null &&
!waitForConfirm && shouldBeChauffeur(driverAgent.getSetPotentialPassengers())) {
tryToBecomeChauffeur();
LOG.info("i'm trying to become chauffeur");
} else {
for (ACLMessage message : messages) {
ACLMessage newMsg = message.createReply();
newMsg.setContent(message.getContent());
newMsg.setPerformative(ACLMessage.REJECT_PROPOSAL);
driverAgent.send(newMsg);
LOG.info(" need more money, sended to " + message.getSender().getLocalName());
}
}
}
private void tryToBecomeChauffeur() {
if (deleted)
return;
ACLMessage msg = new ACLMessage(ACLMessage.ACCEPT_PROPOSAL);
msg.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : passengersToAttempt) {
msg.addReceiver(dd.getAid());
LOG.info("try to bring passenger " + dd.getAid().getLocalName());
}
driverAgent.send(msg);
}
private void failTryToBeChauffeur() {
ACLMessage newMsg = new ACLMessage(ACLMessage.DISCONFIRM);
newMsg.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : agreedPassengers) {
newMsg.addReceiver(dd.getAid());
LOG.info(" FAIL! disconfirm to " + dd.getAid().getLocalName());
}
driverAgent.send(newMsg);
HashSet<DriverDescription> newSet = new HashSet<>(driverAgent.getSetPotentialPassengers());
for (DriverDescription dd : disagreedPassengers) {
Helper.removeFromCollectionByAID(newSet, dd.getAid());
}
passengersToAttempt = null;
agreedPassengers = null;
disagreedPassengers = null;
if (shouldBeChauffeur(newSet)) {
tryToBecomeChauffeur();
}
}
private void handleForAttemptToBeChauffeur() {
if (passengersToAttempt == null || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CANCEL),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
if ((msg = myAgent.receive(mt)) != null) {
if (Helper.containsInCollectionByAID(passengersToAttempt, msg.getSender())) {
failToTryChauffeurFlag = true;
disagreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, msg.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, msg.getSender());
// badPassengers.add(msg.getSender());
}
if (passengersToAttempt.isEmpty()) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
return;
}
}
MessageTemplate goodMT = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.AGREE),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage goodMSG;
while ((goodMSG = myAgent.receive(goodMT)) != null) {
if (Helper.containsInCollectionByAID(passengersToAttempt, goodMSG.getSender())) {
agreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, goodMSG.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, goodMSG.getSender());
}
}
if (passengersToAttempt.isEmpty()) {
if (failToTryChauffeurFlag) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
} else {
ACLMessage successMSG = new ACLMessage(ACLMessage.CONFIRM);
successMSG.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : agreedPassengers) {
LOG.info("gone like chauffeur with passenger " + dd.getAid().getLocalName());
successMSG.addReceiver(dd.getAid());
}
driverAgent.send(successMSG);
ACLMessage infoMSG = new ACLMessage(ACLMessage.INFORM);
infoMSG.setConversationId(Consts.IMGONE_ID);
Set<DriverDescription> allDrivers = driverAgent.getDrivers();
for (DriverDescription dd : allDrivers) {
if (!Helper.containsInCollectionByAID(agreedPassengers, dd.getAid())) {
// LOG.info("gone like chauffeur. Notification for " + dd.getAid().getLocalName());
infoMSG.addReceiver(dd.getAid());
}
}
driverAgent.send(infoMSG);
deleted = true;
}
}
}
private void handleRefuseFromPotentialPassengers() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REFUSE),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
driverAgent.removePotentialPassenger(msg.getSender());
}
}
private void handleInformAboutChauffeur() {
if (deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
MessageTemplate.MatchConversationId(Consts.IMCHAUFFER_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
driverAgent.removePotentialPassenger(msg.getSender());
LOG.info(" i've got message about new chauffeur - " +
msg.getSender().getLocalName());
}
}
private void handleAcceptFromPotentialChauffeur() {
if (driverAgent.isChauffeur() || deleted || waitForConfirm)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(
ACLMessage.ACCEPT_PROPOSAL), MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
if (passengersToAttempt != null) {
if (expectedChauffeur == msg.getSender())
throw new IllegalStateException("unexpected accept from " + msg.getSender().getLocalName());
ACLMessage newMsg = msg.createReply();
newMsg.setPerformative(ACLMessage.CANCEL);
LOG.info("cancel accept from " + msg.getSender().getLocalName() + " because i'm trying to be chauffeur");
myAgent.send(newMsg);
continue;
}
LOG.info(" have handled accept proposal from chauffeur - " + msg.getSender().getLocalName());
waitForConfirm = true;
ACLMessage newMsg = msg.createReply();
newMsg.setPerformative(ACLMessage.AGREE);
expectedChauffeur = msg.getSender();
LOG.info(" send AGREE to " + msg.getSender().getLocalName());
myAgent.send(newMsg);
break;
}
}
private void sendMessage(String content, int performative, String id, Set<DriverDescription> receivers) {
ACLMessage message = new ACLMessage(performative);
message.setConversationId(id);
for (DriverDescription dd : receivers) {
AID reciverAID = dd.getAid();
if (reciverAID.equals(driverAgent.getAID())) {
message.addReceiver(dd.getAid());
}
}
message.setContent(content);
driverAgent.send(message);
}
private void handleConfirmFromPotentialChauffeur() {
if (!waitForConfirm || driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CONFIRM),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage message;
while ((message = myAgent.receive(mt)) != null) {
AID senderAID = message.getSender();
if (!senderAID.equals(expectedChauffeur)) {
throw new IllegalStateException("confirm from unexpected chauffeur - " + senderAID);
}
ACLMessage newMsg = new ACLMessage(ACLMessage.INFORM);
newMsg.setConversationId(Consts.IMGONE_ID);
for (DriverDescription dd : driverAgent.getDrivers()) {
if (dd.getAid() != senderAID && !dd.getAid().getLocalName().equals(myAgent.getAID().getLocalName())) {
newMsg.addReceiver(dd.getAid());
// LOG.info(" notificate " + dd.getAid().getLocalName() + " that i've gone like passenger ");
}
}
driverAgent.send(newMsg);
LOG.info(" CONFIRM! i gone like passenger(with " + senderAID.getLocalName() + " )");
deleted = true;
break;
}
}
private void handleDisconfirmFromPotentialChauffeur() {
if (!waitForConfirm || driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.DISCONFIRM),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
if (msg.getSender().getLocalName().equals(expectedChauffeur.getLocalName())) {
waitForConfirm = false;
expectedChauffeur = null;
LOG.info(" i've handled disconfirm from chauffeur " + msg.getSender().getLocalName());
return;
}
}
}
private void handleInformAboutLeaving() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
MessageTemplate.MatchConversationId(Consts.IMGONE_ID));
ACLMessage message;
while ((message = myAgent.receive(mt)) != null) {
if (passengersToAttempt != null && Helper.containsInCollectionByAID(passengersToAttempt, message.getSender())) {
failToTryChauffeurFlag = true;
disagreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, message.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, message.getSender());
}
LOG.info(" i've(passenger) got message about leaving " + message.getSender().getLocalName());
driverAgent.addGoneDriver(message.getSender());
driverAgent.removePotentialPassenger(message.getSender());
removePotentialChauffeur(message.getSender());
if (potentialChauffeurs.isEmpty() && passengersToAttempt == null) {
// if (waitForConfirm)
// throw new IllegalStateException("try to become chauffeur while waiting confirm");
becomeChaufferAndInformAll();
LOG.info(" chauffeur because all guys leaving");
}
}
if (passengersToAttempt != null && passengersToAttempt.isEmpty()) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
}
}
private void sendPassengerStatistic() {
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(driverAgent.getAID());
ServiceDescription sd = new ServiceDescription();
sd.setType(Consts.STATISTICS_ID);
sd.setName(driverAgent.getName());
sd.addProperties(new Property("type", "passenger"));
dfd.addServices(sd);
try {
DFService.modify(driverAgent, dfd);
} catch (FIPAException fe) {
LOG.error("Failed to register agent in Yellow Pages Service caused {}\n", fe);
}
}
@Override
public void onTick() {
driverAgent = (DriverAgent) myAgent;
if (driverAgent.isChauffeur())
return;
if (!sendedRequests) {
sendRequests();
return;
} else {
checkBecomeChauffeur();
}
receiveRequestFromPotentialPassengers();
handleForAttemptToBeChauffeur();
handleRefuseFromPotentialPassengers();
handleInformAboutLeaving();
receiveRejectFromPotentialChauffeurs();
handleAcceptFromPotentialChauffeur();
handleDisconfirmFromPotentialChauffeur();
handleConfirmFromPotentialChauffeur();
handleInformAboutChauffeur();
if (deleted) {
sendPassengerStatistic();
driverAgent.doDelete();
}
}
} | daynekoroman/MAS | src/main/java/com/rida/behaviours/ServerPassengerBehaviour.java | 5,869 | // if (!badPassengers.contains(dd.getAid())) { | line_comment | nl | package com.rida.behaviours;
import com.rida.agents.DriverAgent;
import com.rida.tools.Consts;
import com.rida.tools.DriverDescription;
import com.rida.tools.Graph;
import com.rida.tools.Helper;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.TickerBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.Property;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.domain.FIPAException;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.List;
/**
* Поведение пассажира
*/
public class ServerPassengerBehaviour extends TickerBehaviour {
private static final Logger LOG = LoggerFactory.getLogger(ServerPassengerBehaviour.class);
private static final long serialVersionUID = -4274531231778761295L;
private DriverAgent driverAgent;
private boolean sendedRequests = false;
private Set<DriverDescription> potentialChauffeurs = new HashSet<>();
private boolean waitForConfirm = false;
private AID expectedChauffeur = null;
private double initialCost = Double.NaN;
private Set<DriverDescription> passengersToAttempt = null;
private Set<DriverDescription> agreedPassengers = null;
private Set<DriverDescription> disagreedPassengers = null;
private Set<AID> badPassengers = new HashSet<>();
private boolean deleted = false;
private boolean failToTryChauffeurFlag = false;
public ServerPassengerBehaviour(Agent a, long period) {
super(a, period);
}
private boolean containsPotentialChauffeurByAID(AID aid) {
for (DriverDescription dd : potentialChauffeurs) {
if (dd.getName().equals(aid.getName())) {
return true;
}
}
return false;
}
private void becomeChaufferAndInformAll() {
driverAgent.becomeChauffeur();
LOG.info("chauffeur now!");
sendMessage(null, ACLMessage.INFORM, Consts.IMCHAUFFER_ID, potentialChauffeurs);
// LOG.info(" inform about new chauffeur other potential chauffeurs");
sendMessage(null, ACLMessage.INFORM, Consts.IMCHAUFFER_ID, driverAgent.getSetPotentialPassengers());
// LOG.info("inform about new chauffeur gother potential passengers");
potentialChauffeurs.clear();
if (waitForConfirm)
throw new IllegalStateException("WHAAAAAAAAAAT!!");
}
private void removePotentialChauffeur(AID aid) {
for (DriverDescription dd : potentialChauffeurs) {
if (dd.getName().equals(aid.getName())) {
potentialChauffeurs.remove(dd);
return;
}
}
// throw new IllegalStateException("not found potential chauffer while removing " + aid.getLocalName());
}
private boolean shouldBeChauffeur(Set<DriverDescription> currentPassengers) {
// HashSet<DriverDescription> currentPassengers = new HashSet<>();
// for(DriverDescription dd : _currentPassengers) {
// if (!badPassengers.contains(dd.getAid()))<SUF>
// currentPassengers.add(dd);
// }
// }
Set<DriverDescription> passengers = Helper.getBestPassengers(driverAgent, currentPassengers);
if (passengers == null || passengers.isEmpty())
return false;
boolean flag = (Helper.calcBestSetProfit(passengers, driverAgent.getMapGraph(), driverAgent.getDescription().getTrip()) > 0f);
if (flag) {
passengersToAttempt = new HashSet<>(passengers);
agreedPassengers = new HashSet<>();
disagreedPassengers = new HashSet<>();
}
return flag;
}
private double calcCost() {
Graph g = driverAgent.getMapGraph();
int from = driverAgent.getDescription().getTrip().getFrom();
int to = driverAgent.getDescription().getTrip().getTo();
double cost = g.bfs(from, to);
Random rand = new Random();
cost += cost * 0.00001 * (rand.nextInt() % 200 - 100);
return cost;
}
private void checkBecomeChauffeur() {
if (potentialChauffeurs.isEmpty() && passengersToAttempt == null) {
if (waitForConfirm)
throw new IllegalStateException();
becomeChaufferAndInformAll();
LOG.info("chauffeur because there is no one good driver");
}
}
private void sendRequests() {
sendedRequests = true;
potentialChauffeurs = driverAgent.getGoodTrips();
double cost = calcCost();
initialCost = cost;
ACLMessage cfp = new ACLMessage(ACLMessage.CFP);
cfp.setContent(String.valueOf(cost));
cfp.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription driver : potentialChauffeurs) {
cfp.addReceiver(driver.getAid());
LOG.info(" send a message to " + driver.getAid().getLocalName() + " with cost " + cost);
}
driverAgent.send(cfp);
}
private void receiveRejectFromPotentialChauffeurs() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REJECT_PROPOSAL),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
replyOnRejectFromPotentialChauffeurs(msg);
}
}
private void replyOnRejectFromPotentialChauffeurs(ACLMessage message) {
AID senderAID = message.getSender();
ACLMessage newMsg = message.createReply();
double newCost = Double.parseDouble(message.getContent());
newCost *= Consts.PASSANGER_COEF_NEW_COST;
if (newCost > Consts.PASSANGER_COEF_LIMIT * initialCost) {
removePotentialChauffeur(senderAID);
if (!containsPotentialChauffeurByAID(senderAID))
return;
newMsg.setContent("Too expensive");
newMsg.setPerformative(ACLMessage.REFUSE);
LOG.info(" refuse because this guy - " + senderAID.getLocalName() + " too expensive");
if (potentialChauffeurs.isEmpty()) {
becomeChaufferAndInformAll();
LOG.info(" chauffeur because other chauffeurs are too expensive or rejected my proposal");
return;
}
} else {
newMsg.setContent(String.valueOf(newCost));
newMsg.setPerformative(ACLMessage.CFP);
LOG.info(" new cost(" + newCost + ") for chauffeur " + senderAID.getLocalName());
}
driverAgent.send(newMsg);
}
private void receiveRequestFromPotentialPassengers() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CFP),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg = null;
double currentCost;
List<ACLMessage> messages = new LinkedList<>();
while ((msg = myAgent.receive(mt)) != null) {
AID driverAID = msg.getSender();
boolean flag = driverAgent.addPotentialPassengerByName(driverAID);
if (flag) {
currentCost = Double.parseDouble(msg.getContent());
driverAgent.setCostToPotentialPassenger(driverAID, currentCost);
messages.add((ACLMessage) msg.clone());
LOG.info(" got msg CFP from potential passenger " + msg.getSender().getLocalName());
}
}
if (!messages.isEmpty() && passengersToAttempt == null &&
!waitForConfirm && shouldBeChauffeur(driverAgent.getSetPotentialPassengers())) {
tryToBecomeChauffeur();
LOG.info("i'm trying to become chauffeur");
} else {
for (ACLMessage message : messages) {
ACLMessage newMsg = message.createReply();
newMsg.setContent(message.getContent());
newMsg.setPerformative(ACLMessage.REJECT_PROPOSAL);
driverAgent.send(newMsg);
LOG.info(" need more money, sended to " + message.getSender().getLocalName());
}
}
}
private void tryToBecomeChauffeur() {
if (deleted)
return;
ACLMessage msg = new ACLMessage(ACLMessage.ACCEPT_PROPOSAL);
msg.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : passengersToAttempt) {
msg.addReceiver(dd.getAid());
LOG.info("try to bring passenger " + dd.getAid().getLocalName());
}
driverAgent.send(msg);
}
private void failTryToBeChauffeur() {
ACLMessage newMsg = new ACLMessage(ACLMessage.DISCONFIRM);
newMsg.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : agreedPassengers) {
newMsg.addReceiver(dd.getAid());
LOG.info(" FAIL! disconfirm to " + dd.getAid().getLocalName());
}
driverAgent.send(newMsg);
HashSet<DriverDescription> newSet = new HashSet<>(driverAgent.getSetPotentialPassengers());
for (DriverDescription dd : disagreedPassengers) {
Helper.removeFromCollectionByAID(newSet, dd.getAid());
}
passengersToAttempt = null;
agreedPassengers = null;
disagreedPassengers = null;
if (shouldBeChauffeur(newSet)) {
tryToBecomeChauffeur();
}
}
private void handleForAttemptToBeChauffeur() {
if (passengersToAttempt == null || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CANCEL),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
if ((msg = myAgent.receive(mt)) != null) {
if (Helper.containsInCollectionByAID(passengersToAttempt, msg.getSender())) {
failToTryChauffeurFlag = true;
disagreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, msg.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, msg.getSender());
// badPassengers.add(msg.getSender());
}
if (passengersToAttempt.isEmpty()) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
return;
}
}
MessageTemplate goodMT = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.AGREE),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage goodMSG;
while ((goodMSG = myAgent.receive(goodMT)) != null) {
if (Helper.containsInCollectionByAID(passengersToAttempt, goodMSG.getSender())) {
agreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, goodMSG.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, goodMSG.getSender());
}
}
if (passengersToAttempt.isEmpty()) {
if (failToTryChauffeurFlag) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
} else {
ACLMessage successMSG = new ACLMessage(ACLMessage.CONFIRM);
successMSG.setConversationId(Consts.BRINGUP_ID);
for (DriverDescription dd : agreedPassengers) {
LOG.info("gone like chauffeur with passenger " + dd.getAid().getLocalName());
successMSG.addReceiver(dd.getAid());
}
driverAgent.send(successMSG);
ACLMessage infoMSG = new ACLMessage(ACLMessage.INFORM);
infoMSG.setConversationId(Consts.IMGONE_ID);
Set<DriverDescription> allDrivers = driverAgent.getDrivers();
for (DriverDescription dd : allDrivers) {
if (!Helper.containsInCollectionByAID(agreedPassengers, dd.getAid())) {
// LOG.info("gone like chauffeur. Notification for " + dd.getAid().getLocalName());
infoMSG.addReceiver(dd.getAid());
}
}
driverAgent.send(infoMSG);
deleted = true;
}
}
}
private void handleRefuseFromPotentialPassengers() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.REFUSE),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
driverAgent.removePotentialPassenger(msg.getSender());
}
}
private void handleInformAboutChauffeur() {
if (deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
MessageTemplate.MatchConversationId(Consts.IMCHAUFFER_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
driverAgent.removePotentialPassenger(msg.getSender());
LOG.info(" i've got message about new chauffeur - " +
msg.getSender().getLocalName());
}
}
private void handleAcceptFromPotentialChauffeur() {
if (driverAgent.isChauffeur() || deleted || waitForConfirm)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(
ACLMessage.ACCEPT_PROPOSAL), MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
if (passengersToAttempt != null) {
if (expectedChauffeur == msg.getSender())
throw new IllegalStateException("unexpected accept from " + msg.getSender().getLocalName());
ACLMessage newMsg = msg.createReply();
newMsg.setPerformative(ACLMessage.CANCEL);
LOG.info("cancel accept from " + msg.getSender().getLocalName() + " because i'm trying to be chauffeur");
myAgent.send(newMsg);
continue;
}
LOG.info(" have handled accept proposal from chauffeur - " + msg.getSender().getLocalName());
waitForConfirm = true;
ACLMessage newMsg = msg.createReply();
newMsg.setPerformative(ACLMessage.AGREE);
expectedChauffeur = msg.getSender();
LOG.info(" send AGREE to " + msg.getSender().getLocalName());
myAgent.send(newMsg);
break;
}
}
private void sendMessage(String content, int performative, String id, Set<DriverDescription> receivers) {
ACLMessage message = new ACLMessage(performative);
message.setConversationId(id);
for (DriverDescription dd : receivers) {
AID reciverAID = dd.getAid();
if (reciverAID.equals(driverAgent.getAID())) {
message.addReceiver(dd.getAid());
}
}
message.setContent(content);
driverAgent.send(message);
}
private void handleConfirmFromPotentialChauffeur() {
if (!waitForConfirm || driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.CONFIRM),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage message;
while ((message = myAgent.receive(mt)) != null) {
AID senderAID = message.getSender();
if (!senderAID.equals(expectedChauffeur)) {
throw new IllegalStateException("confirm from unexpected chauffeur - " + senderAID);
}
ACLMessage newMsg = new ACLMessage(ACLMessage.INFORM);
newMsg.setConversationId(Consts.IMGONE_ID);
for (DriverDescription dd : driverAgent.getDrivers()) {
if (dd.getAid() != senderAID && !dd.getAid().getLocalName().equals(myAgent.getAID().getLocalName())) {
newMsg.addReceiver(dd.getAid());
// LOG.info(" notificate " + dd.getAid().getLocalName() + " that i've gone like passenger ");
}
}
driverAgent.send(newMsg);
LOG.info(" CONFIRM! i gone like passenger(with " + senderAID.getLocalName() + " )");
deleted = true;
break;
}
}
private void handleDisconfirmFromPotentialChauffeur() {
if (!waitForConfirm || driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.DISCONFIRM),
MessageTemplate.MatchConversationId(Consts.BRINGUP_ID));
ACLMessage msg;
while ((msg = myAgent.receive(mt)) != null) {
if (msg.getSender().getLocalName().equals(expectedChauffeur.getLocalName())) {
waitForConfirm = false;
expectedChauffeur = null;
LOG.info(" i've handled disconfirm from chauffeur " + msg.getSender().getLocalName());
return;
}
}
}
private void handleInformAboutLeaving() {
if (driverAgent.isChauffeur() || deleted)
return;
MessageTemplate mt = MessageTemplate.and(MessageTemplate.MatchPerformative(ACLMessage.INFORM),
MessageTemplate.MatchConversationId(Consts.IMGONE_ID));
ACLMessage message;
while ((message = myAgent.receive(mt)) != null) {
if (passengersToAttempt != null && Helper.containsInCollectionByAID(passengersToAttempt, message.getSender())) {
failToTryChauffeurFlag = true;
disagreedPassengers.add(Helper.getFromCollectionByAID(passengersToAttempt, message.getSender()));
Helper.removeFromCollectionByAID(passengersToAttempt, message.getSender());
}
LOG.info(" i've(passenger) got message about leaving " + message.getSender().getLocalName());
driverAgent.addGoneDriver(message.getSender());
driverAgent.removePotentialPassenger(message.getSender());
removePotentialChauffeur(message.getSender());
if (potentialChauffeurs.isEmpty() && passengersToAttempt == null) {
// if (waitForConfirm)
// throw new IllegalStateException("try to become chauffeur while waiting confirm");
becomeChaufferAndInformAll();
LOG.info(" chauffeur because all guys leaving");
}
}
if (passengersToAttempt != null && passengersToAttempt.isEmpty()) {
failToTryChauffeurFlag = false;
failTryToBeChauffeur();
}
}
private void sendPassengerStatistic() {
DFAgentDescription dfd = new DFAgentDescription();
dfd.setName(driverAgent.getAID());
ServiceDescription sd = new ServiceDescription();
sd.setType(Consts.STATISTICS_ID);
sd.setName(driverAgent.getName());
sd.addProperties(new Property("type", "passenger"));
dfd.addServices(sd);
try {
DFService.modify(driverAgent, dfd);
} catch (FIPAException fe) {
LOG.error("Failed to register agent in Yellow Pages Service caused {}\n", fe);
}
}
@Override
public void onTick() {
driverAgent = (DriverAgent) myAgent;
if (driverAgent.isChauffeur())
return;
if (!sendedRequests) {
sendRequests();
return;
} else {
checkBecomeChauffeur();
}
receiveRequestFromPotentialPassengers();
handleForAttemptToBeChauffeur();
handleRefuseFromPotentialPassengers();
handleInformAboutLeaving();
receiveRejectFromPotentialChauffeurs();
handleAcceptFromPotentialChauffeur();
handleDisconfirmFromPotentialChauffeur();
handleConfirmFromPotentialChauffeur();
handleInformAboutChauffeur();
if (deleted) {
sendPassengerStatistic();
driverAgent.doDelete();
}
}
} | False |
772 | 24453_2 | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat de database leeg maken en een message daarin toevoegen
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| IsmatFaizi/studeren-examen | Spring-Redis/src/main/java/edu/ap/spring/RedisApplication.java | 524 | //Deze gaat de database leeg maken en een message daarin toevoegen | line_comment | nl | package edu.ap.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import edu.ap.spring.controller.RedisController;
import edu.ap.spring.redis.RedisService;
@SpringBootApplication
public class RedisApplication {
private String CHANNEL = "edu:ap:redis";
@Autowired
private RedisService service;
//Subscript op channel
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new ChannelTopic(CHANNEL));
return container;
}
//Deze luistert op channel en wanneer er een message komt stuur die deze onMessage functie van Controller
@Bean
MessageListenerAdapter listenerAdapter(RedisController controller) {
return new MessageListenerAdapter(controller, "onMessage");
}
//Deze gaat<SUF>
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return (args) -> {
// empty db
this.service.flushDb();
// messaging
service.sendMessage(CHANNEL, "Hello from Spring Boot");
};
}
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}
| True |
2,605 | 171856_2 | /*
* Copyright 2014 http://Bither.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.util;
import android.os.Handler;
import com.google.bitcoin.store.WalletProtobufSerializer;
import net.bither.bitherj.core.Address;
import net.bither.bitherj.core.BitherjSettings;
import net.bither.bitherj.crypto.ECKey;
import net.bither.bitherj.utils.PrivateKeyUtil;
import net.bither.bitherj.utils.Utils;
import net.bither.preference.AppSharedPreference;
import net.bither.runnable.BaseRunnable;
import net.bither.runnable.HandlerMessage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class UpgradeUtil {
// old watch only dir
private static final String WALLET_WATCH_ONLY_OLD = "w";
public static final int BITHERJ_VERSION_CODE = 9;
private static final String WALLET_SEQUENCE_WATCH_ONLY = "sequence_watch_only";
private static final String WALLET_SEQUENCE_PRIVATE = "sequence_private";
private static final String WALLET_ROM_CACHE = "wallet";
private static final String WALLET_WATCH_ONLY = "watch";
private static final String WALLET_HOT = "hot";
private static final String WALLET_COLD = "cold";
private static final String WALLET_ERROR = "error";
private UpgradeUtil() {
}
public static boolean needUpgrade() {
int verionCode = AppSharedPreference.getInstance().getVerionCode();
return verionCode < BITHERJ_VERSION_CODE && verionCode > 0 || getOldWatchOnlyCacheDir().exists();
}
public static void upgradeNewVerion(Handler handler) {
BaseRunnable baseRunnable = new BaseRunnable() {
@Override
public void run() {
obtainMessage(HandlerMessage.MSG_PREPARE);
try {
long beginTime = System.currentTimeMillis();
if (getOldWatchOnlyCacheDir().exists()) {
upgradeV4();
upgradeToBitherj();
}
int verionCode = AppSharedPreference.getInstance().getVerionCode();
if (verionCode < BITHERJ_VERSION_CODE && verionCode > 0) {
upgradeToBitherj();
}
long nowTime = System.currentTimeMillis();
if (nowTime - beginTime < 2000) {
Thread.sleep(2000 - (nowTime - beginTime));
}
obtainMessage(HandlerMessage.MSG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
obtainMessage(HandlerMessage.MSG_FAILURE);
}
}
};
baseRunnable.setHandler(handler);
new Thread(baseRunnable).start();
}
//upgrde when version code <9
private static void upgradeToBitherj() throws Exception {
List<ECKey> ecKeyPrivates = initPrivateWallet(readPrivateAddressSequence());
List<ECKey> ecKeysWatchOnly = initWatchOnlyWallet(readWatchOnlyAddressSequence());
List<Address> privateAddressList = new ArrayList<Address>();
List<Address> watchOnlyAddressList = new ArrayList<Address>();
for (int i = 0; i < ecKeyPrivates.size(); i++) {
ECKey ecKey = ecKeyPrivates.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), PrivateKeyUtil.getPrivateKeyString(ecKey), false);
privateAddressList.add(address);
}
if (privateAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, privateAddressList);
}
for (int i = 0; i < ecKeysWatchOnly.size(); i++) {
ECKey ecKey = ecKeysWatchOnly.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), null, false);
watchOnlyAddressList.add(address);
}
if (watchOnlyAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, watchOnlyAddressList);
}
}
private static void upgradeV4() {
AppSharedPreference.getInstance().clear();
File walletFile = UpgradeUtil.getOldWatchOnlyCacheDir();
FileUtil.delFolder(walletFile.getAbsolutePath());
File watchOnlyAddressSequenceFile = getWatchOnlyAddressSequenceFile();
if (watchOnlyAddressSequenceFile.exists()) {
watchOnlyAddressSequenceFile.delete();
}
//upgrade
// File blockFile = FileUtil.getBlockChainFile();
// if (blockFile.exists()) {
// blockFile.delete();
// }
File errorFolder = getWatchErrorDir();
FileUtil.delFolder(errorFolder.getAbsolutePath());
}
public static File getOldWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY_OLD);
return file;
}
private static List<ECKey> initPrivateWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getPrivateCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
private static List<ECKey> initWatchOnlyWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getWatchOnlyCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
public static File getPrivateCacheDir() {
File file = Utils.getWalletRomCache();
String dirName = WALLET_HOT;
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
dirName = WALLET_COLD;
}
file = new File(file, dirName);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchErrorDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_ERROR);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private static File[] sortAddressFile(File[] fs, final List<String> sequence) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = sequence.indexOf(f1.getName())
- sequence.indexOf(f2.getName());
if (diff > 0) {
return 1;
} else if (diff == 0) {
return 0;
} else {
return -1;
}
}
});
return fs;
}
private static ECKey loadECKey(File walletFile) throws Exception {
FileInputStream walletStream = null;
walletStream = new FileInputStream(walletFile);
ECKey ecKey = new
WalletProtobufSerializer()
.readWallet(walletStream);
return ecKey;
}
public static File getWarmPrivateAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_PRIVATE);
return file;
}
public static File getWatchOnlyAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_WATCH_ONLY);
return file;
}
private static List<String> readPrivateAddressSequence() {
File file = getWarmPrivateAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
private static List<String> readWatchOnlyAddressSequence() {
File file = getWatchOnlyAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
}
| dworznik/bither-android | bither-android/src/net/bither/util/UpgradeUtil.java | 2,635 | //upgrde when version code <9 | line_comment | nl | /*
* Copyright 2014 http://Bither.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.bither.util;
import android.os.Handler;
import com.google.bitcoin.store.WalletProtobufSerializer;
import net.bither.bitherj.core.Address;
import net.bither.bitherj.core.BitherjSettings;
import net.bither.bitherj.crypto.ECKey;
import net.bither.bitherj.utils.PrivateKeyUtil;
import net.bither.bitherj.utils.Utils;
import net.bither.preference.AppSharedPreference;
import net.bither.runnable.BaseRunnable;
import net.bither.runnable.HandlerMessage;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class UpgradeUtil {
// old watch only dir
private static final String WALLET_WATCH_ONLY_OLD = "w";
public static final int BITHERJ_VERSION_CODE = 9;
private static final String WALLET_SEQUENCE_WATCH_ONLY = "sequence_watch_only";
private static final String WALLET_SEQUENCE_PRIVATE = "sequence_private";
private static final String WALLET_ROM_CACHE = "wallet";
private static final String WALLET_WATCH_ONLY = "watch";
private static final String WALLET_HOT = "hot";
private static final String WALLET_COLD = "cold";
private static final String WALLET_ERROR = "error";
private UpgradeUtil() {
}
public static boolean needUpgrade() {
int verionCode = AppSharedPreference.getInstance().getVerionCode();
return verionCode < BITHERJ_VERSION_CODE && verionCode > 0 || getOldWatchOnlyCacheDir().exists();
}
public static void upgradeNewVerion(Handler handler) {
BaseRunnable baseRunnable = new BaseRunnable() {
@Override
public void run() {
obtainMessage(HandlerMessage.MSG_PREPARE);
try {
long beginTime = System.currentTimeMillis();
if (getOldWatchOnlyCacheDir().exists()) {
upgradeV4();
upgradeToBitherj();
}
int verionCode = AppSharedPreference.getInstance().getVerionCode();
if (verionCode < BITHERJ_VERSION_CODE && verionCode > 0) {
upgradeToBitherj();
}
long nowTime = System.currentTimeMillis();
if (nowTime - beginTime < 2000) {
Thread.sleep(2000 - (nowTime - beginTime));
}
obtainMessage(HandlerMessage.MSG_SUCCESS);
} catch (Exception e) {
e.printStackTrace();
obtainMessage(HandlerMessage.MSG_FAILURE);
}
}
};
baseRunnable.setHandler(handler);
new Thread(baseRunnable).start();
}
//upgrde when<SUF>
private static void upgradeToBitherj() throws Exception {
List<ECKey> ecKeyPrivates = initPrivateWallet(readPrivateAddressSequence());
List<ECKey> ecKeysWatchOnly = initWatchOnlyWallet(readWatchOnlyAddressSequence());
List<Address> privateAddressList = new ArrayList<Address>();
List<Address> watchOnlyAddressList = new ArrayList<Address>();
for (int i = 0; i < ecKeyPrivates.size(); i++) {
ECKey ecKey = ecKeyPrivates.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), PrivateKeyUtil.getPrivateKeyString(ecKey), false);
privateAddressList.add(address);
}
if (privateAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, privateAddressList);
}
for (int i = 0; i < ecKeysWatchOnly.size(); i++) {
ECKey ecKey = ecKeysWatchOnly.get(i);
Address address = new Address(ecKey.toAddress(), ecKey.getPubKey(), null, false);
watchOnlyAddressList.add(address);
}
if (watchOnlyAddressList.size() > 0) {
KeyUtil.addAddressListByDesc(null, watchOnlyAddressList);
}
}
private static void upgradeV4() {
AppSharedPreference.getInstance().clear();
File walletFile = UpgradeUtil.getOldWatchOnlyCacheDir();
FileUtil.delFolder(walletFile.getAbsolutePath());
File watchOnlyAddressSequenceFile = getWatchOnlyAddressSequenceFile();
if (watchOnlyAddressSequenceFile.exists()) {
watchOnlyAddressSequenceFile.delete();
}
//upgrade
// File blockFile = FileUtil.getBlockChainFile();
// if (blockFile.exists()) {
// blockFile.delete();
// }
File errorFolder = getWatchErrorDir();
FileUtil.delFolder(errorFolder.getAbsolutePath());
}
public static File getOldWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY_OLD);
return file;
}
private static List<ECKey> initPrivateWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getPrivateCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
private static List<ECKey> initWatchOnlyWallet(
List<String> sequence) throws Exception {
List<ECKey> result = new ArrayList<ECKey>();
File dir = getWatchOnlyCacheDir();
File[] fs = dir.listFiles();
if (sequence != null) {
fs = sortAddressFile(fs, sequence);
}
for (File walletFile : fs) {
String name = walletFile.getName();
if (sequence.contains(name)) {
ECKey ecKey = loadECKey(walletFile);
result.add(ecKey);
}
}
return result;
}
public static File getPrivateCacheDir() {
File file = Utils.getWalletRomCache();
String dirName = WALLET_HOT;
if (AppSharedPreference.getInstance().getAppMode() == BitherjSettings.AppMode.COLD) {
dirName = WALLET_COLD;
}
file = new File(file, dirName);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchOnlyCacheDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_WATCH_ONLY);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
public static File getWatchErrorDir() {
File file = Utils.getWalletRomCache();
file = new File(file, WALLET_ERROR);
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private static File[] sortAddressFile(File[] fs, final List<String> sequence) {
Arrays.sort(fs, new Comparator<File>() {
public int compare(File f1, File f2) {
long diff = sequence.indexOf(f1.getName())
- sequence.indexOf(f2.getName());
if (diff > 0) {
return 1;
} else if (diff == 0) {
return 0;
} else {
return -1;
}
}
});
return fs;
}
private static ECKey loadECKey(File walletFile) throws Exception {
FileInputStream walletStream = null;
walletStream = new FileInputStream(walletFile);
ECKey ecKey = new
WalletProtobufSerializer()
.readWallet(walletStream);
return ecKey;
}
public static File getWarmPrivateAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_PRIVATE);
return file;
}
public static File getWatchOnlyAddressSequenceFile() {
File dir = Utils.getWalletRomCache();
File file = new File(dir, WALLET_SEQUENCE_WATCH_ONLY);
return file;
}
private static List<String> readPrivateAddressSequence() {
File file = getWarmPrivateAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
private static List<String> readWatchOnlyAddressSequence() {
File file = getWatchOnlyAddressSequenceFile();
if (file.exists()) {
ArrayList<String> addresses = (ArrayList<String>) FileUtil
.deserialize(file);
return addresses;
} else {
return null;
}
}
}
| False |
2,996 | 60681_1 | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties die de speler uit kan voeren
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | hogeschoolnovi/tic-tac-toe-Quinten-dev | src/novi/basics/Player.java | 201 | //methoden: acties die de speler uit kan voeren | line_comment | nl | package novi.basics;
public class Player {
//attributen: informatie verzamelen
private String name;
private char token;
private int score;
//methoden: acties<SUF>
//constructor
public Player(String name, char token) {
this.name = name;
this.token = token;
score = 0;
}
//get methoden
public String getName() {
return name;
}
public char getToken() {
return token;
}
public int getScore() {
return score;
}
//set methoden
/*public void setScore(int score) {
this.score = score;
}*/
public void addScore() {
score++;
}
} | True |
2,618 | 100813_17 | /**
** Person.java
**
** Copyright 2011 by Sarah Wise, Mark Coletti, Andrew Crooks, and
** George Mason University.
**
** Licensed under the Academic Free License version 3.0
**
** See the file "LICENSE" for more information
**
** $Id$
**/
package sim.app.geo.schellingpolygon;
import java.util.ArrayList;
import sim.engine.SimState;
import sim.engine.Steppable;
public class Person implements Steppable
{
String color;
double preference;
Polygon region;
double personalThreshold = .5;
int numMoves = 0;
/**
* Constructor function
* @param c
*/
public Person(String c)
{
color = c;
}
/**
* Moves the Person to the given Polygon
* @param p - the Polygon to which the Person should move
*/
public void updateLocation(Polygon p)
{
// leave old tile, if previously was on a tile
if (region != null)
{
region.residents.remove(this);
region.soc = "UNOCCUPIED";
}
// go to new tile
region = p;
region.residents.add(this);
region.soc = color;
numMoves++; // increment the number of times moved
}
/**
*
* @param poly the proposed location
* @return whether the given Polygon is an acceptable location for the Person,
* based on the Person's personalThreshold
*/
boolean acceptable(Polygon poly)
{
// decide if Person is unhappy with surroundings
double unlike = 0, total = 0.;
for (Polygon p : poly.neighbors)
{
if (p.soc.equals("UNOCCUPIED")) // empty spaces don't count
{
continue;
}
if (!p.soc.equals(color)) // is this neighbor an unlike neighbor?
{
unlike++;
}
total++; // total count of neighbors
}
double percentUnlike = unlike / Math.max(total, 1); // don't divide by 0!
// if unhappy, return false
if (percentUnlike >= personalThreshold)
{
return false;
} else // if happy, return true
{
return true;
}
}
/**
* @param ps the list of Polygons open to the Person
* @return the closest available Polygon that meets the Person's needs, if such
* a Polygon exists. If no such Polygon exists, returns null.
*/
Polygon bestMove(ArrayList<Polygon> ps)
{
Polygon result = null;
double bestDist = Double.MAX_VALUE;
// go through all polygons and determine the best move to make
for (Polygon p : ps)
{
if (!p.soc.equals("UNOCCUPIED"))
{
continue; // not available
} else if (p.geometry.getCentroid().distance(
region.geometry.getCentroid()) >= bestDist) // distance between centroids
//else if( p.geometry.distance( region.geometry ) >= bestDist)
// distance between region borders
{
continue; // we already have a better option
} else if (!acceptable(p))
{
continue; // not an acceptable neighborhood
} else
{ // otherwise it's an acceptable region and the closest region yet
result = p;
bestDist = p.geometry.distance(region.geometry);
}
}
return result;
}
/**
* Determines whether the Person's current location is acceptable. If not, attempts
* to move the Person to a better location.
*/
@Override
public void step(SimState state)
{
if (!acceptable(region))
{ // the current location is unacceptable
// System.out.println("unacceptable!");
// try to find and move to a better location
Polygon potentialNew = bestMove(((PolySchelling) state).polys);
if (potentialNew != null) // a better location was found
{
updateLocation(potentialNew);
} else // no better location was found. Stay in place.
{
// System.out.println("...but immobile");
}
}
}
}
| eclab/mason | contrib/geomason/src/main/java/sim/app/geo/schellingpolygon/Person.java | 1,161 | //else if( p.geometry.distance( region.geometry ) >= bestDist) | line_comment | nl | /**
** Person.java
**
** Copyright 2011 by Sarah Wise, Mark Coletti, Andrew Crooks, and
** George Mason University.
**
** Licensed under the Academic Free License version 3.0
**
** See the file "LICENSE" for more information
**
** $Id$
**/
package sim.app.geo.schellingpolygon;
import java.util.ArrayList;
import sim.engine.SimState;
import sim.engine.Steppable;
public class Person implements Steppable
{
String color;
double preference;
Polygon region;
double personalThreshold = .5;
int numMoves = 0;
/**
* Constructor function
* @param c
*/
public Person(String c)
{
color = c;
}
/**
* Moves the Person to the given Polygon
* @param p - the Polygon to which the Person should move
*/
public void updateLocation(Polygon p)
{
// leave old tile, if previously was on a tile
if (region != null)
{
region.residents.remove(this);
region.soc = "UNOCCUPIED";
}
// go to new tile
region = p;
region.residents.add(this);
region.soc = color;
numMoves++; // increment the number of times moved
}
/**
*
* @param poly the proposed location
* @return whether the given Polygon is an acceptable location for the Person,
* based on the Person's personalThreshold
*/
boolean acceptable(Polygon poly)
{
// decide if Person is unhappy with surroundings
double unlike = 0, total = 0.;
for (Polygon p : poly.neighbors)
{
if (p.soc.equals("UNOCCUPIED")) // empty spaces don't count
{
continue;
}
if (!p.soc.equals(color)) // is this neighbor an unlike neighbor?
{
unlike++;
}
total++; // total count of neighbors
}
double percentUnlike = unlike / Math.max(total, 1); // don't divide by 0!
// if unhappy, return false
if (percentUnlike >= personalThreshold)
{
return false;
} else // if happy, return true
{
return true;
}
}
/**
* @param ps the list of Polygons open to the Person
* @return the closest available Polygon that meets the Person's needs, if such
* a Polygon exists. If no such Polygon exists, returns null.
*/
Polygon bestMove(ArrayList<Polygon> ps)
{
Polygon result = null;
double bestDist = Double.MAX_VALUE;
// go through all polygons and determine the best move to make
for (Polygon p : ps)
{
if (!p.soc.equals("UNOCCUPIED"))
{
continue; // not available
} else if (p.geometry.getCentroid().distance(
region.geometry.getCentroid()) >= bestDist) // distance between centroids
//else if(<SUF>
// distance between region borders
{
continue; // we already have a better option
} else if (!acceptable(p))
{
continue; // not an acceptable neighborhood
} else
{ // otherwise it's an acceptable region and the closest region yet
result = p;
bestDist = p.geometry.distance(region.geometry);
}
}
return result;
}
/**
* Determines whether the Person's current location is acceptable. If not, attempts
* to move the Person to a better location.
*/
@Override
public void step(SimState state)
{
if (!acceptable(region))
{ // the current location is unacceptable
// System.out.println("unacceptable!");
// try to find and move to a better location
Polygon potentialNew = bestMove(((PolySchelling) state).polys);
if (potentialNew != null) // a better location was found
{
updateLocation(potentialNew);
} else // no better location was found. Stay in place.
{
// System.out.println("...but immobile");
}
}
}
}
| False |
4,202 | 116167_2 | /*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <fredrik@dolda2000.com>, and
* Björn Johannessen <johannessen.bjorn@gmail.com>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ender.CurioInfo;
public class Item extends Widget implements DTarget {
static Coord shoff = new Coord(1, 3);
static final Pattern patt = Pattern.compile("quality (\\d+) ", Pattern.CASE_INSENSITIVE);
static Map<Integer, Tex> qmap;
static Resource missing = Resource.load("gfx/invobjs/missing");
static Color outcol = new Color(0, 0, 0, 255);
static Color clrWater = new Color(24, 116, 205);
static Color clrWine = new Color(139, 71, 137);
static Color clrHoney = new Color(238, 173, 14);
boolean dm = false;
public int q, q2;
boolean hq;
Coord doff;
public String tooltip;
int num = -1;
Indir<Resource> res;
Tex sh;
public Color olcol = null;
Tex mask = null;
int meter = 0;
String curioStr = null;
public static int idCounter = 0; // new
public int id = 0; // new
static {
Widget.addtype("item", new WidgetFactory() {
public Widget create(Coord c, Widget parent, Object[] args) {
int res = (Integer) args[0];
int q = (Integer) args[1];
int num = -1;
String tooltip = null;
int ca = 3;
Coord drag = null;
if ((Integer) args[2] != 0)
drag = (Coord) args[ca++];
if (args.length > ca)
tooltip = (String) args[ca++];
if ((tooltip != null) && tooltip.equals(""))
tooltip = null;
if (args.length > ca)
num = (Integer) args[ca++];
Item item = new Item(c, res, q, parent, drag, num);
item.settip(tooltip);
return (item);
}
});
missing.loadwait();
qmap = new HashMap<Integer, Tex>();
}
public void settip(String t) {
tooltip = t;
q2 = -1;
if (tooltip != null) {
try {
Matcher m = patt.matcher(tooltip);
while (m.find()) {
q2 = Integer.parseInt(m.group(1));
}
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
calcFEP();
calcCurio();
shorttip = longtip = null;
}
private void fixsize() {
if (res.get() != null) {
Tex tex = res.get().layer(Resource.imgc).tex();
sz = tex.sz().add(shoff);
} else {
sz = new Coord(30, 30);
}
}
public void draw(GOut g) {
final Resource ttres;
if (res.get() == null) {
sh = null;
sz = new Coord(30, 30);
g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz);
ttres = missing;
} else {
Tex tex = res.get().layer(Resource.imgc).tex();
fixsize();
if (dm) {
g.chcolor(255, 255, 255, 128);
g.image(tex, Coord.z);
g.chcolor();
} else {
if(res.get().basename().equals("silkmoth") && tooltip != null && tooltip.contains("Female"))
g.chcolor(255, 124, 195, 255);
g.image(tex, Coord.z);
g.chcolor();
}
if (num >= 0) {
// g.chcolor(Color.WHITE);
// g.atext(Integer.toString(num), new Coord(0, 30), 0, 1);
g.aimage(getqtex(num), Coord.z, 0, 0);
}
if (meter > 0) {
double a = ((double) meter) / 100.0;
int r = (int) ((1 - a) * 255);
int gr = (int) (a * 255);
int b = 0;
g.chcolor(r, gr, b, 255);
// g.fellipse(sz.div(2), new Coord(15, 15), 90, (int)(90 + (360
// * a)));
g.frect(new Coord(sz.x - 5, (int) ((1 - a) * sz.y)), new Coord(5, (int) (a * sz.y)));
g.chcolor();
}
int tq = (q2 > 0) ? q2 : q;
if (Config.showq && (tq > 0)) {
tex = getqtex(tq);
g.aimage(tex, sz.sub(1, 1), 1, 1);
}
ttres = res.get();
}
if (olcol != null) {
Tex bg = ttres.layer(Resource.imgc).tex();
if ((mask == null) && (bg instanceof TexI)) {
mask = ((TexI) bg).mkmask();
}
if (mask != null) {
g.chcolor(olcol);
g.image(mask, Coord.z);
g.chcolor();
}
}
if (FEP == null) {
calcFEP();
}
if (curioStr == null) {
calcCurio();
}
if (ttres.name.lastIndexOf("waterflask") > 0) {
drawBar(g, 2, clrWater, 3);
} else if (ttres.name.lastIndexOf("glass-winef") > 0) {
drawBar(g, 0.2, clrWine, 3);
} else if (ttres.name.lastIndexOf("bottle-winef") > 0) {
drawBar(g, 0.6, clrWine, 3);
} else if (ttres.name.lastIndexOf("bottle-wine-weißbier") > 0) {
drawBar(g, 0.6, clrWine, 3);
} else if (ttres.name.lastIndexOf("tankardf") > 0) {
drawBar(g, 0.4, clrWine, 3);
} else if (ttres.name.lastIndexOf("waterskin") > 0) {
drawBar(g, 3, clrWater, 3);
} else if (ttres.name.lastIndexOf("bucket-") > 0 || ttres.name.lastIndexOf("waterflask-") > 0) {
Color clr;
if (ttres.name.lastIndexOf("water") > 0)
clr = clrWater;
else if (ttres.name.lastIndexOf("wine") > 0 || ttres.name.lastIndexOf("vinegar") > 0)
clr = clrWine;
else if (ttres.name.lastIndexOf("honey") > 0)
clr = clrHoney;
else
clr = Color.LIGHT_GRAY;
drawBar(g, 10, clr, 9);
}
}
private void drawBar(GOut g, double capacity, Color clr, int width) {
try {
String valStr = tooltip.substring(tooltip.indexOf('(') + 1, tooltip.indexOf('/'));
double val = Double.parseDouble(valStr);
int h = (int) (val / capacity * sz.y);
g.chcolor(clr);
int barH = h - shoff.y;
g.frect(new Coord(0, sz.y - h), new Coord(width, barH < 0 ? 0 : barH));
g.chcolor();
} catch (Exception e) {
} // fail silently.
}
static Tex getqtex(int q) {
synchronized (qmap) {
if (qmap.containsKey(q)) {
return qmap.get(q);
} else {
BufferedImage img = Text.render(Integer.toString(q)).img;
img = Utils.outline2(img, outcol, true);
Tex tex = new TexI(img);
qmap.put(q, tex);
return tex;
}
}
}
static Tex makesh(Resource res) {
BufferedImage img = res.layer(Resource.imgc).img;
Coord sz = Utils.imgsz(img);
BufferedImage sh = new BufferedImage(sz.x, sz.y, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < sz.y; y++) {
for (int x = 0; x < sz.x; x++) {
long c = img.getRGB(x, y) & 0x00000000ffffffffL;
int a = (int) ((c & 0xff000000) >> 24);
sh.setRGB(x, y, (a / 2) << 24);
}
}
return (new TexI(sh));
}
public String name() {
Resource res = this.res.get();
if (res != null) {
if (res.layer(Resource.tooltip) != null) {
return res.layer(Resource.tooltip).t;
} else {
return (this.tooltip);
}
}
return null;
}
public String shorttip() {
if (this.tooltip != null)
return (this.tooltip);
Resource res = this.res.get();
if ((res != null) && (res.layer(Resource.tooltip) != null)) {
String tt = res.layer(Resource.tooltip).t;
if (tt != null) {
if (q > 0) {
tt = tt + ", quality " + q;
if (hq)
tt = tt + "+";
}
return (tt);
}
}
return (null);
}
long hoverstart;
Text shorttip = null, longtip = null;
public double qmult;
private String FEP = null;
public Object tooltip(Coord c, boolean again) {
long now = System.currentTimeMillis();
if (!again)
hoverstart = now;
Resource res = this.res.get();
Resource.Pagina pg = (res != null) ? res.layer(Resource.pagina) : null;
if (((now - hoverstart) < 500) || (pg == null)) {
if (shorttip == null) {
String tt = shorttip();
if (tt != null) {
tt = RichText.Parser.quote(tt);
if (meter > 0) {
tt = tt + " (" + meter + "%)";
}
if (FEP != null) {
tt += FEP;
}
if (curioStr != null) {
tt += curioStr;
}
shorttip = RichText.render(tt, 200);
}
}
return (shorttip);
} else {
if ((longtip == null) && (res != null)) {
String tip = shorttip();
if (tip == null)
return (null);
String tt = RichText.Parser.quote(tip);
if (meter > 0) {
tt = tt + " (" + meter + "%)";
}
if (FEP != null) {
tt += FEP;
}
if (curioStr != null) {
tt += curioStr;
}
if (pg != null)
tt += "\n\n" + pg.text;
longtip = RichText.render(tt, 200);
}
return (longtip);
}
}
private void resettt() {
shorttip = null;
longtip = null;
}
private void decq(int q) {
if (q < 0) {
this.q = q;
hq = false;
} else {
int fl = (q & 0xff000000) >> 24;
this.q = (q & 0xffffff);
hq = ((fl & 1) != 0);
}
}
public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag, int num) {
super(c, Coord.z, parent);
this.res = res;
idCounter++; // new
id = idCounter; // new
decq(q);
fixsize();
this.num = num;
if (drag == null) {
dm = false;
} else {
dm = true;
doff = drag;
ui.grabmouse(this);
this.c = ui.mc.add(doff.inv());
}
qmult = Math.sqrt((float) q / 10);
calcFEP();
calcCurio();
}
private void calcFEP() {
Map<String, Float> fep;
String name = name();
if (name == null) {
return;
}
if (name.equals("Ring of Brodgar")) {
if (res.get().name.equals("gfx/invobjs/bread-brodgar")) {
name = "Ring of Brodgar (Baking)";
}
if (res.get().name.equals("gfx/invobjs/feast-rob")) {
name = "Ring of Brodgar (Seafood)";
}
}
name = name.toLowerCase();
boolean isItem = false;
if ((fep = Config.FEPMap.get(name)) != null) {
if (fep.containsKey("isItem")) {
isItem = true;
}
FEP = "\n";
for (String key : fep.keySet()) {
float val = (float) (fep.get(key) * qmult);
if (key.equals("isItem")) {
continue;
}
if (isItem) {
val = (float) Math.floor(val);
FEP += String.format("%s:%.0f ", key, val);
} else {
FEP += String.format("%s:%.1f ", key, val);
}
}
shorttip = longtip = null;
}
}
public int getLP() {
String name = name();
if (name == null) {
return 0;
}
name = name.toLowerCase();
CurioInfo curio;
if ((curio = Config.curios.get(name)) != null) {
return (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100);
}
return 0;
}
private void calcCurio() {
String name = name();
if (name == null) {
return;
}
name = name.toLowerCase();
CurioInfo curio;
if ((curio = Config.curios.get(name)) != null) {
int LP = (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100);
int time = curio.time * (100 - meter) / 100;
int h = time / 60;
int m = time % 60;
curioStr = String.format("\nLP: %d, Weight: %d\nStudy time: %dh %2dm", LP, curio.weight, h, m);
shorttip = longtip = null;
}
}
public Item(Coord c, int res, int q, Widget parent, Coord drag, int num) {
this(c, parent.ui.sess.getres(res), q, parent, drag, num);
}
public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag) {
this(c, res, q, parent, drag, -1);
}
public Item(Coord c, int res, int q, Widget parent, Coord drag) {
this(c, parent.ui.sess.getres(res), q, parent, drag);
}
public boolean dropon(Widget w, Coord c) {
for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) {
if (wdg == this)
continue;
Coord cc = w.xlate(wdg.c, true);
if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) {
if (dropon(wdg, c.add(cc.inv())))
return (true);
}
}
if (w instanceof DTarget) {
if (((DTarget) w).drop(c, c.add(doff.inv())))
return (true);
}
if (w instanceof DTarget2) {
if (((DTarget2) w).drop(c, c.add(doff.inv()), this))
return (true);
}
return (false);
}
public boolean interact(Widget w, Coord c) {
for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) {
if (wdg == this)
continue;
Coord cc = w.xlate(wdg.c, true);
if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) {
if (interact(wdg, c.add(cc.inv())))
return (true);
}
}
if (w instanceof DTarget) {
if (((DTarget) w).iteminteract(c, c.add(doff.inv())))
return (true);
}
return (false);
}
public void chres(Indir<Resource> res, int q) {
this.res = res;
sh = null;
decq(q);
}
public void uimsg(String name, Object... args) {
if (name == "num") {
num = (Integer) args[0];
} else if (name == "chres") {
chres(ui.sess.getres((Integer) args[0]), (Integer) args[1]);
resettt();
} else if (name == "color") {
olcol = (Color) args[0];
} else if (name == "tt") {
if ((args.length > 0) && (((String) args[0]).length() > 0))
settip((String) args[0]);
else
settip(null);
resettt();
} else if (name == "meter") {
meter = (Integer) args[0];
shorttip = null;
longtip = null;
calcCurio();
}
}
public String GetResName() { // new
if (this.res.get() != null) {
return ((Resource) this.res.get()).name;
}
return "";
}
void sortedSkoop() { // new
String name = GetResName();
if (parent instanceof Inventory)
((Inventory) parent).skoopItems(name);
}
public boolean mousedown(Coord c, int button) {
if (button == 3 && ui.modflags() == 4) { // new
sortedSkoop();
return (true);
}
if (!dm) {
if (button == 1) {
if (ui.modshift)
if (ui.modmeta)
wdgmsg("transfer-same", name(), false);
else
wdgmsg("transfer", c);
else if (ui.modctrl)
if (ui.modmeta)
wdgmsg("drop-same", name(), false);
else
wdgmsg("drop", c);
else
wdgmsg("take", c);
return (true);
} else if (button == 3) {
if (ui.modmeta) {
if (ui.modshift) {
wdgmsg("transfer-same", name(), true);
} else if (ui.modctrl) {
wdgmsg("drop-same", name(), true);
}
} else {
wdgmsg("iact", c);
}
return (true);
}
} else {
if (button == 1) {
dropon(parent, c.add(this.c));
} else if (button == 3) {
interact(parent, c.add(this.c));
}
return (true);
}
return (false);
}
public void mousemove(Coord c) {
if (dm)
this.c = this.c.add(c.add(doff.inv()));
}
public boolean drop(Coord cc, Coord ul) {
return (false);
}
public boolean iteminteract(Coord cc, Coord ul) {
wdgmsg("itemact", ui.modflags());
return (true);
}
public ItemType getItemType(Item itm) {
String resname = itm.res.get().name;
int idx = resname.lastIndexOf("/");
resname = resname.substring(idx + 1);
if (!Config.itemTypes.containsKey(resname))
return ItemType.NOT_IMPLEMENTED;
return Config.itemTypes.get(resname);
}
}
| romovs/anemone | src/haven/Item.java | 6,235 | // g.fellipse(sz.div(2), new Coord(15, 15), 90, (int)(90 + (360 | line_comment | nl | /*
* This file is part of the Haven & Hearth game client.
* Copyright (C) 2009 Fredrik Tolf <fredrik@dolda2000.com>, and
* Björn Johannessen <johannessen.bjorn@gmail.com>
*
* Redistribution and/or modification of this file is subject to the
* terms of the GNU Lesser General Public License, version 3, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* Other parts of this source tree adhere to other copying
* rights. Please see the file `COPYING' in the root directory of the
* source tree for details.
*
* A copy the GNU Lesser General Public License is distributed along
* with the source tree of which this file is a part in the file
* `doc/LPGL-3'. If it is missing for any reason, please see the Free
* Software Foundation's website at <http://www.fsf.org/>, or write
* to the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package haven;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import ender.CurioInfo;
public class Item extends Widget implements DTarget {
static Coord shoff = new Coord(1, 3);
static final Pattern patt = Pattern.compile("quality (\\d+) ", Pattern.CASE_INSENSITIVE);
static Map<Integer, Tex> qmap;
static Resource missing = Resource.load("gfx/invobjs/missing");
static Color outcol = new Color(0, 0, 0, 255);
static Color clrWater = new Color(24, 116, 205);
static Color clrWine = new Color(139, 71, 137);
static Color clrHoney = new Color(238, 173, 14);
boolean dm = false;
public int q, q2;
boolean hq;
Coord doff;
public String tooltip;
int num = -1;
Indir<Resource> res;
Tex sh;
public Color olcol = null;
Tex mask = null;
int meter = 0;
String curioStr = null;
public static int idCounter = 0; // new
public int id = 0; // new
static {
Widget.addtype("item", new WidgetFactory() {
public Widget create(Coord c, Widget parent, Object[] args) {
int res = (Integer) args[0];
int q = (Integer) args[1];
int num = -1;
String tooltip = null;
int ca = 3;
Coord drag = null;
if ((Integer) args[2] != 0)
drag = (Coord) args[ca++];
if (args.length > ca)
tooltip = (String) args[ca++];
if ((tooltip != null) && tooltip.equals(""))
tooltip = null;
if (args.length > ca)
num = (Integer) args[ca++];
Item item = new Item(c, res, q, parent, drag, num);
item.settip(tooltip);
return (item);
}
});
missing.loadwait();
qmap = new HashMap<Integer, Tex>();
}
public void settip(String t) {
tooltip = t;
q2 = -1;
if (tooltip != null) {
try {
Matcher m = patt.matcher(tooltip);
while (m.find()) {
q2 = Integer.parseInt(m.group(1));
}
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
}
calcFEP();
calcCurio();
shorttip = longtip = null;
}
private void fixsize() {
if (res.get() != null) {
Tex tex = res.get().layer(Resource.imgc).tex();
sz = tex.sz().add(shoff);
} else {
sz = new Coord(30, 30);
}
}
public void draw(GOut g) {
final Resource ttres;
if (res.get() == null) {
sh = null;
sz = new Coord(30, 30);
g.image(missing.layer(Resource.imgc).tex(), Coord.z, sz);
ttres = missing;
} else {
Tex tex = res.get().layer(Resource.imgc).tex();
fixsize();
if (dm) {
g.chcolor(255, 255, 255, 128);
g.image(tex, Coord.z);
g.chcolor();
} else {
if(res.get().basename().equals("silkmoth") && tooltip != null && tooltip.contains("Female"))
g.chcolor(255, 124, 195, 255);
g.image(tex, Coord.z);
g.chcolor();
}
if (num >= 0) {
// g.chcolor(Color.WHITE);
// g.atext(Integer.toString(num), new Coord(0, 30), 0, 1);
g.aimage(getqtex(num), Coord.z, 0, 0);
}
if (meter > 0) {
double a = ((double) meter) / 100.0;
int r = (int) ((1 - a) * 255);
int gr = (int) (a * 255);
int b = 0;
g.chcolor(r, gr, b, 255);
// g.fellipse(sz.div(2), new<SUF>
// * a)));
g.frect(new Coord(sz.x - 5, (int) ((1 - a) * sz.y)), new Coord(5, (int) (a * sz.y)));
g.chcolor();
}
int tq = (q2 > 0) ? q2 : q;
if (Config.showq && (tq > 0)) {
tex = getqtex(tq);
g.aimage(tex, sz.sub(1, 1), 1, 1);
}
ttres = res.get();
}
if (olcol != null) {
Tex bg = ttres.layer(Resource.imgc).tex();
if ((mask == null) && (bg instanceof TexI)) {
mask = ((TexI) bg).mkmask();
}
if (mask != null) {
g.chcolor(olcol);
g.image(mask, Coord.z);
g.chcolor();
}
}
if (FEP == null) {
calcFEP();
}
if (curioStr == null) {
calcCurio();
}
if (ttres.name.lastIndexOf("waterflask") > 0) {
drawBar(g, 2, clrWater, 3);
} else if (ttres.name.lastIndexOf("glass-winef") > 0) {
drawBar(g, 0.2, clrWine, 3);
} else if (ttres.name.lastIndexOf("bottle-winef") > 0) {
drawBar(g, 0.6, clrWine, 3);
} else if (ttres.name.lastIndexOf("bottle-wine-weißbier") > 0) {
drawBar(g, 0.6, clrWine, 3);
} else if (ttres.name.lastIndexOf("tankardf") > 0) {
drawBar(g, 0.4, clrWine, 3);
} else if (ttres.name.lastIndexOf("waterskin") > 0) {
drawBar(g, 3, clrWater, 3);
} else if (ttres.name.lastIndexOf("bucket-") > 0 || ttres.name.lastIndexOf("waterflask-") > 0) {
Color clr;
if (ttres.name.lastIndexOf("water") > 0)
clr = clrWater;
else if (ttres.name.lastIndexOf("wine") > 0 || ttres.name.lastIndexOf("vinegar") > 0)
clr = clrWine;
else if (ttres.name.lastIndexOf("honey") > 0)
clr = clrHoney;
else
clr = Color.LIGHT_GRAY;
drawBar(g, 10, clr, 9);
}
}
private void drawBar(GOut g, double capacity, Color clr, int width) {
try {
String valStr = tooltip.substring(tooltip.indexOf('(') + 1, tooltip.indexOf('/'));
double val = Double.parseDouble(valStr);
int h = (int) (val / capacity * sz.y);
g.chcolor(clr);
int barH = h - shoff.y;
g.frect(new Coord(0, sz.y - h), new Coord(width, barH < 0 ? 0 : barH));
g.chcolor();
} catch (Exception e) {
} // fail silently.
}
static Tex getqtex(int q) {
synchronized (qmap) {
if (qmap.containsKey(q)) {
return qmap.get(q);
} else {
BufferedImage img = Text.render(Integer.toString(q)).img;
img = Utils.outline2(img, outcol, true);
Tex tex = new TexI(img);
qmap.put(q, tex);
return tex;
}
}
}
static Tex makesh(Resource res) {
BufferedImage img = res.layer(Resource.imgc).img;
Coord sz = Utils.imgsz(img);
BufferedImage sh = new BufferedImage(sz.x, sz.y, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < sz.y; y++) {
for (int x = 0; x < sz.x; x++) {
long c = img.getRGB(x, y) & 0x00000000ffffffffL;
int a = (int) ((c & 0xff000000) >> 24);
sh.setRGB(x, y, (a / 2) << 24);
}
}
return (new TexI(sh));
}
public String name() {
Resource res = this.res.get();
if (res != null) {
if (res.layer(Resource.tooltip) != null) {
return res.layer(Resource.tooltip).t;
} else {
return (this.tooltip);
}
}
return null;
}
public String shorttip() {
if (this.tooltip != null)
return (this.tooltip);
Resource res = this.res.get();
if ((res != null) && (res.layer(Resource.tooltip) != null)) {
String tt = res.layer(Resource.tooltip).t;
if (tt != null) {
if (q > 0) {
tt = tt + ", quality " + q;
if (hq)
tt = tt + "+";
}
return (tt);
}
}
return (null);
}
long hoverstart;
Text shorttip = null, longtip = null;
public double qmult;
private String FEP = null;
public Object tooltip(Coord c, boolean again) {
long now = System.currentTimeMillis();
if (!again)
hoverstart = now;
Resource res = this.res.get();
Resource.Pagina pg = (res != null) ? res.layer(Resource.pagina) : null;
if (((now - hoverstart) < 500) || (pg == null)) {
if (shorttip == null) {
String tt = shorttip();
if (tt != null) {
tt = RichText.Parser.quote(tt);
if (meter > 0) {
tt = tt + " (" + meter + "%)";
}
if (FEP != null) {
tt += FEP;
}
if (curioStr != null) {
tt += curioStr;
}
shorttip = RichText.render(tt, 200);
}
}
return (shorttip);
} else {
if ((longtip == null) && (res != null)) {
String tip = shorttip();
if (tip == null)
return (null);
String tt = RichText.Parser.quote(tip);
if (meter > 0) {
tt = tt + " (" + meter + "%)";
}
if (FEP != null) {
tt += FEP;
}
if (curioStr != null) {
tt += curioStr;
}
if (pg != null)
tt += "\n\n" + pg.text;
longtip = RichText.render(tt, 200);
}
return (longtip);
}
}
private void resettt() {
shorttip = null;
longtip = null;
}
private void decq(int q) {
if (q < 0) {
this.q = q;
hq = false;
} else {
int fl = (q & 0xff000000) >> 24;
this.q = (q & 0xffffff);
hq = ((fl & 1) != 0);
}
}
public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag, int num) {
super(c, Coord.z, parent);
this.res = res;
idCounter++; // new
id = idCounter; // new
decq(q);
fixsize();
this.num = num;
if (drag == null) {
dm = false;
} else {
dm = true;
doff = drag;
ui.grabmouse(this);
this.c = ui.mc.add(doff.inv());
}
qmult = Math.sqrt((float) q / 10);
calcFEP();
calcCurio();
}
private void calcFEP() {
Map<String, Float> fep;
String name = name();
if (name == null) {
return;
}
if (name.equals("Ring of Brodgar")) {
if (res.get().name.equals("gfx/invobjs/bread-brodgar")) {
name = "Ring of Brodgar (Baking)";
}
if (res.get().name.equals("gfx/invobjs/feast-rob")) {
name = "Ring of Brodgar (Seafood)";
}
}
name = name.toLowerCase();
boolean isItem = false;
if ((fep = Config.FEPMap.get(name)) != null) {
if (fep.containsKey("isItem")) {
isItem = true;
}
FEP = "\n";
for (String key : fep.keySet()) {
float val = (float) (fep.get(key) * qmult);
if (key.equals("isItem")) {
continue;
}
if (isItem) {
val = (float) Math.floor(val);
FEP += String.format("%s:%.0f ", key, val);
} else {
FEP += String.format("%s:%.1f ", key, val);
}
}
shorttip = longtip = null;
}
}
public int getLP() {
String name = name();
if (name == null) {
return 0;
}
name = name.toLowerCase();
CurioInfo curio;
if ((curio = Config.curios.get(name)) != null) {
return (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100);
}
return 0;
}
private void calcCurio() {
String name = name();
if (name == null) {
return;
}
name = name.toLowerCase();
CurioInfo curio;
if ((curio = Config.curios.get(name)) != null) {
int LP = (int) (curio.LP * qmult * ui.sess.glob.cattr.get("expmod").comp / 100);
int time = curio.time * (100 - meter) / 100;
int h = time / 60;
int m = time % 60;
curioStr = String.format("\nLP: %d, Weight: %d\nStudy time: %dh %2dm", LP, curio.weight, h, m);
shorttip = longtip = null;
}
}
public Item(Coord c, int res, int q, Widget parent, Coord drag, int num) {
this(c, parent.ui.sess.getres(res), q, parent, drag, num);
}
public Item(Coord c, Indir<Resource> res, int q, Widget parent, Coord drag) {
this(c, res, q, parent, drag, -1);
}
public Item(Coord c, int res, int q, Widget parent, Coord drag) {
this(c, parent.ui.sess.getres(res), q, parent, drag);
}
public boolean dropon(Widget w, Coord c) {
for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) {
if (wdg == this)
continue;
Coord cc = w.xlate(wdg.c, true);
if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) {
if (dropon(wdg, c.add(cc.inv())))
return (true);
}
}
if (w instanceof DTarget) {
if (((DTarget) w).drop(c, c.add(doff.inv())))
return (true);
}
if (w instanceof DTarget2) {
if (((DTarget2) w).drop(c, c.add(doff.inv()), this))
return (true);
}
return (false);
}
public boolean interact(Widget w, Coord c) {
for (Widget wdg = w.lchild; wdg != null; wdg = wdg.prev) {
if (wdg == this)
continue;
Coord cc = w.xlate(wdg.c, true);
if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) {
if (interact(wdg, c.add(cc.inv())))
return (true);
}
}
if (w instanceof DTarget) {
if (((DTarget) w).iteminteract(c, c.add(doff.inv())))
return (true);
}
return (false);
}
public void chres(Indir<Resource> res, int q) {
this.res = res;
sh = null;
decq(q);
}
public void uimsg(String name, Object... args) {
if (name == "num") {
num = (Integer) args[0];
} else if (name == "chres") {
chres(ui.sess.getres((Integer) args[0]), (Integer) args[1]);
resettt();
} else if (name == "color") {
olcol = (Color) args[0];
} else if (name == "tt") {
if ((args.length > 0) && (((String) args[0]).length() > 0))
settip((String) args[0]);
else
settip(null);
resettt();
} else if (name == "meter") {
meter = (Integer) args[0];
shorttip = null;
longtip = null;
calcCurio();
}
}
public String GetResName() { // new
if (this.res.get() != null) {
return ((Resource) this.res.get()).name;
}
return "";
}
void sortedSkoop() { // new
String name = GetResName();
if (parent instanceof Inventory)
((Inventory) parent).skoopItems(name);
}
public boolean mousedown(Coord c, int button) {
if (button == 3 && ui.modflags() == 4) { // new
sortedSkoop();
return (true);
}
if (!dm) {
if (button == 1) {
if (ui.modshift)
if (ui.modmeta)
wdgmsg("transfer-same", name(), false);
else
wdgmsg("transfer", c);
else if (ui.modctrl)
if (ui.modmeta)
wdgmsg("drop-same", name(), false);
else
wdgmsg("drop", c);
else
wdgmsg("take", c);
return (true);
} else if (button == 3) {
if (ui.modmeta) {
if (ui.modshift) {
wdgmsg("transfer-same", name(), true);
} else if (ui.modctrl) {
wdgmsg("drop-same", name(), true);
}
} else {
wdgmsg("iact", c);
}
return (true);
}
} else {
if (button == 1) {
dropon(parent, c.add(this.c));
} else if (button == 3) {
interact(parent, c.add(this.c));
}
return (true);
}
return (false);
}
public void mousemove(Coord c) {
if (dm)
this.c = this.c.add(c.add(doff.inv()));
}
public boolean drop(Coord cc, Coord ul) {
return (false);
}
public boolean iteminteract(Coord cc, Coord ul) {
wdgmsg("itemact", ui.modflags());
return (true);
}
public ItemType getItemType(Item itm) {
String resname = itm.res.get().name;
int idx = resname.lastIndexOf("/");
resname = resname.substring(idx + 1);
if (!Config.itemTypes.containsKey(resname))
return ItemType.NOT_IMPLEMENTED;
return Config.itemTypes.get(resname);
}
}
| False |
248 | 178223_2 | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen met switch statement en expliciet yield
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| BrightBoost/ocp | src/main/java/dag15/Java17Switch.java | 754 | // waarde returnen met switch statement en expliciet yield | line_comment | nl | package dag15;
import java.lang.constant.Constable;
public class Java17Switch {
enum KLEUREN {
BLAUW, GEEL, ROOD;
}
public static void main(String[] args) {
int x = 8;
switch(x) {
default:
System.out.println("Wat is dit?");
break;
case 0:
System.out.println("X is nul");
break;
case 1:
System.out.println("X is een");
break;
case 2:
System.out.println("X is twee");
break;
}
// nieuwe versie, geen break nodig bij ->
switch(x) {
case 0 -> System.out.println("X is nul");
case 1 -> { System.out.println("X is een"); break; } // dit mag
case 2 -> System.out.println("X is twee");
default -> System.out.println("Wat is dit?");
}
// waarde returnen met switch statement
String getal = switch(x) {
case 0 -> "X is nul";
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// waarde returnen<SUF>
String getal1 = switch(x) {
case 0: yield "X is nul";
case 1: yield "X is een";
case 2: yield "X is twee";
default: yield "Wat is dit?";
};
// waarde returnen met switch statement en meer acties
String getal2 = switch(x) {
case 0 -> {
System.out.println("Het is nul :)");
yield "X is nul";
}
case 1 -> "X is een";
case 2 -> "X is twee";
default -> "Wat is dit?";
};
// enums en switch
KLEUREN kleur = KLEUREN.GEEL;
String s;
switch (kleur) {
case ROOD:
System.out.println("rood");
s = "rood";
break;
case BLAUW:
System.out.println("blauw");
s = "blauw";
break;
case GEEL:
s = "geel";
break;
default:
s = "watdan?!";
}
System.out.println(s);
// als je alle labels behandelt geen default nodig
var s1 = switch (kleur) {
case ROOD -> "rood";
case BLAUW -> KLEUREN.BLAUW;
case GEEL -> 2;
};
System.out.println(s1 + " " + s1.getClass());
}
}
| True |
2,453 | 194301_0 | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| cpjjpeters/javafx1 | src/main/java/be/ipeters/brol/cpbelcar/services/CarService.java | 2,080 | /*
* bij een nieuwe wagen van een bepaald type dient de stock +1 te worden
* tegelijk 4 parts -1
*/ | block_comment | nl | package be.ipeters.brol.cpbelcar.services;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.ibatis.javassist.bytecode.Descriptor.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import be.ipeters.brol.cpbelcar.domain.Car;
import be.ipeters.brol.cpbelcar.domain.CarProduct;
import be.ipeters.brol.cpbelcar.domain.Production;
import be.ipeters.brol.cpbelcar.mappers.CarMapper;
@Service
public class CarService implements CrudService<Car, Integer> {
private boolean isCarCreationPossible = false;
private Integer pcgetProductId;
private Integer partStock = 0;
private Integer carStock = 0;
private Double partPrice=0.0;
private Double carPrice = 0.0;
private Integer partId = 0;
private Production production;
@Autowired
private CarMapper carMapper;
@Autowired
private SupplierOrderService supplierorderService;
@Autowired
private CarProductService cpService;
@Autowired
private ProductService productService;
@Autowired
private ProductionService productionService;
public CarService() {
super();
}
public CarService(CarMapper carMock) {
this.carMapper = carMock;
}
@Override
public void save(Car entity) {
/*
* bij een nieuwe<SUF>*/
checkPartsAvailable(entity.getId());
if (isCarCreationPossible) {
// verminder de stock van elk onderdeel
partId=entity.getId();
adaptPartStock( partId);
// carMapper.insert(entity); // not creating a new line in the table, so update the stock
this.updateStockPlusOne(entity);
filloutProduction();
productionService.save(production);
System.out.println("We have: "+production.getDescription());
} else {
System.out.println("Not all parts are available...");
}
}
protected void filloutProduction() {
// fill out the fields orderId, orderlineId, description, lastUpdate
production=new Production(1, 1, 1, "created car of type "+partId, LocalDate.now());
}
protected void adaptPartStock(Integer carId) {
// verminder stock van elk van de 4 parts met id=partID
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
for (CarProduct pc : cpList) {
System.out.println("productService.updateProductStock(pc.getProductId()):"+pc.getProductId());
partStock=productService.getProductStock(pc.getProductId());
System.out.println("partStock="+partStock+", for part "+pc.getProductId()+", which is "+productService.findById(pc.getProductId()));
partStock--;
System.out.println("partStock="+partStock);
productService.updateStockMinOne(pc.getProductId());
}
}
public boolean checkPartsAvailable(Integer carId) {
Map<Integer, Integer> cpMap = new HashMap<Integer, Integer>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot produce a car with id " + carId + ".");
isCarCreationPossible = false;
} else { //
for (CarProduct pc : cpList) {
pcgetProductId = pc.getProductId();
System.out.println(pcgetProductId);
partStock = productService.findById(pcgetProductId).getStock();
cpMap.put(pcgetProductId, partStock);
switch (partStock) {
case 0:
// part not available
System.out
.println("part <" + productService.findById(pcgetProductId).getName() + "> not available");
System.out.println("Need to order this part...");
// create SupplierOrder // Order this part
supplierorderService.createSupplierOrderViaPartId(pcgetProductId);
isCarCreationPossible = false;
break;
default:
System.out.println("available!");
isCarCreationPossible = true;
}
}
// check if at least one part is missing to set isCarCreationPossible=false;
for (Map.Entry<Integer, Integer> entry : cpMap.entrySet()) {
if (entry.getValue() == 0) {
isCarCreationPossible = false;
}
}
}
System.out.println("isCarCreationPossible=" + isCarCreationPossible);
return isCarCreationPossible;
}
public Double calculateCarOrderPrice(Integer carId) {
System.out.println("carService - calculateCarOrderPrice");
carPrice=0.0;
Map<Integer, Double> cpMap = new HashMap<Integer, Double>();
List<CarProduct> cpList = cpService.findAllById(carId);
System.out.println("carId=" + carId + ", size of cpList=" + cpList.size());
if (cpList.size() == 0) {
System.out.println("We cannot calculate a price for car with id " + carId + ".");
} else {
for (CarProduct cp : cpList) {
pcgetProductId = cp.getProductId();
partPrice = productService.findById(pcgetProductId).getConsumerPrice();
System.out.println(pcgetProductId+ " costs " +partPrice);
carPrice+=partPrice;
}
}
System.out.println("carPrice=" + carPrice);
return carPrice;
}
@Override
public Car findById(Integer key) {
return carMapper.findById(key);
}
@Override
public List<Car> findAll() {
return carMapper.findAll();
}
@Override
public void deleteById(Integer key) {
carMapper.deleteById(key);
}
@Override
public void update(Car entity) {
carMapper.update(entity);
}
public Integer getCarStock(Integer key) {
return carMapper.getCarStock(key);
}
public void updateStockMinOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("carStock="+carStock);
carStock--;
System.out.println("carStock="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public void updateStockPlusOne(Car entity) {
carStock=carMapper.getCarStock(entity.getId());
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
carStock++;
System.out.println("updateStockPlusOne carStock for Car "+entity.getId()+"="+carStock);
entity.setStock(carStock);
carMapper.updateStock(entity);
}
public Integer getProductStock(int carProductId) {
// TODO Auto-generated method stub
return this.findById(carProductId).getStock();
}
}
| True |
4,012 | 46920_9 | /*
* Copyright (c) 2015 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.android.util;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.Layout;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.LeadingMarginSpan;
import android.text.style.QuoteSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.TypefaceSpan;
import org.xml.sax.XMLReader;
import java.util.LinkedList;
import static android.graphics.Paint.Style.FILL;
import static android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
import static android.text.Spanned.SPAN_MARK_MARK;
/**
* HTML Utilities
*/
public class HtmlUtils {
private static class ReplySpan implements LeadingMarginSpan {
private final int color = 0xffDDDDDD;
@Override
public int getLeadingMargin(boolean first) {
return 18;
}
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
int top, int baseline, int bottom, CharSequence text,
int start, int end, boolean first, Layout layout) {
final Style style = p.getStyle();
final int color = p.getColor();
p.setStyle(FILL);
p.setColor(this.color);
c.drawRect(x, top, x + dir * 6, bottom, p);
p.setStyle(style);
p.setColor(color);
}
}
private static final String TAG_ROOT = "githubroot";
private static final String ROOT_START = '<' + TAG_ROOT + '>';
private static final String ROOT_END = "</" + TAG_ROOT + '>';
private static final String TOGGLE_START = "<span class=\"email-hidden-toggle\">";
private static final String TOGGLE_END = "</span>";
private static final String REPLY_START = "<div class=\"email-quoted-reply\">";
private static final String REPLY_END = "</div>";
private static final String SIGNATURE_START = "<div class=\"email-signature-reply\">";
private static final String SIGNATURE_END = "</div>";
private static final String EMAIL_START = "<div class=\"email-fragment\">";
private static final String EMAIL_END = "</div>";
private static final String HIDDEN_REPLY_START = "<div class=\"email-hidden-reply\" style=\" display:none\">";
private static final String HIDDEN_REPLY_END = "</div>";
private static final String BREAK = "<br>";
private static final String PARAGRAPH_START = "<p>";
private static final String PARAGRAPH_END = "</p>";
private static final String BLOCKQUOTE_START = "<blockquote>";
private static final String BLOCKQUOTE_END = "</blockquote>";
private static final String SPACE = " ";
private static final String PRE_START = "<pre>";
private static final String PRE_END = "</pre>";
private static final String CODE_START = "<code>";
private static final String CODE_END = "</code>";
private static class ListSeparator {
private int count;
public ListSeparator(boolean ordered) {
count = ordered ? 1 : -1;
}
public ListSeparator append(Editable output, int indentLevel) {
output.append('\n');
for (int i = 0; i < indentLevel * 2; i++) {
output.append(' ');
}
if (count != -1) {
output.append(Integer.toString(count)).append('.');
count++;
} else {
output.append('\u2022');
}
output.append(' ').append(' ');
return this;
}
}
private static final TagHandler TAG_HANDLER = new TagHandler() {
private static final String TAG_DEL = "del";
private static final String TAG_UL = "ul";
private static final String TAG_OL = "ol";
private static final String TAG_LI = "li";
private static final String TAG_CODE = "code";
private static final String TAG_PRE = "pre";
private int indentLevel;
private final LinkedList<ListSeparator> listElements = new LinkedList<>();
@Override
public void handleTag(final boolean opening, final String tag,
final Editable output, final XMLReader xmlReader) {
if (TAG_DEL.equalsIgnoreCase(tag)) {
if (opening) {
startSpan(new StrikethroughSpan(), output);
} else {
endSpan(StrikethroughSpan.class, output);
}
return;
}
if (TAG_UL.equalsIgnoreCase(tag)) {
if (opening) {
listElements.addFirst(new ListSeparator(false));
indentLevel++;
} else {
listElements.removeFirst();
indentLevel--;
}
if (!opening && indentLevel == 0) {
output.append('\n');
}
return;
}
if (TAG_OL.equalsIgnoreCase(tag)) {
if (opening) {
listElements.addFirst(new ListSeparator(true));
indentLevel++;
} else {
listElements.removeFirst();
indentLevel--;
}
if (!opening && indentLevel == 0) {
output.append('\n');
}
return;
}
if (TAG_LI.equalsIgnoreCase(tag) && opening) {
listElements.getFirst().append(output, indentLevel);
return;
}
if (TAG_CODE.equalsIgnoreCase(tag)) {
if (opening) {
startSpan(new TypefaceSpan("monospace"), output);
} else {
endSpan(TypefaceSpan.class, output);
}
return;
}
if (TAG_PRE.equalsIgnoreCase(tag)) {
output.append('\n');
if (opening) {
startSpan(new TypefaceSpan("monospace"), output);
} else {
endSpan(TypefaceSpan.class, output);
}
return;
}
if (TAG_ROOT.equalsIgnoreCase(tag) && !opening) {
// Remove leading newlines
while (output.length() > 0 && output.charAt(0) == '\n') {
output.delete(0, 1);
}
// Remove trailing newlines
int last = output.length() - 1;
while (last >= 0 && output.charAt(last) == '\n') {
output.delete(last, last + 1);
last = output.length() - 1;
}
QuoteSpan[] quoteSpans = output.getSpans(0, output.length(),
QuoteSpan.class);
for (QuoteSpan span : quoteSpans) {
int start = output.getSpanStart(span);
int end = output.getSpanEnd(span);
output.removeSpan(span);
output.setSpan(new ReplySpan(), start, end,
SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
};
private static Object getLast(final Spanned text, final Class<?> kind) {
Object[] spans = text.getSpans(0, text.length(), kind);
return spans.length > 0 ? spans[spans.length - 1] : null;
}
private static void startSpan(Object span, Editable output) {
int length = output.length();
output.setSpan(span, length, length, SPAN_MARK_MARK);
}
private static void endSpan(Class<?> type, Editable output) {
int length = output.length();
Object span = getLast(output, type);
int start = output.getSpanStart(span);
output.removeSpan(span);
if (start != length) {
output.setSpan(span, start, length, SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(final String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(final String html,
final ImageGetter imageGetter) {
if (TextUtils.isEmpty(html)) {
return "";
}
return Html.fromHtml(html, imageGetter, TAG_HANDLER);
}
/**
* Format given HTML string so it is ready to be presented in a text view
*
* @param html
* @return formatted HTML
*/
public static final CharSequence format(final String html) {
if (html == null) {
return "";
}
if (html.length() == 0) {
return "";
}
StringBuilder formatted = new StringBuilder(html);
// Remove e-mail toggle link
strip(formatted, TOGGLE_START, TOGGLE_END);
// Remove signature
strip(formatted, SIGNATURE_START, SIGNATURE_END);
// Replace div with e-mail content with block quote
replace(formatted, REPLY_START, REPLY_END, BLOCKQUOTE_START,
BLOCKQUOTE_END);
// Remove hidden div
strip(formatted, HIDDEN_REPLY_START, HIDDEN_REPLY_END);
// Replace paragraphs with breaks
if (replace(formatted, PARAGRAPH_START, BREAK)) {
replace(formatted, PARAGRAPH_END, BREAK);
}
formatPres(formatted);
formatEmailFragments(formatted);
trim(formatted);
formatted.insert(0, ROOT_START);
formatted.append(ROOT_END);
return formatted;
}
private static StringBuilder strip(final StringBuilder input,
final String prefix, final String suffix) {
int start = input.indexOf(prefix);
while (start != -1) {
int end = input.indexOf(suffix, start + prefix.length());
if (end == -1) {
end = input.length();
}
input.delete(start, end + suffix.length());
start = input.indexOf(prefix, start);
}
return input;
}
private static boolean replace(final StringBuilder input,
final String from, final String to) {
int start = input.indexOf(from);
if (start == -1) {
return false;
}
final int fromLength = from.length();
final int toLength = to.length();
while (start != -1) {
input.replace(start, start + fromLength, to);
start = input.indexOf(from, start + toLength);
}
return true;
}
private static void replaceTag(final StringBuilder input,
final String from, final String to) {
if (replace(input, '<' + from + '>', '<' + to + '>')) {
replace(input, "</" + from + '>', "</" + to + '>');
}
}
private static StringBuilder replace(final StringBuilder input,
final String fromStart, final String fromEnd, final String toStart,
final String toEnd) {
int start = input.indexOf(fromStart);
if (start == -1) {
return input;
}
final int fromStartLength = fromStart.length();
final int fromEndLength = fromEnd.length();
final int toStartLength = toStart.length();
while (start != -1) {
input.replace(start, start + fromStartLength, toStart);
int end = input.indexOf(fromEnd, start + toStartLength);
if (end != -1) {
input.replace(end, end + fromEndLength, toEnd);
}
start = input.indexOf(fromStart);
}
return input;
}
private static StringBuilder formatPres(final StringBuilder input) {
int start = input.indexOf(PRE_START);
final int spaceAdvance = SPACE.length() - 1;
final int breakAdvance = BREAK.length() - 1;
while (start != -1) {
int end = input.indexOf(PRE_END, start + PRE_START.length());
if (end == -1) {
break;
}
// Skip over code element
if (input.indexOf(CODE_START, start) == start) {
start += CODE_START.length();
}
if (input.indexOf(CODE_END, start) == end - CODE_END.length()) {
end -= CODE_END.length();
}
for (int i = start; i < end; i++) {
switch (input.charAt(i)) {
case ' ':
input.deleteCharAt(i);
input.insert(i, SPACE);
start += spaceAdvance;
end += spaceAdvance;
break;
case '\t':
input.deleteCharAt(i);
input.insert(i, SPACE);
start += spaceAdvance;
end += spaceAdvance;
for (int j = 0; j < 3; j++) {
input.insert(i, SPACE);
start += spaceAdvance + 1;
end += spaceAdvance + 1;
}
break;
case '\n':
input.deleteCharAt(i);
// Ignore if last character is a newline
if (i + 1 < end) {
input.insert(i, BREAK);
start += breakAdvance;
end += breakAdvance;
}
break;
}
}
start = input.indexOf(PRE_START, end + PRE_END.length());
}
return input;
}
/**
* Remove email fragment 'div' tag and replace newlines with 'br' tags
*
* @param input
* @return input
*/
private static StringBuilder formatEmailFragments(final StringBuilder input) {
int emailStart = input.indexOf(EMAIL_START);
int breakAdvance = BREAK.length() - 1;
while (emailStart != -1) {
int startLength = EMAIL_START.length();
int emailEnd = input.indexOf(EMAIL_END, emailStart + startLength);
if (emailEnd == -1) {
break;
}
input.delete(emailEnd, emailEnd + EMAIL_END.length());
input.delete(emailStart, emailStart + startLength);
int fullEmail = emailEnd - startLength;
for (int i = emailStart; i < fullEmail; i++) {
if (input.charAt(i) == '\n') {
input.deleteCharAt(i);
input.insert(i, BREAK);
i += breakAdvance;
fullEmail += breakAdvance;
}
}
emailStart = input.indexOf(EMAIL_START, fullEmail);
}
return input;
}
/**
* Remove leading and trailing whitespace
*
* @param input
*/
private static StringBuilder trim(final StringBuilder input) {
int length = input.length();
int breakLength = BREAK.length();
while (length > 0) {
if (input.indexOf(BREAK) == 0) {
input.delete(0, breakLength);
} else if (length >= breakLength
&& input.lastIndexOf(BREAK) == length - breakLength) {
input.delete(length - breakLength, length);
} else if (Character.isWhitespace(input.charAt(0))) {
input.deleteCharAt(0);
} else if (Character.isWhitespace(input.charAt(length - 1))) {
input.deleteCharAt(length - 1);
} else {
break;
}
length = input.length();
}
return input;
}
}
| pockethub/PocketHub | app/src/main/java/com/github/pockethub/android/util/HtmlUtils.java | 4,549 | // Remove hidden div | line_comment | nl | /*
* Copyright (c) 2015 PocketHub
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.pockethub.android.util;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.text.Editable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.Html.TagHandler;
import android.text.Layout;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.LeadingMarginSpan;
import android.text.style.QuoteSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.TypefaceSpan;
import org.xml.sax.XMLReader;
import java.util.LinkedList;
import static android.graphics.Paint.Style.FILL;
import static android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE;
import static android.text.Spanned.SPAN_MARK_MARK;
/**
* HTML Utilities
*/
public class HtmlUtils {
private static class ReplySpan implements LeadingMarginSpan {
private final int color = 0xffDDDDDD;
@Override
public int getLeadingMargin(boolean first) {
return 18;
}
@Override
public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,
int top, int baseline, int bottom, CharSequence text,
int start, int end, boolean first, Layout layout) {
final Style style = p.getStyle();
final int color = p.getColor();
p.setStyle(FILL);
p.setColor(this.color);
c.drawRect(x, top, x + dir * 6, bottom, p);
p.setStyle(style);
p.setColor(color);
}
}
private static final String TAG_ROOT = "githubroot";
private static final String ROOT_START = '<' + TAG_ROOT + '>';
private static final String ROOT_END = "</" + TAG_ROOT + '>';
private static final String TOGGLE_START = "<span class=\"email-hidden-toggle\">";
private static final String TOGGLE_END = "</span>";
private static final String REPLY_START = "<div class=\"email-quoted-reply\">";
private static final String REPLY_END = "</div>";
private static final String SIGNATURE_START = "<div class=\"email-signature-reply\">";
private static final String SIGNATURE_END = "</div>";
private static final String EMAIL_START = "<div class=\"email-fragment\">";
private static final String EMAIL_END = "</div>";
private static final String HIDDEN_REPLY_START = "<div class=\"email-hidden-reply\" style=\" display:none\">";
private static final String HIDDEN_REPLY_END = "</div>";
private static final String BREAK = "<br>";
private static final String PARAGRAPH_START = "<p>";
private static final String PARAGRAPH_END = "</p>";
private static final String BLOCKQUOTE_START = "<blockquote>";
private static final String BLOCKQUOTE_END = "</blockquote>";
private static final String SPACE = " ";
private static final String PRE_START = "<pre>";
private static final String PRE_END = "</pre>";
private static final String CODE_START = "<code>";
private static final String CODE_END = "</code>";
private static class ListSeparator {
private int count;
public ListSeparator(boolean ordered) {
count = ordered ? 1 : -1;
}
public ListSeparator append(Editable output, int indentLevel) {
output.append('\n');
for (int i = 0; i < indentLevel * 2; i++) {
output.append(' ');
}
if (count != -1) {
output.append(Integer.toString(count)).append('.');
count++;
} else {
output.append('\u2022');
}
output.append(' ').append(' ');
return this;
}
}
private static final TagHandler TAG_HANDLER = new TagHandler() {
private static final String TAG_DEL = "del";
private static final String TAG_UL = "ul";
private static final String TAG_OL = "ol";
private static final String TAG_LI = "li";
private static final String TAG_CODE = "code";
private static final String TAG_PRE = "pre";
private int indentLevel;
private final LinkedList<ListSeparator> listElements = new LinkedList<>();
@Override
public void handleTag(final boolean opening, final String tag,
final Editable output, final XMLReader xmlReader) {
if (TAG_DEL.equalsIgnoreCase(tag)) {
if (opening) {
startSpan(new StrikethroughSpan(), output);
} else {
endSpan(StrikethroughSpan.class, output);
}
return;
}
if (TAG_UL.equalsIgnoreCase(tag)) {
if (opening) {
listElements.addFirst(new ListSeparator(false));
indentLevel++;
} else {
listElements.removeFirst();
indentLevel--;
}
if (!opening && indentLevel == 0) {
output.append('\n');
}
return;
}
if (TAG_OL.equalsIgnoreCase(tag)) {
if (opening) {
listElements.addFirst(new ListSeparator(true));
indentLevel++;
} else {
listElements.removeFirst();
indentLevel--;
}
if (!opening && indentLevel == 0) {
output.append('\n');
}
return;
}
if (TAG_LI.equalsIgnoreCase(tag) && opening) {
listElements.getFirst().append(output, indentLevel);
return;
}
if (TAG_CODE.equalsIgnoreCase(tag)) {
if (opening) {
startSpan(new TypefaceSpan("monospace"), output);
} else {
endSpan(TypefaceSpan.class, output);
}
return;
}
if (TAG_PRE.equalsIgnoreCase(tag)) {
output.append('\n');
if (opening) {
startSpan(new TypefaceSpan("monospace"), output);
} else {
endSpan(TypefaceSpan.class, output);
}
return;
}
if (TAG_ROOT.equalsIgnoreCase(tag) && !opening) {
// Remove leading newlines
while (output.length() > 0 && output.charAt(0) == '\n') {
output.delete(0, 1);
}
// Remove trailing newlines
int last = output.length() - 1;
while (last >= 0 && output.charAt(last) == '\n') {
output.delete(last, last + 1);
last = output.length() - 1;
}
QuoteSpan[] quoteSpans = output.getSpans(0, output.length(),
QuoteSpan.class);
for (QuoteSpan span : quoteSpans) {
int start = output.getSpanStart(span);
int end = output.getSpanEnd(span);
output.removeSpan(span);
output.setSpan(new ReplySpan(), start, end,
SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
};
private static Object getLast(final Spanned text, final Class<?> kind) {
Object[] spans = text.getSpans(0, text.length(), kind);
return spans.length > 0 ? spans[spans.length - 1] : null;
}
private static void startSpan(Object span, Editable output) {
int length = output.length();
output.setSpan(span, length, length, SPAN_MARK_MARK);
}
private static void endSpan(Class<?> type, Editable output) {
int length = output.length();
Object span = getLast(output, type);
int start = output.getSpanStart(span);
output.removeSpan(span);
if (start != length) {
output.setSpan(span, start, length, SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
/**
* Encode HTML
*
* @param html
* @return html
*/
public static CharSequence encode(final String html) {
return encode(html, null);
}
/**
* Encode HTML
*
* @param html
* @param imageGetter
* @return html
*/
public static CharSequence encode(final String html,
final ImageGetter imageGetter) {
if (TextUtils.isEmpty(html)) {
return "";
}
return Html.fromHtml(html, imageGetter, TAG_HANDLER);
}
/**
* Format given HTML string so it is ready to be presented in a text view
*
* @param html
* @return formatted HTML
*/
public static final CharSequence format(final String html) {
if (html == null) {
return "";
}
if (html.length() == 0) {
return "";
}
StringBuilder formatted = new StringBuilder(html);
// Remove e-mail toggle link
strip(formatted, TOGGLE_START, TOGGLE_END);
// Remove signature
strip(formatted, SIGNATURE_START, SIGNATURE_END);
// Replace div with e-mail content with block quote
replace(formatted, REPLY_START, REPLY_END, BLOCKQUOTE_START,
BLOCKQUOTE_END);
// Remove hidden<SUF>
strip(formatted, HIDDEN_REPLY_START, HIDDEN_REPLY_END);
// Replace paragraphs with breaks
if (replace(formatted, PARAGRAPH_START, BREAK)) {
replace(formatted, PARAGRAPH_END, BREAK);
}
formatPres(formatted);
formatEmailFragments(formatted);
trim(formatted);
formatted.insert(0, ROOT_START);
formatted.append(ROOT_END);
return formatted;
}
private static StringBuilder strip(final StringBuilder input,
final String prefix, final String suffix) {
int start = input.indexOf(prefix);
while (start != -1) {
int end = input.indexOf(suffix, start + prefix.length());
if (end == -1) {
end = input.length();
}
input.delete(start, end + suffix.length());
start = input.indexOf(prefix, start);
}
return input;
}
private static boolean replace(final StringBuilder input,
final String from, final String to) {
int start = input.indexOf(from);
if (start == -1) {
return false;
}
final int fromLength = from.length();
final int toLength = to.length();
while (start != -1) {
input.replace(start, start + fromLength, to);
start = input.indexOf(from, start + toLength);
}
return true;
}
private static void replaceTag(final StringBuilder input,
final String from, final String to) {
if (replace(input, '<' + from + '>', '<' + to + '>')) {
replace(input, "</" + from + '>', "</" + to + '>');
}
}
private static StringBuilder replace(final StringBuilder input,
final String fromStart, final String fromEnd, final String toStart,
final String toEnd) {
int start = input.indexOf(fromStart);
if (start == -1) {
return input;
}
final int fromStartLength = fromStart.length();
final int fromEndLength = fromEnd.length();
final int toStartLength = toStart.length();
while (start != -1) {
input.replace(start, start + fromStartLength, toStart);
int end = input.indexOf(fromEnd, start + toStartLength);
if (end != -1) {
input.replace(end, end + fromEndLength, toEnd);
}
start = input.indexOf(fromStart);
}
return input;
}
private static StringBuilder formatPres(final StringBuilder input) {
int start = input.indexOf(PRE_START);
final int spaceAdvance = SPACE.length() - 1;
final int breakAdvance = BREAK.length() - 1;
while (start != -1) {
int end = input.indexOf(PRE_END, start + PRE_START.length());
if (end == -1) {
break;
}
// Skip over code element
if (input.indexOf(CODE_START, start) == start) {
start += CODE_START.length();
}
if (input.indexOf(CODE_END, start) == end - CODE_END.length()) {
end -= CODE_END.length();
}
for (int i = start; i < end; i++) {
switch (input.charAt(i)) {
case ' ':
input.deleteCharAt(i);
input.insert(i, SPACE);
start += spaceAdvance;
end += spaceAdvance;
break;
case '\t':
input.deleteCharAt(i);
input.insert(i, SPACE);
start += spaceAdvance;
end += spaceAdvance;
for (int j = 0; j < 3; j++) {
input.insert(i, SPACE);
start += spaceAdvance + 1;
end += spaceAdvance + 1;
}
break;
case '\n':
input.deleteCharAt(i);
// Ignore if last character is a newline
if (i + 1 < end) {
input.insert(i, BREAK);
start += breakAdvance;
end += breakAdvance;
}
break;
}
}
start = input.indexOf(PRE_START, end + PRE_END.length());
}
return input;
}
/**
* Remove email fragment 'div' tag and replace newlines with 'br' tags
*
* @param input
* @return input
*/
private static StringBuilder formatEmailFragments(final StringBuilder input) {
int emailStart = input.indexOf(EMAIL_START);
int breakAdvance = BREAK.length() - 1;
while (emailStart != -1) {
int startLength = EMAIL_START.length();
int emailEnd = input.indexOf(EMAIL_END, emailStart + startLength);
if (emailEnd == -1) {
break;
}
input.delete(emailEnd, emailEnd + EMAIL_END.length());
input.delete(emailStart, emailStart + startLength);
int fullEmail = emailEnd - startLength;
for (int i = emailStart; i < fullEmail; i++) {
if (input.charAt(i) == '\n') {
input.deleteCharAt(i);
input.insert(i, BREAK);
i += breakAdvance;
fullEmail += breakAdvance;
}
}
emailStart = input.indexOf(EMAIL_START, fullEmail);
}
return input;
}
/**
* Remove leading and trailing whitespace
*
* @param input
*/
private static StringBuilder trim(final StringBuilder input) {
int length = input.length();
int breakLength = BREAK.length();
while (length > 0) {
if (input.indexOf(BREAK) == 0) {
input.delete(0, breakLength);
} else if (length >= breakLength
&& input.lastIndexOf(BREAK) == length - breakLength) {
input.delete(length - breakLength, length);
} else if (Character.isWhitespace(input.charAt(0))) {
input.deleteCharAt(0);
} else if (Character.isWhitespace(input.charAt(length - 1))) {
input.deleteCharAt(length - 1);
} else {
break;
}
length = input.length();
}
return input;
}
}
| False |
2,665 | 143237_48 | /*
* 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 org.apache.jasper;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldLocationsCache;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public final class EmbeddedServletOptions implements Options {
// Logger
private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); // must not be static
private Properties settings = new Properties();
/**
* Is Jasper being used in development mode?
*/
private boolean development = true;
/**
* Should Ant fork its java compiles of JSP pages.
*/
public boolean fork = true;
/**
* Do you want to keep the generated Java files around?
*/
private boolean keepGenerated = true;
/**
* Should template text that consists entirely of whitespace be removed?
*/
private boolean trimSpaces = false;
/**
* Determines whether tag handler pooling is enabled.
*/
private boolean isPoolingEnabled = true;
/**
* Do you want support for "mapped" files? This will generate
* servlet that has a print statement per line of the JSP file.
* This seems like a really nice feature to have for debugging.
*/
private boolean mappedFile = true;
/**
* Do we want to include debugging information in the class file?
*/
private boolean classDebugInfo = true;
/**
* Background compile thread check interval in seconds.
*/
private int checkInterval = 0;
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
private boolean isSmapSuppressed = false;
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
private boolean isSmapDumped = false;
/**
* Are Text strings to be generated as char arrays?
*/
private boolean genStringAsCharArray = false;
private boolean errorOnUseBeanInvalidClassAttribute = true;
/**
* I want to see my generated servlets. Which directory are they
* in?
*/
private File scratchDir;
/**
* Need to have this as is for versions 4 and 5 of IE. Can be set from
* the initParams so if it changes in the future all that is needed is
* to have a jsp initParam of type ieClassId="<value>"
*/
private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
/**
* What classpath should I use while compiling generated servlets?
*/
private String classpath = null;
/**
* Compiler to use.
*/
private String compiler = null;
/**
* Compiler target VM.
*/
private String compilerTargetVM = "1.6";
/**
* The compiler source VM.
*/
private String compilerSourceVM = "1.6";
/**
* The compiler class name.
*/
private String compilerClassName = null;
/**
* Cache for the TLD locations
*/
private TldLocationsCache tldLocationsCache = null;
/**
* Jsp config information
*/
private JspConfig jspConfig = null;
/**
* TagPluginManager
*/
private TagPluginManager tagPluginManager = null;
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
private String javaEncoding = "UTF-8";
/**
* Modification test interval.
*/
private int modificationTestInterval = 4;
/**
* Is re-compilation attempted immediately after a failure?
*/
private boolean recompileOnFail = false;
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
private boolean xpoweredBy;
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
private boolean displaySourceFragment = true;
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded.
*/
private int maxLoadedJsps = -1;
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
private int jspIdleTimeout = -1;
/**
* When EL is used in JSP attribute values, should the rules for quoting of
* attributes described in JSP.1.6 be applied to the expression?
*/
private boolean quoteAttributeEL = true;
public String getProperty(String name ) {
return settings.getProperty( name );
}
public void setProperty(String name, String value ) {
if (name != null && value != null){
settings.setProperty( name, value );
}
}
public void setQuoteAttributeEL(boolean b) {
this.quoteAttributeEL = b;
}
@Override
public boolean getQuoteAttributeEL() {
return quoteAttributeEL;
}
/**
* Are we keeping generated code around?
*/
@Override
public boolean getKeepGenerated() {
return keepGenerated;
}
/**
* Should template text that consists entirely of whitespace be removed?
*/
@Override
public boolean getTrimSpaces() {
return trimSpaces;
}
@Override
public boolean isPoolingEnabled() {
return isPoolingEnabled;
}
/**
* Are we supporting HTML mapped servlets?
*/
@Override
public boolean getMappedFile() {
return mappedFile;
}
/**
* Should class files be compiled with debug information?
*/
@Override
public boolean getClassDebugInfo() {
return classDebugInfo;
}
/**
* Background JSP compile thread check interval
*/
@Override
public int getCheckInterval() {
return checkInterval;
}
/**
* Modification test interval.
*/
@Override
public int getModificationTestInterval() {
return modificationTestInterval;
}
/**
* Re-compile on failure.
*/
@Override
public boolean getRecompileOnFail() {
return recompileOnFail;
}
/**
* Is Jasper being used in development mode?
*/
@Override
public boolean getDevelopment() {
return development;
}
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
@Override
public boolean isSmapSuppressed() {
return isSmapSuppressed;
}
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
@Override
public boolean isSmapDumped() {
return isSmapDumped;
}
/**
* Are Text strings to be generated as char arrays?
*/
@Override
public boolean genStringAsCharArray() {
return this.genStringAsCharArray;
}
/**
* Class ID for use in the plugin tag when the browser is IE.
*/
@Override
public String getIeClassId() {
return ieClassId;
}
/**
* What is my scratch dir?
*/
@Override
public File getScratchDir() {
return scratchDir;
}
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
@Override
public String getClassPath() {
return classpath;
}
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
@Override
public boolean isXpoweredBy() {
return xpoweredBy;
}
/**
* Compiler to use.
*/
@Override
public String getCompiler() {
return compiler;
}
/**
* @see Options#getCompilerTargetVM
*/
@Override
public String getCompilerTargetVM() {
return compilerTargetVM;
}
/**
* @see Options#getCompilerSourceVM
*/
@Override
public String getCompilerSourceVM() {
return compilerSourceVM;
}
/**
* Java compiler class to use.
*/
@Override
public String getCompilerClassName() {
return compilerClassName;
}
@Override
public boolean getErrorOnUseBeanInvalidClassAttribute() {
return errorOnUseBeanInvalidClassAttribute;
}
public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
errorOnUseBeanInvalidClassAttribute = b;
}
@Override
public TldLocationsCache getTldLocationsCache() {
return tldLocationsCache;
}
public void setTldLocationsCache( TldLocationsCache tldC ) {
tldLocationsCache = tldC;
}
@Override
public String getJavaEncoding() {
return javaEncoding;
}
@Override
public boolean getFork() {
return fork;
}
@Override
public JspConfig getJspConfig() {
return jspConfig;
}
@Override
public TagPluginManager getTagPluginManager() {
return tagPluginManager;
}
@Override
public boolean isCaching() {
return false;
}
@Override
public Map<String, TagLibraryInfo> getCache() {
return null;
}
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
@Override
public boolean getDisplaySourceFragment() {
return displaySourceFragment;
}
/**
* Should jsps be unloaded if to many are loaded?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getMaxLoadedJsps() {
return maxLoadedJsps;
}
/**
* Should any jsps be unloaded when being idle for this time in seconds?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getJspIdleTimeout() {
return jspIdleTimeout;
}
/**
* Create an EmbeddedServletOptions object using data available from
* ServletConfig and ServletContext.
*/
public EmbeddedServletOptions(ServletConfig config,
ServletContext context) {
Enumeration<String> enumeration=config.getInitParameterNames();
while( enumeration.hasMoreElements() ) {
String k=enumeration.nextElement();
String v=config.getInitParameter( k );
setProperty( k, v);
}
String keepgen = config.getInitParameter("keepgenerated");
if (keepgen != null) {
if (keepgen.equalsIgnoreCase("true")) {
this.keepGenerated = true;
} else if (keepgen.equalsIgnoreCase("false")) {
this.keepGenerated = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.keepgen"));
}
}
}
String trimsp = config.getInitParameter("trimSpaces");
if (trimsp != null) {
if (trimsp.equalsIgnoreCase("true")) {
trimSpaces = true;
} else if (trimsp.equalsIgnoreCase("false")) {
trimSpaces = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
}
}
}
this.isPoolingEnabled = true;
String poolingEnabledParam
= config.getInitParameter("enablePooling");
if (poolingEnabledParam != null
&& !poolingEnabledParam.equalsIgnoreCase("true")) {
if (poolingEnabledParam.equalsIgnoreCase("false")) {
this.isPoolingEnabled = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
}
}
}
String mapFile = config.getInitParameter("mappedfile");
if (mapFile != null) {
if (mapFile.equalsIgnoreCase("true")) {
this.mappedFile = true;
} else if (mapFile.equalsIgnoreCase("false")) {
this.mappedFile = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
}
}
}
String debugInfo = config.getInitParameter("classdebuginfo");
if (debugInfo != null) {
if (debugInfo.equalsIgnoreCase("true")) {
this.classDebugInfo = true;
} else if (debugInfo.equalsIgnoreCase("false")) {
this.classDebugInfo = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
}
}
}
String checkInterval = config.getInitParameter("checkInterval");
if (checkInterval != null) {
try {
this.checkInterval = Integer.parseInt(checkInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
}
}
}
String modificationTestInterval = config.getInitParameter("modificationTestInterval");
if (modificationTestInterval != null) {
try {
this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
}
}
}
String recompileOnFail = config.getInitParameter("recompileOnFail");
if (recompileOnFail != null) {
if (recompileOnFail.equalsIgnoreCase("true")) {
this.recompileOnFail = true;
} else if (recompileOnFail.equalsIgnoreCase("false")) {
this.recompileOnFail = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
}
}
}
String development = config.getInitParameter("development");
if (development != null) {
if (development.equalsIgnoreCase("true")) {
this.development = true;
} else if (development.equalsIgnoreCase("false")) {
this.development = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.development"));
}
}
}
String suppressSmap = config.getInitParameter("suppressSmap");
if (suppressSmap != null) {
if (suppressSmap.equalsIgnoreCase("true")) {
isSmapSuppressed = true;
} else if (suppressSmap.equalsIgnoreCase("false")) {
isSmapSuppressed = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
}
}
}
String dumpSmap = config.getInitParameter("dumpSmap");
if (dumpSmap != null) {
if (dumpSmap.equalsIgnoreCase("true")) {
isSmapDumped = true;
} else if (dumpSmap.equalsIgnoreCase("false")) {
isSmapDumped = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
}
}
}
String genCharArray = config.getInitParameter("genStringAsCharArray");
if (genCharArray != null) {
if (genCharArray.equalsIgnoreCase("true")) {
genStringAsCharArray = true;
} else if (genCharArray.equalsIgnoreCase("false")) {
genStringAsCharArray = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.genchararray"));
}
}
}
String errBeanClass =
config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
if (errBeanClass != null) {
if (errBeanClass.equalsIgnoreCase("true")) {
errorOnUseBeanInvalidClassAttribute = true;
} else if (errBeanClass.equalsIgnoreCase("false")) {
errorOnUseBeanInvalidClassAttribute = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.errBean"));
}
}
}
String ieClassId = config.getInitParameter("ieClassId");
if (ieClassId != null)
this.ieClassId = ieClassId;
String classpath = config.getInitParameter("classpath");
if (classpath != null)
this.classpath = classpath;
/*
* scratchdir
*/
String dir = config.getInitParameter("scratchdir");
if (dir != null && Constants.IS_SECURITY_ENABLED) {
log.info(Localizer.getMessage("jsp.info.ignoreSetting", "scratchdir", dir));
dir = null;
}
if (dir != null) {
scratchDir = new File(dir);
} else {
// First try the Servlet 2.2 javax.servlet.context.tempdir property
scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
if (scratchDir == null) {
// Not running in a Servlet 2.2 container.
// Try to get the JDK 1.2 java.io.tmpdir property
dir = System.getProperty("java.io.tmpdir");
if (dir != null)
scratchDir = new File(dir);
}
}
if (this.scratchDir == null) {
log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
return;
}
if (!(scratchDir.exists() && scratchDir.canRead() &&
scratchDir.canWrite() && scratchDir.isDirectory()))
log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
scratchDir.getAbsolutePath()));
this.compiler = config.getInitParameter("compiler");
String compilerTargetVM = config.getInitParameter("compilerTargetVM");
if(compilerTargetVM != null) {
this.compilerTargetVM = compilerTargetVM;
}
String compilerSourceVM = config.getInitParameter("compilerSourceVM");
if(compilerSourceVM != null) {
this.compilerSourceVM = compilerSourceVM;
}
String javaEncoding = config.getInitParameter("javaEncoding");
if (javaEncoding != null) {
this.javaEncoding = javaEncoding;
}
String compilerClassName = config.getInitParameter("compilerClassName");
if (compilerClassName != null) {
this.compilerClassName = compilerClassName;
}
String fork = config.getInitParameter("fork");
if (fork != null) {
if (fork.equalsIgnoreCase("true")) {
this.fork = true;
} else if (fork.equalsIgnoreCase("false")) {
this.fork = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.fork"));
}
}
}
String xpoweredBy = config.getInitParameter("xpoweredBy");
if (xpoweredBy != null) {
if (xpoweredBy.equalsIgnoreCase("true")) {
this.xpoweredBy = true;
} else if (xpoweredBy.equalsIgnoreCase("false")) {
this.xpoweredBy = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
}
}
}
String displaySourceFragment = config.getInitParameter("displaySourceFragment");
if (displaySourceFragment != null) {
if (displaySourceFragment.equalsIgnoreCase("true")) {
this.displaySourceFragment = true;
} else if (displaySourceFragment.equalsIgnoreCase("false")) {
this.displaySourceFragment = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
}
}
}
String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
if (maxLoadedJsps != null) {
try {
this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
}
}
}
String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
if (jspIdleTimeout != null) {
try {
this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
}
}
}
String quoteAttributeEL = config.getInitParameter("quoteAttributeEL");
if (quoteAttributeEL != null) {
if (quoteAttributeEL.equalsIgnoreCase("true")) {
this.quoteAttributeEL = true;
} else if (quoteAttributeEL.equalsIgnoreCase("false")) {
this.quoteAttributeEL = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL"));
}
}
}
// Setup the global Tag Libraries location cache for this
// web-application.
tldLocationsCache = TldLocationsCache.getInstance(context);
// Setup the jsp config info for this web app.
jspConfig = new JspConfig(context);
// Create a Tag plugin instance
tagPluginManager = new TagPluginManager(context);
}
}
| enterpriseih/apache-tomcat-7.0.96-src | java/org/apache/jasper/EmbeddedServletOptions.java | 6,311 | /**
* @see Options#getCompilerTargetVM
*/ | block_comment | nl | /*
* 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 org.apache.jasper;
import java.io.File;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.jsp.tagext.TagLibraryInfo;
import org.apache.jasper.compiler.JspConfig;
import org.apache.jasper.compiler.Localizer;
import org.apache.jasper.compiler.TagPluginManager;
import org.apache.jasper.compiler.TldLocationsCache;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* A class to hold all init parameters specific to the JSP engine.
*
* @author Anil K. Vijendran
* @author Hans Bergsten
* @author Pierre Delisle
*/
public final class EmbeddedServletOptions implements Options {
// Logger
private final Log log = LogFactory.getLog(EmbeddedServletOptions.class); // must not be static
private Properties settings = new Properties();
/**
* Is Jasper being used in development mode?
*/
private boolean development = true;
/**
* Should Ant fork its java compiles of JSP pages.
*/
public boolean fork = true;
/**
* Do you want to keep the generated Java files around?
*/
private boolean keepGenerated = true;
/**
* Should template text that consists entirely of whitespace be removed?
*/
private boolean trimSpaces = false;
/**
* Determines whether tag handler pooling is enabled.
*/
private boolean isPoolingEnabled = true;
/**
* Do you want support for "mapped" files? This will generate
* servlet that has a print statement per line of the JSP file.
* This seems like a really nice feature to have for debugging.
*/
private boolean mappedFile = true;
/**
* Do we want to include debugging information in the class file?
*/
private boolean classDebugInfo = true;
/**
* Background compile thread check interval in seconds.
*/
private int checkInterval = 0;
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
private boolean isSmapSuppressed = false;
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
private boolean isSmapDumped = false;
/**
* Are Text strings to be generated as char arrays?
*/
private boolean genStringAsCharArray = false;
private boolean errorOnUseBeanInvalidClassAttribute = true;
/**
* I want to see my generated servlets. Which directory are they
* in?
*/
private File scratchDir;
/**
* Need to have this as is for versions 4 and 5 of IE. Can be set from
* the initParams so if it changes in the future all that is needed is
* to have a jsp initParam of type ieClassId="<value>"
*/
private String ieClassId = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93";
/**
* What classpath should I use while compiling generated servlets?
*/
private String classpath = null;
/**
* Compiler to use.
*/
private String compiler = null;
/**
* Compiler target VM.
*/
private String compilerTargetVM = "1.6";
/**
* The compiler source VM.
*/
private String compilerSourceVM = "1.6";
/**
* The compiler class name.
*/
private String compilerClassName = null;
/**
* Cache for the TLD locations
*/
private TldLocationsCache tldLocationsCache = null;
/**
* Jsp config information
*/
private JspConfig jspConfig = null;
/**
* TagPluginManager
*/
private TagPluginManager tagPluginManager = null;
/**
* Java platform encoding to generate the JSP
* page servlet.
*/
private String javaEncoding = "UTF-8";
/**
* Modification test interval.
*/
private int modificationTestInterval = 4;
/**
* Is re-compilation attempted immediately after a failure?
*/
private boolean recompileOnFail = false;
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
private boolean xpoweredBy;
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
private boolean displaySourceFragment = true;
/**
* The maximum number of loaded jsps per web-application. If there are more
* jsps loaded, they will be unloaded.
*/
private int maxLoadedJsps = -1;
/**
* The idle time in seconds after which a JSP is unloaded.
* If unset or less or equal than 0, no jsps are unloaded.
*/
private int jspIdleTimeout = -1;
/**
* When EL is used in JSP attribute values, should the rules for quoting of
* attributes described in JSP.1.6 be applied to the expression?
*/
private boolean quoteAttributeEL = true;
public String getProperty(String name ) {
return settings.getProperty( name );
}
public void setProperty(String name, String value ) {
if (name != null && value != null){
settings.setProperty( name, value );
}
}
public void setQuoteAttributeEL(boolean b) {
this.quoteAttributeEL = b;
}
@Override
public boolean getQuoteAttributeEL() {
return quoteAttributeEL;
}
/**
* Are we keeping generated code around?
*/
@Override
public boolean getKeepGenerated() {
return keepGenerated;
}
/**
* Should template text that consists entirely of whitespace be removed?
*/
@Override
public boolean getTrimSpaces() {
return trimSpaces;
}
@Override
public boolean isPoolingEnabled() {
return isPoolingEnabled;
}
/**
* Are we supporting HTML mapped servlets?
*/
@Override
public boolean getMappedFile() {
return mappedFile;
}
/**
* Should class files be compiled with debug information?
*/
@Override
public boolean getClassDebugInfo() {
return classDebugInfo;
}
/**
* Background JSP compile thread check interval
*/
@Override
public int getCheckInterval() {
return checkInterval;
}
/**
* Modification test interval.
*/
@Override
public int getModificationTestInterval() {
return modificationTestInterval;
}
/**
* Re-compile on failure.
*/
@Override
public boolean getRecompileOnFail() {
return recompileOnFail;
}
/**
* Is Jasper being used in development mode?
*/
@Override
public boolean getDevelopment() {
return development;
}
/**
* Is the generation of SMAP info for JSR45 debugging suppressed?
*/
@Override
public boolean isSmapSuppressed() {
return isSmapSuppressed;
}
/**
* Should SMAP info for JSR45 debugging be dumped to a file?
*/
@Override
public boolean isSmapDumped() {
return isSmapDumped;
}
/**
* Are Text strings to be generated as char arrays?
*/
@Override
public boolean genStringAsCharArray() {
return this.genStringAsCharArray;
}
/**
* Class ID for use in the plugin tag when the browser is IE.
*/
@Override
public String getIeClassId() {
return ieClassId;
}
/**
* What is my scratch dir?
*/
@Override
public File getScratchDir() {
return scratchDir;
}
/**
* What classpath should I use while compiling the servlets
* generated from JSP files?
*/
@Override
public String getClassPath() {
return classpath;
}
/**
* Is generation of X-Powered-By response header enabled/disabled?
*/
@Override
public boolean isXpoweredBy() {
return xpoweredBy;
}
/**
* Compiler to use.
*/
@Override
public String getCompiler() {
return compiler;
}
/**
* @see Options#getCompilerTargetVM
<SUF>*/
@Override
public String getCompilerTargetVM() {
return compilerTargetVM;
}
/**
* @see Options#getCompilerSourceVM
*/
@Override
public String getCompilerSourceVM() {
return compilerSourceVM;
}
/**
* Java compiler class to use.
*/
@Override
public String getCompilerClassName() {
return compilerClassName;
}
@Override
public boolean getErrorOnUseBeanInvalidClassAttribute() {
return errorOnUseBeanInvalidClassAttribute;
}
public void setErrorOnUseBeanInvalidClassAttribute(boolean b) {
errorOnUseBeanInvalidClassAttribute = b;
}
@Override
public TldLocationsCache getTldLocationsCache() {
return tldLocationsCache;
}
public void setTldLocationsCache( TldLocationsCache tldC ) {
tldLocationsCache = tldC;
}
@Override
public String getJavaEncoding() {
return javaEncoding;
}
@Override
public boolean getFork() {
return fork;
}
@Override
public JspConfig getJspConfig() {
return jspConfig;
}
@Override
public TagPluginManager getTagPluginManager() {
return tagPluginManager;
}
@Override
public boolean isCaching() {
return false;
}
@Override
public Map<String, TagLibraryInfo> getCache() {
return null;
}
/**
* Should we include a source fragment in exception messages, which could be displayed
* to the developer ?
*/
@Override
public boolean getDisplaySourceFragment() {
return displaySourceFragment;
}
/**
* Should jsps be unloaded if to many are loaded?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getMaxLoadedJsps() {
return maxLoadedJsps;
}
/**
* Should any jsps be unloaded when being idle for this time in seconds?
* If set to a value greater than 0 eviction of jsps is started. Default: -1
*/
@Override
public int getJspIdleTimeout() {
return jspIdleTimeout;
}
/**
* Create an EmbeddedServletOptions object using data available from
* ServletConfig and ServletContext.
*/
public EmbeddedServletOptions(ServletConfig config,
ServletContext context) {
Enumeration<String> enumeration=config.getInitParameterNames();
while( enumeration.hasMoreElements() ) {
String k=enumeration.nextElement();
String v=config.getInitParameter( k );
setProperty( k, v);
}
String keepgen = config.getInitParameter("keepgenerated");
if (keepgen != null) {
if (keepgen.equalsIgnoreCase("true")) {
this.keepGenerated = true;
} else if (keepgen.equalsIgnoreCase("false")) {
this.keepGenerated = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.keepgen"));
}
}
}
String trimsp = config.getInitParameter("trimSpaces");
if (trimsp != null) {
if (trimsp.equalsIgnoreCase("true")) {
trimSpaces = true;
} else if (trimsp.equalsIgnoreCase("false")) {
trimSpaces = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.trimspaces"));
}
}
}
this.isPoolingEnabled = true;
String poolingEnabledParam
= config.getInitParameter("enablePooling");
if (poolingEnabledParam != null
&& !poolingEnabledParam.equalsIgnoreCase("true")) {
if (poolingEnabledParam.equalsIgnoreCase("false")) {
this.isPoolingEnabled = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.enablePooling"));
}
}
}
String mapFile = config.getInitParameter("mappedfile");
if (mapFile != null) {
if (mapFile.equalsIgnoreCase("true")) {
this.mappedFile = true;
} else if (mapFile.equalsIgnoreCase("false")) {
this.mappedFile = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.mappedFile"));
}
}
}
String debugInfo = config.getInitParameter("classdebuginfo");
if (debugInfo != null) {
if (debugInfo.equalsIgnoreCase("true")) {
this.classDebugInfo = true;
} else if (debugInfo.equalsIgnoreCase("false")) {
this.classDebugInfo = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.classDebugInfo"));
}
}
}
String checkInterval = config.getInitParameter("checkInterval");
if (checkInterval != null) {
try {
this.checkInterval = Integer.parseInt(checkInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.checkInterval"));
}
}
}
String modificationTestInterval = config.getInitParameter("modificationTestInterval");
if (modificationTestInterval != null) {
try {
this.modificationTestInterval = Integer.parseInt(modificationTestInterval);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.modificationTestInterval"));
}
}
}
String recompileOnFail = config.getInitParameter("recompileOnFail");
if (recompileOnFail != null) {
if (recompileOnFail.equalsIgnoreCase("true")) {
this.recompileOnFail = true;
} else if (recompileOnFail.equalsIgnoreCase("false")) {
this.recompileOnFail = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.recompileOnFail"));
}
}
}
String development = config.getInitParameter("development");
if (development != null) {
if (development.equalsIgnoreCase("true")) {
this.development = true;
} else if (development.equalsIgnoreCase("false")) {
this.development = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.development"));
}
}
}
String suppressSmap = config.getInitParameter("suppressSmap");
if (suppressSmap != null) {
if (suppressSmap.equalsIgnoreCase("true")) {
isSmapSuppressed = true;
} else if (suppressSmap.equalsIgnoreCase("false")) {
isSmapSuppressed = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.suppressSmap"));
}
}
}
String dumpSmap = config.getInitParameter("dumpSmap");
if (dumpSmap != null) {
if (dumpSmap.equalsIgnoreCase("true")) {
isSmapDumped = true;
} else if (dumpSmap.equalsIgnoreCase("false")) {
isSmapDumped = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.dumpSmap"));
}
}
}
String genCharArray = config.getInitParameter("genStringAsCharArray");
if (genCharArray != null) {
if (genCharArray.equalsIgnoreCase("true")) {
genStringAsCharArray = true;
} else if (genCharArray.equalsIgnoreCase("false")) {
genStringAsCharArray = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.genchararray"));
}
}
}
String errBeanClass =
config.getInitParameter("errorOnUseBeanInvalidClassAttribute");
if (errBeanClass != null) {
if (errBeanClass.equalsIgnoreCase("true")) {
errorOnUseBeanInvalidClassAttribute = true;
} else if (errBeanClass.equalsIgnoreCase("false")) {
errorOnUseBeanInvalidClassAttribute = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.errBean"));
}
}
}
String ieClassId = config.getInitParameter("ieClassId");
if (ieClassId != null)
this.ieClassId = ieClassId;
String classpath = config.getInitParameter("classpath");
if (classpath != null)
this.classpath = classpath;
/*
* scratchdir
*/
String dir = config.getInitParameter("scratchdir");
if (dir != null && Constants.IS_SECURITY_ENABLED) {
log.info(Localizer.getMessage("jsp.info.ignoreSetting", "scratchdir", dir));
dir = null;
}
if (dir != null) {
scratchDir = new File(dir);
} else {
// First try the Servlet 2.2 javax.servlet.context.tempdir property
scratchDir = (File) context.getAttribute(ServletContext.TEMPDIR);
if (scratchDir == null) {
// Not running in a Servlet 2.2 container.
// Try to get the JDK 1.2 java.io.tmpdir property
dir = System.getProperty("java.io.tmpdir");
if (dir != null)
scratchDir = new File(dir);
}
}
if (this.scratchDir == null) {
log.fatal(Localizer.getMessage("jsp.error.no.scratch.dir"));
return;
}
if (!(scratchDir.exists() && scratchDir.canRead() &&
scratchDir.canWrite() && scratchDir.isDirectory()))
log.fatal(Localizer.getMessage("jsp.error.bad.scratch.dir",
scratchDir.getAbsolutePath()));
this.compiler = config.getInitParameter("compiler");
String compilerTargetVM = config.getInitParameter("compilerTargetVM");
if(compilerTargetVM != null) {
this.compilerTargetVM = compilerTargetVM;
}
String compilerSourceVM = config.getInitParameter("compilerSourceVM");
if(compilerSourceVM != null) {
this.compilerSourceVM = compilerSourceVM;
}
String javaEncoding = config.getInitParameter("javaEncoding");
if (javaEncoding != null) {
this.javaEncoding = javaEncoding;
}
String compilerClassName = config.getInitParameter("compilerClassName");
if (compilerClassName != null) {
this.compilerClassName = compilerClassName;
}
String fork = config.getInitParameter("fork");
if (fork != null) {
if (fork.equalsIgnoreCase("true")) {
this.fork = true;
} else if (fork.equalsIgnoreCase("false")) {
this.fork = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.fork"));
}
}
}
String xpoweredBy = config.getInitParameter("xpoweredBy");
if (xpoweredBy != null) {
if (xpoweredBy.equalsIgnoreCase("true")) {
this.xpoweredBy = true;
} else if (xpoweredBy.equalsIgnoreCase("false")) {
this.xpoweredBy = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.xpoweredBy"));
}
}
}
String displaySourceFragment = config.getInitParameter("displaySourceFragment");
if (displaySourceFragment != null) {
if (displaySourceFragment.equalsIgnoreCase("true")) {
this.displaySourceFragment = true;
} else if (displaySourceFragment.equalsIgnoreCase("false")) {
this.displaySourceFragment = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.displaySourceFragment"));
}
}
}
String maxLoadedJsps = config.getInitParameter("maxLoadedJsps");
if (maxLoadedJsps != null) {
try {
this.maxLoadedJsps = Integer.parseInt(maxLoadedJsps);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.maxLoadedJsps", ""+this.maxLoadedJsps));
}
}
}
String jspIdleTimeout = config.getInitParameter("jspIdleTimeout");
if (jspIdleTimeout != null) {
try {
this.jspIdleTimeout = Integer.parseInt(jspIdleTimeout);
} catch(NumberFormatException ex) {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.jspIdleTimeout", ""+this.jspIdleTimeout));
}
}
}
String quoteAttributeEL = config.getInitParameter("quoteAttributeEL");
if (quoteAttributeEL != null) {
if (quoteAttributeEL.equalsIgnoreCase("true")) {
this.quoteAttributeEL = true;
} else if (quoteAttributeEL.equalsIgnoreCase("false")) {
this.quoteAttributeEL = false;
} else {
if (log.isWarnEnabled()) {
log.warn(Localizer.getMessage("jsp.warning.quoteAttributeEL"));
}
}
}
// Setup the global Tag Libraries location cache for this
// web-application.
tldLocationsCache = TldLocationsCache.getInstance(context);
// Setup the jsp config info for this web app.
jspConfig = new JspConfig(context);
// Create a Tag plugin instance
tagPluginManager = new TagPluginManager(context);
}
}
| False |
2,753 | 43284_7 | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt.
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| gabeplz/ganzebordStan | src/Spel.java | 1,513 | // waarneer 2 spelers dezelfde worp hebben moet de laatste speler gooien tot hij een niet eerder gegooide waarde krijgt. | line_comment | nl | import java.nio.BufferOverflowException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Spel {
ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
//ArrayList<String> gansKleuren = new ArrayList<>(Arrays.asList("wit", "rood", "groen", "blauw", "geel", "zwart"));
ArrayList<Speler> spelerArrayList = new ArrayList<>();
ArrayList<Gans> gansArrayList = new ArrayList<>();
ArrayList<Gans> speelVolgorde = new ArrayList<>();
Dobbelsteen steen1 = new Dobbelsteen();
Dobbelsteen steen2 = new Dobbelsteen();
public void maakSpelers() {
Bord das = new Bord();
das.fillVakjeArraylist();
System.out.println("hoeveel spelers zijn er");
Scanner in = new Scanner(System.in);
int userInput = 0;
int spelers = 0;
try {
userInput = Integer.parseInt(in.next());
System.out.println("je nummer was" + userInput);
if (userInput < 0) {
throw new ArithmeticException("negatief!");
}
if (userInput >= 7) {
throw new BufferOverflowException();
}
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println("");
}
spelers = userInput;
for (int i = 0; i < spelers; i++) {
try {
System.out.println("voer je naam in");
Scanner in2 = new Scanner(System.in);
String userNaamInput = in2.next();
System.out.println("je naam is " + userNaamInput);
Speler speler = new Speler("usernaam", i + 1);
System.out.println(userNaamInput + " jij bent speler " + i + 1 + " je ganskleur is " + gansKleuren.get(i));
Gans gans = new Gans(gansKleuren.get(i), speler);
spelerArrayList.add(speler);
gansArrayList.add(gans);
} catch (BufferOverflowException ignore) {
}
}
//speler volgorde bepalen
speelVolgorde = bepaalSpeelVolgorde(gansArrayList,steen1);
System.out.println(speelVolgorde);
//methode roll 1
System.out.println("druk op een toests om terug te gaan");
userInput = Integer.parseInt(in.next());
for (int emptyLines = 0; emptyLines < 6; emptyLines++) {
System.out.println(" ");
}
// break; // breaks out of the loop, do not remove fully
} catch (NumberFormatException ignore) {
System.out.println("voer alleen getallen ");
} catch (ArithmeticException ignore) {
System.out.println("negatief ");
} catch (BufferOverflowException ignore) {
System.out.println("veel te groot getal ");
}
}
public void speelronde(ArrayList<Gans> speelVolgorde, Dobbelsteen steen1, Dobbelsteen steen2 ){
for (Gans gans: speelVolgorde) {
if (gans.BeurtOverslaan == true){
continue;
}
int waardeSteen1 = steen1.roll();
int waardeSteen2 = steen2.roll();
// TODO: 13/10/2022 // check voor specialle combi bij en eerste worp
int totaalWaardeWorp = waardeSteen1 + waardeSteen2;
int curPos = gans.getPositie();
}
// TODO: 12/10/2022 for each speler, check if beurt overslaan, roll 2 dobbelstenen, addup, check if arrayIndex empty, move on array
}
public ArrayList<Gans> bepaalSpeelVolgorde(ArrayList<Gans> gansArrayList, Dobbelsteen steen){
ArrayList<Gans> newSpeelvolgorde = new ArrayList<>();
//int[] rolls = new int[gansArrayList.size()];
int x= 0;
ArrayList<Integer> rolls = new ArrayList<>();
for (Gans i: gansArrayList) {
int currentRoll = steen.roll();
while (rolls.contains(currentRoll)){ // waarneer 2<SUF>
currentRoll = steen.roll();
}
rolls.add(currentRoll);
x+=1;
}
// sort players ; sort indexes; how to remember reference to player
// [5,3,4,1]
// get index max; place index in new VolgordeArray, set value in worp array to 0;
for (Gans ii: gansArrayList) {
int max = 0;
for (int val : rolls) {
if (val > max) {
max = val;
}
}
int indexMax = rolls.indexOf(max);
newSpeelvolgorde.add(gansArrayList.get(indexMax));
rolls.set(indexMax, 0);
}
return newSpeelvolgorde;
}
}
| True |
299 | 57243_0 | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| Camambar/CheeseSqueeze | core/src/cheese/squeeze/gameObjects/Mouse.java | 1,855 | //TODO: direction bijhouden, en veranderen als we aan een gotopoint belanden._x000D_ | line_comment | nl | package cheese.squeeze.gameObjects;_x000D_
_x000D_
import java.util.Iterator;_x000D_
import java.util.List;_x000D_
_x000D_
import cheese.squeeze.helpers.AssetLoader;_x000D_
_x000D_
import com.badlogic.gdx.Gdx;_x000D_
import com.badlogic.gdx.math.MathUtils;_x000D_
import com.badlogic.gdx.math.Vector2;_x000D_
_x000D_
//TODO: direction<SUF>
public class Mouse {_x000D_
_x000D_
private Vector2 position;_x000D_
private Vector2 velocity;_x000D_
private final float FLIKERING =100;_x000D_
private float EYEOPEN;_x000D_
private boolean open = true;_x000D_
_x000D_
private float orignSpeed;_x000D_
private float speed;_x000D_
private float tolerance = 0.02f;_x000D_
_x000D_
private Vector2 absolutePosition;_x000D_
_x000D_
private float rotation;_x000D_
private Vector2 mouseNose = AssetLoader.mouseNose;_x000D_
_x000D_
private Line currentLine;_x000D_
private Line nextLine;_x000D_
private Vector2 goToOrientation;_x000D_
private Vector2 nextGoToPoint;_x000D_
private boolean ended = false;_x000D_
_x000D_
public Mouse(float speed, Line line){_x000D_
EYEOPEN = (float) (FLIKERING*Math.random());_x000D_
float x = line.getX1();_x000D_
float y = line.getY1();_x000D_
//float y = 0;_x000D_
position = new Vector2(x,y);_x000D_
this.currentLine = line;_x000D_
this.speed = speed;_x000D_
this.orignSpeed = speed;_x000D_
//position = new Vector2(x-(mouseNose.x), y- (mouseNose.y));_x000D_
_x000D_
velocity = new Vector2(0, 0);_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
updatePath();_x000D_
}_x000D_
_x000D_
public boolean isOnHorizontalLine() {_x000D_
if(currentLine instanceof HorizontalLine) {_x000D_
return true;_x000D_
}_x000D_
return false;_x000D_
}_x000D_
_x000D_
public void update(float delta) {_x000D_
EYEOPEN--;_x000D_
_x000D_
if (nextGoToPoint != null) {_x000D_
if(atIntersection()) {_x000D_
//System.out.println("intersection reached!");_x000D_
//the mouse stands now at the previous nextGoToPoint_x000D_
setPosition(nextGoToPoint.x, nextGoToPoint.y);_x000D_
//nextGoToPoint is yet to be determined_x000D_
nextGoToPoint = null;_x000D_
//This mouse is now on the new line. _x000D_
//If there is no next line, the mouse stays on this line._x000D_
currentLine = (nextLine != null) ? nextLine : currentLine;_x000D_
//nextLine is yet to be determined._x000D_
nextLine = null;_x000D_
if (currentLine instanceof VerticalLine){_x000D_
goToOrientation = new Vector2(0, 1);_x000D_
} else if (currentLine instanceof HorizontalLine) {_x000D_
if (getPosition().equals(currentLine.getPoint1()))_x000D_
goToOrientation = currentLine.getPoint2().cpy().sub(currentLine.getPoint1());_x000D_
else_x000D_
goToOrientation = currentLine.getPoint1().cpy().sub(currentLine.getPoint2());_x000D_
}_x000D_
//updateVelocityDirection();_x000D_
//pick a new destination_x000D_
updatePath();_x000D_
}_x000D_
//set the mouses new speed._x000D_
if (atIntersection()) {_x000D_
//The mouse ran into something with a dead end._x000D_
((VerticalLine) currentLine).getGoal().activate();_x000D_
velocity.set(Vector2.Zero);_x000D_
ended = true;_x000D_
} else {_x000D_
updateVelocityDirection();_x000D_
}_x000D_
//move the mouse._x000D_
updateVelocityDirection();_x000D_
// setPosition(getX() + velocity.x * delta, getY() + velocity.y * delta);_x000D_
setPosition(getX() + velocity.x * 1, getY() + velocity.y * 1);_x000D_
//System.out.println(this.rotation);_x000D_
} _x000D_
}_x000D_
_x000D_
private void updateVelocityDirection() {_x000D_
if(!ended) {_x000D_
float angle = (float) Math.atan2(nextGoToPoint.y - getY(), nextGoToPoint.x - getX());_x000D_
velocity.set((float) Math.cos(angle) * speed, (float) Math.sin(angle) * speed);_x000D_
//set the mouses angle._x000D_
setRotation(angle * MathUtils.radiansToDegrees);_x000D_
}_x000D_
else {_x000D_
setRotation(90);_x000D_
}_x000D_
}_x000D_
_x000D_
public void updatePath() {_x000D_
Vector2 nextIntersection = currentLine.getNextIntersection(getPosition(), goToOrientation);_x000D_
nextLine = currentLine.getNeighbour(getPosition(), goToOrientation);_x000D_
if (nextIntersection == null) {_x000D_
nextGoToPoint = currentLine.getEndPoint(getPosition(), velocity);_x000D_
} else {_x000D_
nextGoToPoint = nextIntersection;_x000D_
}_x000D_
}_x000D_
_x000D_
private boolean atIntersection() {_x000D_
float dynTolerance = speed / tolerance * Gdx.graphics.getDeltaTime();_x000D_
//System.out.println("dyn tol: " + dynTolerance);_x000D_
return Math.abs(nextGoToPoint.x - getX()) <= dynTolerance _x000D_
&& Math.abs(nextGoToPoint.y - getY()) <= dynTolerance;_x000D_
}_x000D_
_x000D_
private void setRotation(float f) {_x000D_
this.rotation = f;_x000D_
_x000D_
}_x000D_
_x000D_
public float getX() {_x000D_
return position.x;_x000D_
}_x000D_
_x000D_
public float getY() {_x000D_
return position.y;_x000D_
}_x000D_
_x000D_
private void setPosition(float x,float y) {_x000D_
this.position.set(x, y);_x000D_
}_x000D_
_x000D_
public float getXAbs() {_x000D_
return this.absolutePosition.x;_x000D_
}_x000D_
_x000D_
public float getYAbs() {_x000D_
return this.absolutePosition.y;_x000D_
}_x000D_
_x000D_
public float getRotation() {_x000D_
return rotation;_x000D_
}_x000D_
_x000D_
_x000D_
public Vector2 getPosition() {_x000D_
return position;_x000D_
}_x000D_
_x000D_
public boolean isEnded() {_x000D_
return ended ;_x000D_
}_x000D_
_x000D_
public float getSpeed() {_x000D_
// TODO Auto-generated method stub_x000D_
return velocity.x + velocity.y;_x000D_
}_x000D_
_x000D_
//public void changeNextWayPoints(ArrayList<Vector2> newWaypoints) {_x000D_
// this.setPath(nPath);_x000D_
//}_x000D_
_x000D_
public boolean eyesOpen() {_x000D_
if(EYEOPEN < 0 && !open) {_x000D_
EYEOPEN = (float) ((FLIKERING*2)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
if(EYEOPEN < 0 && open) {_x000D_
EYEOPEN = (float) ((FLIKERING/5)*Math.random());_x000D_
open = !open;_x000D_
}_x000D_
return open;_x000D_
}_x000D_
_x000D_
public void setSpeed(float angle) {_x000D_
this.speed = this.orignSpeed + this.orignSpeed*angle;_x000D_
}_x000D_
_x000D_
public float getSpeedLine() {_x000D_
return this.speed - this.orignSpeed;_x000D_
}_x000D_
_x000D_
}_x000D_
| True |
2,157 | 33415_10 | package me.devsaki.hentoid.enums;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashSet;
import java.util.Set;
import io.objectbox.converter.PropertyConverter;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.json.core.JsonSiteSettings;
import me.devsaki.hentoid.util.network.HttpHelperKt;
import timber.log.Timber;
/**
* Site enumerator
*/
public enum Site {
// NOTE : to maintain compatiblity with saved JSON files and prefs, do _not_ edit either existing names or codes
FAKKU(0, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), // Legacy support for old fakku archives
PURURIN(1, "Pururin", "https://pururin.to", R.drawable.ic_site_pururin),
HITOMI(2, "hitomi", "https://hitomi.la", R.drawable.ic_site_hitomi),
NHENTAI(3, "nhentai", "https://nhentai.net", R.drawable.ic_site_nhentai),
TSUMINO(4, "tsumino", "https://www.tsumino.com", R.drawable.ic_site_tsumino),
HENTAICAFE(5, "hentaicafe", "https://hentai.cafe", R.drawable.ic_site_hentaicafe),
ASMHENTAI(6, "asmhentai", "https://asmhentai.com", R.drawable.ic_site_asmhentai),
ASMHENTAI_COMICS(7, "asmhentai comics", "https://comics.asmhentai.com", R.drawable.ic_site_asmcomics),
EHENTAI(8, "e-hentai", "https://e-hentai.org", R.drawable.ic_site_ehentai),
FAKKU2(9, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku),
NEXUS(10, "Hentai Nexus", "https://hentainexus.com", R.drawable.ic_site_nexus),
MUSES(11, "8Muses", "https://www.8muses.com", R.drawable.ic_site_8muses),
DOUJINS(12, "doujins.com", "https://doujins.com/", R.drawable.ic_site_doujins),
LUSCIOUS(13, "luscious.net", "https://members.luscious.net/manga/", R.drawable.ic_site_luscious),
EXHENTAI(14, "exhentai", "https://exhentai.org", R.drawable.ic_site_exhentai),
PORNCOMIX(15, "porncomixonline", "https://www.porncomixonline.net/", R.drawable.ic_site_porncomix),
HBROWSE(16, "Hbrowse", "https://www.hbrowse.com/", R.drawable.ic_site_hbrowse),
HENTAI2READ(17, "Hentai2Read", "https://hentai2read.com/", R.drawable.ic_site_hentai2read),
HENTAIFOX(18, "Hentaifox", "https://hentaifox.com", R.drawable.ic_site_hentaifox),
MRM(19, "MyReadingManga", "https://myreadingmanga.info/", R.drawable.ic_site_mrm),
MANHWA(20, "ManwhaHentai", "https://manhwahentai.me/", R.drawable.ic_site_manhwa),
IMHENTAI(21, "Imhentai", "https://imhentai.xxx", R.drawable.ic_site_imhentai),
TOONILY(22, "Toonily", "https://toonily.com/", R.drawable.ic_site_toonily),
ALLPORNCOMIC(23, "Allporncomic", "https://allporncomic.com/", R.drawable.ic_site_allporncomic),
PIXIV(24, "Pixiv", "https://www.pixiv.net/", R.drawable.ic_site_pixiv),
MANHWA18(25, "Manhwa18", "https://manhwa18.com/", R.drawable.ic_site_manhwa18),
MULTPORN(26, "Multporn", "https://multporn.net/", R.drawable.ic_site_multporn),
SIMPLY(27, "Simply Hentai", "https://www.simply-hentai.com/", R.drawable.ic_site_simply),
HDPORNCOMICS(28, "HD Porn Comics", "https://hdporncomics.com/", R.drawable.ic_site_hdporncomics),
EDOUJIN(29, "Edoujin", "https://edoujin.net/", R.drawable.ic_site_edoujin),
KSK(30, "Koushoku", "https://ksk.moe", R.drawable.ic_site_ksk),
ANCHIRA(31, "Anchira", "https://anchira.to", R.drawable.ic_site_anchira),
DEVIANTART(32, "DeviantArt", "https://www.deviantart.com/", R.drawable.ic_site_deviantart),
NONE(98, "none", "", R.drawable.ic_attribute_source), // External library; fallback site
PANDA(99, "panda", "https://www.mangapanda.com", R.drawable.ic_site_panda); // Safe-for-work/wife/gf option; not used anymore and kept here for retrocompatibility
private static final Site[] INVISIBLE_SITES = {
NEXUS, // Dead
HBROWSE, // Dead
HENTAICAFE, // Removed as per Fakku request + dead
KSK, // Dead
FAKKU, // Old Fakku; kept for retrocompatibility
FAKKU2, // Dropped after Fakku decided to flag downloading accounts and IPs
ASMHENTAI_COMICS, // Does not work directly
PANDA, // Dropped; kept for retrocompatibility
NONE // Technical fallback
};
private final int code;
private final String description;
private final String url;
private final int ico;
// Default values overridden in sites.json
private boolean useMobileAgent = true;
private boolean useHentoidAgent = false;
private boolean useWebviewAgent = true;
// Download behaviour control
private boolean hasBackupURLs = false;
private boolean hasCoverBasedPageUpdates = false;
private boolean useCloudflare = false;
private boolean hasUniqueBookId = false;
private int requestsCapPerSecond = -1;
private int parallelDownloadCap = 0;
// Controls for "Mark downloaded/merged" in browser
private int bookCardDepth = 2;
private Set<String> bookCardExcludedParentClasses = new HashSet<>();
// Controls for "Mark books with blocked tags" in browser
private int galleryHeight = -1;
// Determine which Jsoup output to use when rewriting the HTML
// 0 : html; 1 : xml
private int jsoupOutputSyntax = 0;
Site(int code,
String description,
String url,
int ico) {
this.code = code;
this.description = description;
this.url = url;
this.ico = ico;
}
public static Site searchByCode(long code) {
for (Site s : values())
if (s.getCode() == code) return s;
return NONE;
}
// Same as ValueOf with a fallback to NONE
// (vital for forward compatibility)
public static Site searchByName(String name) {
for (Site s : values())
if (s.name().equalsIgnoreCase(name)) return s;
return NONE;
}
@Nullable
public static Site searchByUrl(String url) {
if (null == url || url.isEmpty()) {
Timber.w("Invalid url");
return null;
}
for (Site s : Site.values())
if (s.code > 0 && HttpHelperKt.getDomainFromUri(url).equalsIgnoreCase(HttpHelperKt.getDomainFromUri(s.url)))
return s;
return Site.NONE;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public int getIco() {
return ico;
}
public boolean useMobileAgent() {
return useMobileAgent;
}
public boolean useHentoidAgent() {
return useHentoidAgent;
}
public boolean useWebviewAgent() {
return useWebviewAgent;
}
public boolean hasBackupURLs() {
return hasBackupURLs;
}
public boolean hasCoverBasedPageUpdates() {
return hasCoverBasedPageUpdates;
}
public boolean isUseCloudflare() {
return useCloudflare;
}
public boolean hasUniqueBookId() {
return hasUniqueBookId;
}
public int getRequestsCapPerSecond() {
return requestsCapPerSecond;
}
public int getParallelDownloadCap() {
return parallelDownloadCap;
}
public int getBookCardDepth() {
return bookCardDepth;
}
public Set<String> getBookCardExcludedParentClasses() {
return bookCardExcludedParentClasses;
}
public int getGalleryHeight() {
return galleryHeight;
}
public int getJsoupOutputSyntax() { return jsoupOutputSyntax; }
public boolean isVisible() {
for (Site s : INVISIBLE_SITES) if (s.equals(this)) return false;
return true;
}
public String getFolder() {
if (this == FAKKU)
return "Downloads";
else
return description;
}
public String getUserAgent() {
if (useMobileAgent())
return HttpHelperKt.getMobileUserAgent(useHentoidAgent(), useWebviewAgent());
else
return HttpHelperKt.getDesktopUserAgent(useHentoidAgent(), useWebviewAgent());
}
public void updateFrom(@NonNull final JsonSiteSettings.JsonSite jsonSite) {
if (jsonSite.getUseMobileAgent() != null) useMobileAgent = jsonSite.getUseMobileAgent();
if (jsonSite.getUseHentoidAgent() != null) useHentoidAgent = jsonSite.getUseHentoidAgent();
if (jsonSite.getUseWebviewAgent() != null) useWebviewAgent = jsonSite.getUseWebviewAgent();
if (jsonSite.getHasBackupURLs() != null) hasBackupURLs = jsonSite.getHasBackupURLs();
if (jsonSite.getHasCoverBasedPageUpdates() != null)
hasCoverBasedPageUpdates = jsonSite.getHasCoverBasedPageUpdates();
if (jsonSite.getUseCloudflare() != null)
useCloudflare = jsonSite.getUseCloudflare();
if (jsonSite.getHasUniqueBookId() != null)
hasUniqueBookId = jsonSite.getHasUniqueBookId();
if (jsonSite.getParallelDownloadCap() != null)
parallelDownloadCap = jsonSite.getParallelDownloadCap();
if (jsonSite.getRequestsCapPerSecond() != null)
requestsCapPerSecond = jsonSite.getRequestsCapPerSecond();
if (jsonSite.getBookCardDepth() != null)
bookCardDepth = jsonSite.getBookCardDepth();
if (jsonSite.getBookCardExcludedParentClasses() != null)
bookCardExcludedParentClasses = new HashSet<>(jsonSite.getBookCardExcludedParentClasses());
if (jsonSite.getGalleryHeight() != null)
galleryHeight = jsonSite.getGalleryHeight();
if (jsonSite.getJsoupOutputSyntax() != null)
jsoupOutputSyntax = jsonSite.getJsoupOutputSyntax();
}
public static class SiteConverter implements PropertyConverter<Site, Long> {
@Override
public Site convertToEntityProperty(Long databaseValue) {
if (databaseValue == null) {
return Site.NONE;
}
for (Site site : Site.values()) {
if (site.getCode() == databaseValue) {
return site;
}
}
return Site.NONE;
}
@Override
public Long convertToDatabaseValue(Site entityProperty) {
return entityProperty == null ? null : (long) entityProperty.getCode();
}
}
}
| avluis/Hentoid | app/src/main/java/me/devsaki/hentoid/enums/Site.java | 3,408 | // Default values overridden in sites.json | line_comment | nl | package me.devsaki.hentoid.enums;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.HashSet;
import java.util.Set;
import io.objectbox.converter.PropertyConverter;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.json.core.JsonSiteSettings;
import me.devsaki.hentoid.util.network.HttpHelperKt;
import timber.log.Timber;
/**
* Site enumerator
*/
public enum Site {
// NOTE : to maintain compatiblity with saved JSON files and prefs, do _not_ edit either existing names or codes
FAKKU(0, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku), // Legacy support for old fakku archives
PURURIN(1, "Pururin", "https://pururin.to", R.drawable.ic_site_pururin),
HITOMI(2, "hitomi", "https://hitomi.la", R.drawable.ic_site_hitomi),
NHENTAI(3, "nhentai", "https://nhentai.net", R.drawable.ic_site_nhentai),
TSUMINO(4, "tsumino", "https://www.tsumino.com", R.drawable.ic_site_tsumino),
HENTAICAFE(5, "hentaicafe", "https://hentai.cafe", R.drawable.ic_site_hentaicafe),
ASMHENTAI(6, "asmhentai", "https://asmhentai.com", R.drawable.ic_site_asmhentai),
ASMHENTAI_COMICS(7, "asmhentai comics", "https://comics.asmhentai.com", R.drawable.ic_site_asmcomics),
EHENTAI(8, "e-hentai", "https://e-hentai.org", R.drawable.ic_site_ehentai),
FAKKU2(9, "Fakku", "https://www.fakku.net", R.drawable.ic_site_fakku),
NEXUS(10, "Hentai Nexus", "https://hentainexus.com", R.drawable.ic_site_nexus),
MUSES(11, "8Muses", "https://www.8muses.com", R.drawable.ic_site_8muses),
DOUJINS(12, "doujins.com", "https://doujins.com/", R.drawable.ic_site_doujins),
LUSCIOUS(13, "luscious.net", "https://members.luscious.net/manga/", R.drawable.ic_site_luscious),
EXHENTAI(14, "exhentai", "https://exhentai.org", R.drawable.ic_site_exhentai),
PORNCOMIX(15, "porncomixonline", "https://www.porncomixonline.net/", R.drawable.ic_site_porncomix),
HBROWSE(16, "Hbrowse", "https://www.hbrowse.com/", R.drawable.ic_site_hbrowse),
HENTAI2READ(17, "Hentai2Read", "https://hentai2read.com/", R.drawable.ic_site_hentai2read),
HENTAIFOX(18, "Hentaifox", "https://hentaifox.com", R.drawable.ic_site_hentaifox),
MRM(19, "MyReadingManga", "https://myreadingmanga.info/", R.drawable.ic_site_mrm),
MANHWA(20, "ManwhaHentai", "https://manhwahentai.me/", R.drawable.ic_site_manhwa),
IMHENTAI(21, "Imhentai", "https://imhentai.xxx", R.drawable.ic_site_imhentai),
TOONILY(22, "Toonily", "https://toonily.com/", R.drawable.ic_site_toonily),
ALLPORNCOMIC(23, "Allporncomic", "https://allporncomic.com/", R.drawable.ic_site_allporncomic),
PIXIV(24, "Pixiv", "https://www.pixiv.net/", R.drawable.ic_site_pixiv),
MANHWA18(25, "Manhwa18", "https://manhwa18.com/", R.drawable.ic_site_manhwa18),
MULTPORN(26, "Multporn", "https://multporn.net/", R.drawable.ic_site_multporn),
SIMPLY(27, "Simply Hentai", "https://www.simply-hentai.com/", R.drawable.ic_site_simply),
HDPORNCOMICS(28, "HD Porn Comics", "https://hdporncomics.com/", R.drawable.ic_site_hdporncomics),
EDOUJIN(29, "Edoujin", "https://edoujin.net/", R.drawable.ic_site_edoujin),
KSK(30, "Koushoku", "https://ksk.moe", R.drawable.ic_site_ksk),
ANCHIRA(31, "Anchira", "https://anchira.to", R.drawable.ic_site_anchira),
DEVIANTART(32, "DeviantArt", "https://www.deviantart.com/", R.drawable.ic_site_deviantart),
NONE(98, "none", "", R.drawable.ic_attribute_source), // External library; fallback site
PANDA(99, "panda", "https://www.mangapanda.com", R.drawable.ic_site_panda); // Safe-for-work/wife/gf option; not used anymore and kept here for retrocompatibility
private static final Site[] INVISIBLE_SITES = {
NEXUS, // Dead
HBROWSE, // Dead
HENTAICAFE, // Removed as per Fakku request + dead
KSK, // Dead
FAKKU, // Old Fakku; kept for retrocompatibility
FAKKU2, // Dropped after Fakku decided to flag downloading accounts and IPs
ASMHENTAI_COMICS, // Does not work directly
PANDA, // Dropped; kept for retrocompatibility
NONE // Technical fallback
};
private final int code;
private final String description;
private final String url;
private final int ico;
// Default values<SUF>
private boolean useMobileAgent = true;
private boolean useHentoidAgent = false;
private boolean useWebviewAgent = true;
// Download behaviour control
private boolean hasBackupURLs = false;
private boolean hasCoverBasedPageUpdates = false;
private boolean useCloudflare = false;
private boolean hasUniqueBookId = false;
private int requestsCapPerSecond = -1;
private int parallelDownloadCap = 0;
// Controls for "Mark downloaded/merged" in browser
private int bookCardDepth = 2;
private Set<String> bookCardExcludedParentClasses = new HashSet<>();
// Controls for "Mark books with blocked tags" in browser
private int galleryHeight = -1;
// Determine which Jsoup output to use when rewriting the HTML
// 0 : html; 1 : xml
private int jsoupOutputSyntax = 0;
Site(int code,
String description,
String url,
int ico) {
this.code = code;
this.description = description;
this.url = url;
this.ico = ico;
}
public static Site searchByCode(long code) {
for (Site s : values())
if (s.getCode() == code) return s;
return NONE;
}
// Same as ValueOf with a fallback to NONE
// (vital for forward compatibility)
public static Site searchByName(String name) {
for (Site s : values())
if (s.name().equalsIgnoreCase(name)) return s;
return NONE;
}
@Nullable
public static Site searchByUrl(String url) {
if (null == url || url.isEmpty()) {
Timber.w("Invalid url");
return null;
}
for (Site s : Site.values())
if (s.code > 0 && HttpHelperKt.getDomainFromUri(url).equalsIgnoreCase(HttpHelperKt.getDomainFromUri(s.url)))
return s;
return Site.NONE;
}
public int getCode() {
return code;
}
public String getDescription() {
return description;
}
public String getUrl() {
return url;
}
public int getIco() {
return ico;
}
public boolean useMobileAgent() {
return useMobileAgent;
}
public boolean useHentoidAgent() {
return useHentoidAgent;
}
public boolean useWebviewAgent() {
return useWebviewAgent;
}
public boolean hasBackupURLs() {
return hasBackupURLs;
}
public boolean hasCoverBasedPageUpdates() {
return hasCoverBasedPageUpdates;
}
public boolean isUseCloudflare() {
return useCloudflare;
}
public boolean hasUniqueBookId() {
return hasUniqueBookId;
}
public int getRequestsCapPerSecond() {
return requestsCapPerSecond;
}
public int getParallelDownloadCap() {
return parallelDownloadCap;
}
public int getBookCardDepth() {
return bookCardDepth;
}
public Set<String> getBookCardExcludedParentClasses() {
return bookCardExcludedParentClasses;
}
public int getGalleryHeight() {
return galleryHeight;
}
public int getJsoupOutputSyntax() { return jsoupOutputSyntax; }
public boolean isVisible() {
for (Site s : INVISIBLE_SITES) if (s.equals(this)) return false;
return true;
}
public String getFolder() {
if (this == FAKKU)
return "Downloads";
else
return description;
}
public String getUserAgent() {
if (useMobileAgent())
return HttpHelperKt.getMobileUserAgent(useHentoidAgent(), useWebviewAgent());
else
return HttpHelperKt.getDesktopUserAgent(useHentoidAgent(), useWebviewAgent());
}
public void updateFrom(@NonNull final JsonSiteSettings.JsonSite jsonSite) {
if (jsonSite.getUseMobileAgent() != null) useMobileAgent = jsonSite.getUseMobileAgent();
if (jsonSite.getUseHentoidAgent() != null) useHentoidAgent = jsonSite.getUseHentoidAgent();
if (jsonSite.getUseWebviewAgent() != null) useWebviewAgent = jsonSite.getUseWebviewAgent();
if (jsonSite.getHasBackupURLs() != null) hasBackupURLs = jsonSite.getHasBackupURLs();
if (jsonSite.getHasCoverBasedPageUpdates() != null)
hasCoverBasedPageUpdates = jsonSite.getHasCoverBasedPageUpdates();
if (jsonSite.getUseCloudflare() != null)
useCloudflare = jsonSite.getUseCloudflare();
if (jsonSite.getHasUniqueBookId() != null)
hasUniqueBookId = jsonSite.getHasUniqueBookId();
if (jsonSite.getParallelDownloadCap() != null)
parallelDownloadCap = jsonSite.getParallelDownloadCap();
if (jsonSite.getRequestsCapPerSecond() != null)
requestsCapPerSecond = jsonSite.getRequestsCapPerSecond();
if (jsonSite.getBookCardDepth() != null)
bookCardDepth = jsonSite.getBookCardDepth();
if (jsonSite.getBookCardExcludedParentClasses() != null)
bookCardExcludedParentClasses = new HashSet<>(jsonSite.getBookCardExcludedParentClasses());
if (jsonSite.getGalleryHeight() != null)
galleryHeight = jsonSite.getGalleryHeight();
if (jsonSite.getJsoupOutputSyntax() != null)
jsoupOutputSyntax = jsonSite.getJsoupOutputSyntax();
}
public static class SiteConverter implements PropertyConverter<Site, Long> {
@Override
public Site convertToEntityProperty(Long databaseValue) {
if (databaseValue == null) {
return Site.NONE;
}
for (Site site : Site.values()) {
if (site.getCode() == databaseValue) {
return site;
}
}
return Site.NONE;
}
@Override
public Long convertToDatabaseValue(Site entityProperty) {
return entityProperty == null ? null : (long) entityProperty.getCode();
}
}
}
| False |
1,827 | 99855_5 | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| Valuya/bobthetinker | bobthetinker-core/src/main/java/be/valuya/bob/core/reader/BobAccountRecordReader.java | 3,727 | //: (STRING, 120): Eigen vermogen, voorzieningen voor risico's en kosten en schulden op meer dan een jaar | line_comment | nl | package be.valuya.bob.core.reader;
import be.valuya.advantaje.core.AdvantajeRecord;
import be.valuya.bob.core.domain.BobAccount;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Optional;
public class BobAccountRecordReader {
public BobAccount readAccount(AdvantajeRecord advantajeRecord) {
String aid = advantajeRecord.getValue("AID"); //: (STRING, 10): 1
Optional<Boolean> aistitle = advantajeRecord.getValueOptional("AISTITLE"); //: (LOGICAL, 1): true
Optional<String> heading1 = advantajeRecord.getValueOptional("HEADING1"); //: (STRING, 40): Fonds propres
Optional<String> heading2 = advantajeRecord.getValueOptional("HEADING2"); //: (STRING, 40): Eigen vermogen
Optional<String> longheading1 = advantajeRecord.getValueOptional("LONGHEADING1"); //: (STRING, 120): Fonds propres, provisions pour risques et charges et dettes à plus d'un an
Optional<String> longheading2 = advantajeRecord.getValueOptional("LONGHEADING2"); //: (STRING,<SUF>
Optional<String> asecondid = advantajeRecord.getValueOptional("ASECONDID"); //: (STRING, 10):
Optional<String> afree = advantajeRecord.getValueOptional("AFREE"); //: (STRING, 40):
Optional<String> acat = advantajeRecord.getValueOptional("ACAT"); //: (STRING, 3):
Optional<String> aintcat = advantajeRecord.getValueOptional("AINTCAT"); //: (STRING, 10):
Optional<String> acatcomm = advantajeRecord.getValueOptional("ACATCOMM"); //: (STRING, 1):
Optional<String> adbcd = advantajeRecord.getValueOptional("ADBCD"); //: (STRING, 1): C
Optional<Boolean> aiscost = advantajeRecord.getValueOptional("AISCOST"); //: (LOGICAL, 1): [-]
Optional<String> avattype = advantajeRecord.getValueOptional("AVATTYPE"); //: (STRING, 1):
Optional<String> avatenat1 = advantajeRecord.getValueOptional("AVATENAT1"); //: (STRING, 3):
Optional<String> avatenat2 = advantajeRecord.getValueOptional("AVATENAT2"); //: (STRING, 3):
Optional<Double> avatecmp = advantajeRecord.getValueOptional("AVATECMP"); //: (DOUBLE, 8): [-]
Optional<String> avatnnat1 = advantajeRecord.getValueOptional("AVATNNAT1"); //: (STRING, 3):
Optional<String> avatnnat2 = advantajeRecord.getValueOptional("AVATNNAT2"); //: (STRING, 3):
Optional<Double> avatncmp = advantajeRecord.getValueOptional("AVATNCMP"); //: (DOUBLE, 8): [-]
Optional<String> avatinat1 = advantajeRecord.getValueOptional("AVATINAT1"); //: (STRING, 3):
Optional<String> avatinat2 = advantajeRecord.getValueOptional("AVATINAT2"); //: (STRING, 3):
Optional<Double> avaticmp = advantajeRecord.getValueOptional("AVATICMP"); //: (DOUBLE, 8): [-]
Optional<Boolean> aissummary = advantajeRecord.getValueOptional("AISSUMMARY"); //: (LOGICAL, 1): false
Optional<Boolean> aisstatus = advantajeRecord.getValueOptional("AISSTATUS"); //: (LOGICAL, 1): [-]
Optional<Boolean> aisreadonl = advantajeRecord.getValueOptional("AISREADONL"); //: (LOGICAL, 1): false
Optional<Boolean> aissecret = advantajeRecord.getValueOptional("AISSECRET"); //: (LOGICAL, 1): false
Optional<Boolean> vtravfa = advantajeRecord.getValueOptional("VTRAVFA"); //: (LOGICAL, 1): [-]
Optional<Boolean> aismatch = advantajeRecord.getValueOptional("AISMATCH"); //: (LOGICAL, 1): false
Optional<String> depacc = advantajeRecord.getValueOptional("DEPACC"); //: (STRING, 10):
Optional<String> provacc = advantajeRecord.getValueOptional("PROVACC"); //: (STRING, 10):
Optional<Boolean> hisintrastat = advantajeRecord.getValueOptional("HISINTRASTAT"); //: (LOGICAL, 1): [-]
Optional<Integer> amatchno = advantajeRecord.getValueOptional("AMATCHNO"); //: (INTEGER, 4): [-]
Optional<String> abalance = advantajeRecord.getValueOptional("ABALANCE"); //: (STRING, 10): LIABILIT
Optional<String> arem = advantajeRecord.getValueOptional("AREM"); //: (STRING, 35):
Optional<Boolean> avatcas = advantajeRecord.getValueOptional("AVATCAS"); //: (LOGICAL, 1): [-]
Optional<Boolean> acctsecondid = advantajeRecord.getValueOptional("ACCTSECONDID"); //: (LOGICAL, 1): [-]
Optional<byte[]> amemo = advantajeRecord.getValueOptional("AMEMO"); //: (BINARY, 9): [B@3cda1055
Optional<Double> prcndcharges = advantajeRecord.getValueOptional("PRCNDCHARGES"); //: (DOUBLE, 8): 0.0
Optional<Double> prcprivate = advantajeRecord.getValueOptional("PRCPRIVATE"); //: (DOUBLE, 8): 0.0
Optional<String> typendcharges = advantajeRecord.getValueOptional("TYPENDCHARGES"); //: (STRING, 12):
Optional<String> createdby = advantajeRecord.getValueOptional("CREATEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> createdon = advantajeRecord.getValueOptional("CREATEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> modifiedby = advantajeRecord.getValueOptional("MODIFIEDBY"); //: (STRING, 10): LICOPPE
Optional<LocalDateTime> modifiedon = advantajeRecord.getValueOptional("MODIFIEDON"); //: (TIMESTAMP, 8): 2017-01-18T14:04:14.595
Optional<String> trftstatus = advantajeRecord.getValueOptional("TRFTSTATUS"); //: (STRING, 3): A
Optional<String> stationid = advantajeRecord.getValueOptional("STATIONID"); //: (STRING, 3):
Optional<String> afixtype = advantajeRecord.getValueOptional("AFIXTYPE"); //: (STRING, 10):
Optional<Boolean> asleeping = advantajeRecord.getValueOptional("ASLEEPING"); //: (LOGICAL, 1): false
Optional<Boolean> discadvnot = advantajeRecord.getValueOptional("DISCADVNOT"); //: (LOGICAL, 1): false
Optional<String> subtype = advantajeRecord.getValueOptional("SUBTYPE"); //: (STRING, 10): LEQUITY
Optional<String> provaccexc = advantajeRecord.getValueOptional("PROVACCEXC"); //: (STRING, 10):
Optional<String> annexid = advantajeRecord.getValueOptional("ANNEXID"); //: (STRING, 15):
Optional<String> altacct = advantajeRecord.getValueOptional("ALTACCT"); //: (STRING, 10):
Optional<String> aautoop = advantajeRecord.getValueOptional("AAUTOOP"); //: (STRING, 2):
Optional<String> aoldid = advantajeRecord.getValueOptional("AOLDID"); //: (STRING, 10):
Optional<String> aprivaccount = advantajeRecord.getValueOptional("APRIVACCOUNT"); //: (STRING, 10):
Optional<String> oldheading1 = advantajeRecord.getValueOptional("OLDHEADING1"); //: (STRING, 40):
Optional<String> oldheading2 = advantajeRecord.getValueOptional("OLDHEADING2"); //: (STRING, 40):
Optional<Boolean> naeprior = advantajeRecord.getValueOptional("NAEPRIOR"); //: (LOGICAL, 1): [-]
Optional<Boolean> asynchro = advantajeRecord.getValueOptional("ASYNCHRO"); //: (LOGICAL, 1): true
Optional<String> apcnid = advantajeRecord.getValueOptional("APCNID"); //: (STRING, 10):
Optional<BigDecimal> avatecmpOptional = avatecmp.map(this::toBigDecimal);
Optional<BigDecimal> avatncmpOptional = avatncmp.map(this::toBigDecimal);
Optional<BigDecimal> avaticmpOptional = avaticmp.map(this::toBigDecimal);
Optional<BigDecimal> prcndchargesOptional = prcndcharges.map(this::toBigDecimal);
Optional<BigDecimal> prcprivateOptional = prcprivate.map(this::toBigDecimal);
BobAccount bobAccount = new BobAccount();
bobAccount.setAid(aid);
bobAccount.setaIsTitle(aistitle.orElse(null));
bobAccount.setHeading1(heading1.orElse(null));
bobAccount.setHeading2(heading2.orElse(null));
bobAccount.setLongHeading1(longheading1.orElse(null));
bobAccount.setLongHeading2(longheading2.orElse(null));
bobAccount.setSecondId(asecondid.orElse(null));
bobAccount.setFree(afree.orElse(null));
bobAccount.setaCat(acat.orElse(null));
bobAccount.setaIntCat(aintcat.orElse(null));
bobAccount.setaCatComm(acatcomm.orElse(null));
bobAccount.setAdbcd(adbcd.orElse(null));
bobAccount.setAiscost(aiscost.orElse(null));
bobAccount.setAvattype(avattype.orElse(null));
bobAccount.setAvatenat1(avatenat1.orElse(null));
bobAccount.setAvatenat2(avatenat2.orElse(null));
bobAccount.setAvatecmp(avatecmpOptional.orElse(null));
bobAccount.setAvatnnat1(avatnnat1.orElse(null));
bobAccount.setAvatnnat2(avatnnat2.orElse(null));
bobAccount.setAvatncmp(avatncmpOptional.orElse(null));
bobAccount.setAvatinat1(avatinat1.orElse(null));
bobAccount.setAvatinat2(avatinat2.orElse(null));
bobAccount.setAvaticmp(avaticmpOptional.orElse(null));
bobAccount.setAissummary(aissummary.orElse(null));
bobAccount.setAisstatus(aisstatus.orElse(null));
bobAccount.setAisreadonl(aisreadonl.orElse(null));
bobAccount.setAissecret(aissecret.orElse(null));
bobAccount.setVtravfa(vtravfa.orElse(null));
bobAccount.setAismatch(aismatch.orElse(null));
bobAccount.setDepacc(depacc.orElse(null));
bobAccount.setProvacc(provacc.orElse(null));
bobAccount.setHisintrastat(hisintrastat.orElse(null));
bobAccount.setAmatchno(amatchno.orElse(null));
bobAccount.setAbalance(abalance.orElse(null));
bobAccount.setArem(arem.orElse(null));
bobAccount.setAvatcas(avatcas.orElse(null));
bobAccount.setAcctsecondid(acctsecondid.orElse(null));
bobAccount.setAmemo(amemo.orElse(null));
bobAccount.setPrcndcharges(prcndchargesOptional.orElse(null));
bobAccount.setPrcprivate(prcprivateOptional.orElse(null));
bobAccount.setTypendcharges(typendcharges.orElse(null));
bobAccount.setCreatedby(createdby.orElse(null));
bobAccount.setCreatedon(createdon.orElse(null));
bobAccount.setModifiedby(modifiedby.orElse(null));
bobAccount.setModifiedon(modifiedon.orElse(null));
bobAccount.setTrftstatus(trftstatus.orElse(null));
bobAccount.setStationid(stationid.orElse(null));
bobAccount.setAfixtype(afixtype.orElse(null));
bobAccount.setAsleeping(asleeping.orElse(null));
bobAccount.setDiscadvnot(discadvnot.orElse(null));
bobAccount.setSubtype(subtype.orElse(null));
bobAccount.setProvaccexc(provaccexc.orElse(null));
bobAccount.setAnnexid(annexid.orElse(null));
bobAccount.setAltacct(altacct.orElse(null));
bobAccount.setAautoop(aautoop.orElse(null));
bobAccount.setAoldid(aoldid.orElse(null));
bobAccount.setAprivaccount(aprivaccount.orElse(null));
bobAccount.setOldheading1(oldheading1.orElse(null));
bobAccount.setOldheading2(oldheading2.orElse(null));
bobAccount.setNaeprior(naeprior.orElse(null));
bobAccount.setAsynchro(asynchro.orElse(null));
bobAccount.setApcnid(apcnid.orElse(null));
return bobAccount;
}
private BigDecimal toBigDecimal(Double aDouble) {
return BigDecimal.valueOf(aDouble);
}
}
| True |
4,199 | 164742_11 | package com.example.bottom_navigationbar_view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class DFragment extends Fragment {
public DFragment() {
// Required empty public constructor
}
AutoCompleteTextView autoCompleteTextView, autoCompleteTextView1;
ArrayAdapter<String> adapterItems, adapterItems1;
Spinner userStateSpinner;
List<String> states = new ArrayList<>();
String[] STATES = {"Andaman and Nicobar", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chhattisgarh", "Dadra and Nagar Haveli", "Daman and Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadweep", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Puducherry",
"Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"};
Map<String, Integer> stateIndexMap = new HashMap<>();
// String[] CITIES = {"rohith", "rahul", "uttej"};
String[][] CITIES = {
{"Car Nicobar","Mayabunder","Port Blair"},
{"Anantapur","Chittoor","Eluru","Guntur","Kadapa","Kakinada","Kurnool","Machilipatnam","Nellore","Ongole","Srikakulam","Visakhapatnam","Vizianagaram"},
{"Along", "Anini", "Basar", "Bomdila", "Changlang", "Daporijo", "Hawai", "Itanagar", "Jamin", "Khonsa", "Koloriang", "Lemmi", "Likabali", "Longding", "Namsai", "Pangin", "Pasighat", "Raga", "Roing", "Seppa", "Tato", "Tawang Town", "Tezu", "Yingkiong", "Ziro"},
{"Barpeta", "Bishwanath Chariali", "Bongaigaon", "Dhemaji", "Dhubri", "Dibrugarh", "Diphu", "Garamur", "Goalpara", "Golaghat", "Goroimari", "Guwahati", "Haflong", "Hailakandi", "Hamren", "Hatsingimari", "Hojai", "Jorhat", "Kajalgaon", "Karimganj", "Kokrajhar", "Mangaldoi", "Marigaon", "Mushalpur", "Nagaon", "Nalbari", "North Lakhimpur", "Sibsagar", "Silchar", "Sonari", "Tezpur", "Tinsukia", "Udalguri"},
{"Araria", "Arrah", "Arwal", "Aurangabad", "Banka", "Begusarai", "Bettiah", "Bhabua", "Bhagalpur", "Bihar Sharif", "Buxar", "Chhapra", "Darbhanga", "Gaya", "Gopalganj", "Hajipur", "Jamui", "Jehanabad", "Katihar", "Khagaria", "Kishanganj", "Lakhisarai", "Madhepura", "Madhubani", "Motihari", "Munger", "Muzaffarpur", "Nawada", "Patna", "Purnia", "Saharsa", "Samastipur", "Sasaram", "Sheikhpura", "Sheohar", "Sitamarhi", "Siwan", "Supaul"},
{"Chandigarh"},
{"Ambikapur", "Baikunthpur", "Balod", "Baloda Bazar", "Balrampur", "Bemetara", "Bijapur", "Bilaspur", "Dantewada", "Dhamtari", "Durg", "Gariaband", "Gaurela Pendra Marwahi", "Jagdalpur", "Jashpur Nagar", "Kanker", "Kawardha", "Kondagaon", "Korba", "Mahasamund", "Mungeli", "Naila Janjgir", "Narayanpur", "Raigarh", "Raipur", "Rajnandgaon", "Sukma", "Surajpur"},
{"Silvassa"},
{"Daman","Diu"},
{"Daryaganj", "Defence Colony", "Kanjhawala", "New Delhi", "Preet Vihar", "Rajouri Garden", "Sadar Bazaar", "Saket", "Shahdara", "Vasant Vihar"},
{"Margao","Panaji"},
{"Ahmedabad", "Ahwa", "Amreli", "Anand", "Bharuch", "Bhavnagar", "Bhuj", "Botad", "Chhota Udepur", "Dahod", "Gandhinagar", "Godhra", "Himatnagar", "Jamnagar", "Junagadh", "Khambhalia", "Lunavada", "Mehsana", "Modasa", "Morbi", "Nadiad", "Navsari", "Palanpur", "Patan", "Porbandar", "Rajkot", "Rajpipla", "Surat", "Surendranagar", "Vadodara", "Valsad", "Veraval", "Vyara"},
{"Ambala", "Bhiwani", "Charkhi Dadri", "Faridabad", "Fatehabad", "Gurgaon", "Hissar", "Jhajjar", "Jind", "Kaithal", "Karnal", "Kurukshetra", "Narnaul", "Nuh", "Palwal", "Panchkula", "Panipat", "Rewari", "Rohtak", "Sirsa", "Sonipat", "Yamuna Nagar"},
{"Bilaspur", "Chamba", "Dharamshala", "Hamirpur", "Keylong", "Kullu", "Mandi", "Nahan", "Reckong Peo", "Shimla", "Solan", "Una"},
{"Anantnag", "Badgam", "Bandipore", "Baramulla", "Doda", "Ganderbal", "Jammu", "Kargil", "Kathua", "Kishtwar", "Kulgam", "Kupwara", "Leh", "Poonch", "Pulwama", "Rajouri", "Ramban", "Reasi", "Samba", "Shupiyan", "Srinagar", "Udhampur"},
{"Bokaro", "Chaibasa", "Chatra", "Daltonganj", "Deoghar", "Dhanbad", "Dumka", "Garhwa", "Giridih", "Godda", "Gumla", "Hazaribag", "Jamshedpur", "Jamtara", "Khunti", "Koderma", "Latehar", "Lohardaga", "Pakur", "Ramgarh", "Ranchi", "Sahebganj", "Seraikela", "Simdega"},
{"Bagalkot", "Bangalore", "Belgaum", "Bellary", "Bengaluru", "Bidar", "Chamarajanagar", "Chikkaballapur", "Chikmagalur", "Chitradurga", "Davangere", "Dharwad", "Gadag Betageri", "Gulbarga", "Hassan", "Haveri", "Karwar", "Kolar", "Koppal", "Madikeri", "Mandya", "Mangalore", "Mysore", "Raichur", "Ramanagara", "Shimoga", "Tumkur", "Udupi", "Vijayapura", "Yadgir"},
{"Alappuzha", "Ernakulam", "Kalpetta", "Kannur", "Kasaragod", "Kollam", "Kottayam", "Kozhikode", "Malappuram", "Painavu", "Palakkad", "Pathanamthitta", "Thiruvananthapuram", "Thrissur"},
{"Kavaratti"},
{"Agar", "Alirajpur", "Anuppur", "Ashok Nagar", "Balaghat", "Barwani", "Betul", "Bhind", "Bhopal", "Burhanpur", "Chachaura", "Chhatarpur", "Chhindwara", "Damoh", "Datia", "Dewas", "Dhar", "Dindori", "Guna", "Gwalior", "Harda", "Hoshangabad", "Indore", "Jabalpur", "Jhabua", "Katni", "Khandwa", "Khargone", "Maihar", "Mandla", "Mandsaur", "Morena", "Nagda", "Narsinghpur", "Neemuch", "Niwari", "Panna", "Raisen", "Rajgarh", "Ratlam", "Rewa", "Sagar", "Satna", "Sehore", "Seoni", "Shahdol", "Shajapur", "Sheopur", "Shivpuri", "Sidhi", "Tikamgarh", "Ujjain", "Umaria", "Vidisha", "Waidhan"},
{"Ahmednagar", "Akola", "Alibag", "Amravati", "Aurangabad", "Bandra (East)", "Beed", "Bhandara", "Buldhana", "Chandrapur", "Dhule", "Gadchiroli", "Gondia", "Hingoli", "Jalgaon", "Jalna", "Kolhapur", "Latur", "Mumbai", "Nagpur", "Nanded", "Nandurbar", "Nashik", "Oros", "Osmanabad", "Palghar", "Parbhani", "Pune", "Ratnagiri", "Sangli", "Satara", "Solapur", "Thane", "Wardha", "Washim", "Yavatmal"},
{"Bishnupur", "Chandel", "Churachandpur", "Imphal", "Jiribam", "Kakching", "Kamjong", "Kangpokpi", "Noney Longmai", "Pherzawl", "Porompat", "Senapati", "Tamenglong", "Tengnoupal", "Thoubal", "Ukhrul"},
{"Ampati", "Baghmara", "Jowai", "Khleihriat", "Mawkyrwat", "Nongpoh", "Nongstoin", "Resubelpara", "Shillong", "Tura", "Williamnagar"},
{"Aizawl", "Champhai", "Kolasib", "Lawngtlai", "Lunglei", "Mamit", "Saiha", "Serchhip"},
{"Dimapur", "Kiphire", "Kohima", "Longleng", "Mokokchung", "Mon", "Noklak", "Peren", "Phek", "Tuensang", "Wokha", "Zunheboto"},
{"Angul", "Balangir", "Balasore", "Bargarh", "Baripada", "Bhadrak", "Bhawanipatna", "Bhubaneswar", "Boudh", "Chhatrapur", "Cuttack", "Debagarh", "Dhenkanal", "Jagatsinghpur", "Jharsuguda", "Kendrapara", "Kendujhar", "Koraput", "Malkangiri", "Nabarangpur", "Nayagarh", "Nuapada", "Panikoili", "Paralakhemundi", "Phulbani", "Puri", "Rayagada", "Sambalpur", "Subarnapur", "Sundargarh"},
{"Karaikal","Mahe","Pondicherry","Yanam"},
{"Amritsar", "Barnala", "Bathinda", "Faridkot", "Fatehgarh Sahib", "Fazilka", "Firozpur", "Gurdaspur", "Hoshiarpur", "Jalandhar", "Kapurthala", "Ludhiana", "Mansa", "Moga", "Mohali", "Nawanshahr", "Pathankot", "Patiala", "Rupnagar", "Sangrur", "Sri Muktsar Sahib", "Tarn Taran Sahib"},
{"Ajmer", "Alwar", "Banswara", "Baran", "Barmer", "Bharatpur", "Bhilwara", "Bikaner", "Bundi", "Chittorgarh", "Churu", "Dausa", "Dholpur", "Dungarpur", "Ganganagar", "Hanumangarh", "Jaipur", "Jaisalmer", "Jalore", "Jhalawar", "Jhunjhunu", "Jodhpur", "Karauli", "Kota", "Nagaur", "Pali", "Pratapgarh", "Rajsamand", "Sawai Madhopur", "Sikar", "Sirohi", "Tonk", "Udaipur"},
{"Gangtok", "Geyzing", "Mangan", "Namchi"},
{"Ariyalur", "Chengalpattu", "Chennai", "Coimbatore", "Cuddalore", "Dharmapuri", "Dindigul", "Erode", "Hosur", "Kallakurichi", "Kanchipuram", "Karur", "Krishnagiri", "Madurai", "Mayiladuthurai", "Nagapattinam", "Nagercoil", "Namakkal", "Perambalur", "Pudukkottai", "Ramanathapuram", "Ranipet", "Salem", "Sivaganga", "Tenkasi", "Thanjavur", "Theni", "Thoothukudi", "Thoothukudi (Tuticorin)", "Tiruchirappalli", "Tirunelveli", "Tirupattur", "Tirupur", "Tiruvallur", "Tiruvannaamalai", "Tiruvarur", "Udagamandalam (Ooty)", "Vellore", "Viluppuram", "Virudhunagar"},
{"Adilabad", "Bhongiri", "Bhupalpalle", "Gadwal", "Geesugonda", "Hyderabad", "Jagtial", "Jangaon", "Kamareddy", "Karimnagar", "Khammam", "Komaram Bheem", "Kothagudem", "Mahabubabad", "Mahbubnagar", "Mancherial", "Medak", "Mulugu", "Nagarkurnool", "Nalgonda", "Narayanpet", "Nirmal", "Nizamabad", "Peddapalle", "Sangareddy", "Shamirpet", "Shamshabad", "Siddipet", "Sircilla", "Suryapet", "Vikarabad", "Wanaparthy", "Warangal"},
{"Agartala", "Ambassa", "Belonia", "Bishramganj", "Dharmanagar", "Kailashahar", "Khowai", "Udaipur Tripura"},
{"Agra", "Akbarpur", "Akbarpur (Mati)", "Aligarh", "Allahabad", "Amroha", "Auraiya", "Azamgarh", "Baghpat", "Bahraich", "Ballia", "Balrampur", "Banda", "Barabanki", "Bareilly", "Basti", "Bijnor", "Budaun", "Bulandshahr", "Chandauli", "Deoria", "Etah", "Etawah", "Faizabad", "Fatehgarh", "Fatehpur", "Firozabad", "Gauriganj", "Ghaziabad", "Ghazipur", "Gonda", "Gorakhpur", "Gyanpur", "Hamirpur", "Hapur", "Hardoi", "Hathras", "Jaunpur", "Jhansi", "Kannauj", "Kanpur", "Karwi", "Kasganj", "Khalilabad", "Lakhimpur", "Lalitpur", "Lucknow", "Maharajganj", "Mahoba", "Mainpuri", "Manjhanpur", "Mathura", "Mau", "Meerut", "Mirzapur", "Moradabad", "Muzaffarnagar", "Naugarh", "Noida", "Orai", "Padrauna", "Pilibhit", "Pratapgarh", "Raebareli", "Rampur", "Robertsganj", "Saharanpur", "Sambhal", "Shahjahanpur", "Shamli", "Shravasti", "Sitapur", "Sultanpur", "Unnao", "Varanasi"},
{"Almora", "Bageshwar", "Champawat", "Dehradun", "Gopeshwar", "Haridwar", "Nainital", "New Tehri", "Pauri", "Pithoragarh", "Rudraprayag", "Rudrapur", "Uttarkashi"},
{"Alipore", "Alipurduar", "Baharampur", "Balurghat", "Bankura", "Barasat", "Bardhaman", "Chinsurah", "Cooch Behar", "Darjeeling", "English Bazar", "Howrah", "Jalpaiguri", "Kolkata", "Krishnanagar", "Midnapore", "Purulia", "Raiganj", "Suri", "Tamluk"}
};
ArrayAdapter<String> userStateAdapter;
Button btn;
// private AViewModel aViewModel;
private int onViewStateRestoredCallBack = 0;
private String selectedUserState = "Select";
private String selectedUserCity = "Select";
private Switch soundToggle;
private SoundManager soundManager;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_d, container, false);
if(!InternetConnectivityUtil.isConnected(getContext())) {
InternetConnectivityUtil.closeApp(getContext(), this.getActivity());
}
for (int i = 0; i < STATES.length; i++) {
stateIndexMap.put(STATES[i], i);
}
soundToggle = view.findViewById(R.id.soundToggle);
soundManager = SoundManager.getInstance(requireContext());
retrieveSoundToggle();
loadStatesArray();
autoCompleteTextView = view.findViewById(R.id.auto_complete_text);
adapterItems = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, STATES);
autoCompleteTextView.setAdapter(adapterItems);
// For city
autoCompleteTextView1 = view.findViewById(R.id.auto_complete_text_city);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
saveSelectedUserState(item); saveSelectedUserCity("");
autoCompleteTextView1.setText("");
autoCompleteTextView.setText(item);
autoCompleteTextView.setSelection(item.length());
int index = stateIndexMap.get(item);
System.out.println("Saved index: " + index);
saveStatePosition(index);
saveStateChangeFlag(true);
saveStateChangeFlag_B_o(true);
Toast.makeText(getContext(), "State: " + item, Toast.LENGTH_SHORT).show();
String[] filteredCities = filterCitiesByState(index);
// System.out.println("Cities list");
// for(String s: filter)
adapterItems1 = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, filteredCities);
autoCompleteTextView1.setAdapter(adapterItems1);
}
});
if(retrieveStatePosition() != -1){
System.out.println("Retrieved index: " + retrieveStatePosition());
String[] filteredCities = filterCitiesByState(retrieveStatePosition());
adapterItems1 = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, filteredCities);
autoCompleteTextView1.setAdapter(adapterItems1);
}
autoCompleteTextView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
saveSelectedUserCity(item);
autoCompleteTextView1.setText(item); autoCompleteTextView1.setSelection(item.length());
saveStateChangeFlag(true); saveStateChangeFlag_B_o(true);
Toast.makeText(getContext(), "City: " + item, Toast.LENGTH_SHORT).show();
}
});
soundToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) soundManager.enableSound(); // Enable sound
else soundManager.disableSound(); // Disable sound
storingSoundToggle();
}
});
return view;
}
private void loadStatesArray() {
states = Arrays.asList(new String[]{"Andaman and Nicobar", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chhattisgarh", "Dadra and Nagar Haveli", "Daman and Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadweep", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Puducherry",
"Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"});
}
String[] filterCitiesByState (int index){
return CITIES[index];
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getId() == R.id.presentStateSpinner1) {
selectedUserState = parent.getItemAtPosition(position).toString();
saveSelectedUserState(selectedUserState);
autoCompleteTextView.setText(selectedUserState);
autoCompleteTextView.setSelection(selectedUserState.length());
System.out.println("onItemSelected() > " + selectedUserState);
if(onViewStateRestoredCallBack == 0){
saveStateChangeFlag(true); saveStateChangeFlag_B_o(true);
}
onViewStateRestoredCallBack = 0;
}
}
private void saveStatePosition(int flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("Position_flag " + flag);
editor.putInt("state_change_position", flag);
editor.apply();
}
private int retrieveStatePosition() {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
return sharedPreferences.getInt("state_change_position", -1);
}
private void saveStateChangeFlag(boolean flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("flag " + flag);
editor.putBoolean("state_change_flag", flag);
editor.apply();
}
private void saveStateChangeFlag_B_o(boolean flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("flag_B_o " + flag);
editor.putBoolean("state_change_flag_B_o", flag);
editor.apply();
}
private void saveSelectedUserState(String selectedUserState) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("selected_userState", selectedUserState);
editor.apply();
}
private void saveSelectedUserCity(String selectedUserCity) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("selected_userCity", selectedUserCity);
editor.apply();
}
//
// @Override
public void onNothingSelected(AdapterView<?> parent) {
System.out.println("onNothingSelected() ");
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
selectedUserState = sharedPreferences.getString("selected_userState", "Telangana");
autoCompleteTextView.setText(selectedUserState);
autoCompleteTextView.setSelection(selectedUserState.length());
selectedUserCity = sharedPreferences.getString("selected_userCity", "Kamareddy");
autoCompleteTextView1.setText(selectedUserCity);
autoCompleteTextView1.setSelection(selectedUserCity.length());
}
public void storingSoundToggle(){
// Get a reference to the SharedPreferences
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Get the SharedPreferences editor
SharedPreferences.Editor editor = sharedPreferences.edit();
// Get the current state of the soundToggle and store it
boolean isSoundEnabled = soundManager.isSoundEnabled();
editor.putBoolean("soundEnabled", isSoundEnabled);
// Apply the changes
editor.apply();
}
public void retrieveSoundToggle(){
// Get a reference to the SharedPreferences
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Retrieve the stored boolean value
boolean isSoundEnabled = sharedPreferences.getBoolean("soundEnabled", true); // Default value is true
// Set the soundToggle based on the retrieved value
soundToggle.setChecked(isSoundEnabled);
}
}
| rohith2001/Project | DFragment.java | 7,402 | // Default value is true | line_comment | nl | package com.example.bottom_navigationbar_view;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
public class DFragment extends Fragment {
public DFragment() {
// Required empty public constructor
}
AutoCompleteTextView autoCompleteTextView, autoCompleteTextView1;
ArrayAdapter<String> adapterItems, adapterItems1;
Spinner userStateSpinner;
List<String> states = new ArrayList<>();
String[] STATES = {"Andaman and Nicobar", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chhattisgarh", "Dadra and Nagar Haveli", "Daman and Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadweep", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Puducherry",
"Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"};
Map<String, Integer> stateIndexMap = new HashMap<>();
// String[] CITIES = {"rohith", "rahul", "uttej"};
String[][] CITIES = {
{"Car Nicobar","Mayabunder","Port Blair"},
{"Anantapur","Chittoor","Eluru","Guntur","Kadapa","Kakinada","Kurnool","Machilipatnam","Nellore","Ongole","Srikakulam","Visakhapatnam","Vizianagaram"},
{"Along", "Anini", "Basar", "Bomdila", "Changlang", "Daporijo", "Hawai", "Itanagar", "Jamin", "Khonsa", "Koloriang", "Lemmi", "Likabali", "Longding", "Namsai", "Pangin", "Pasighat", "Raga", "Roing", "Seppa", "Tato", "Tawang Town", "Tezu", "Yingkiong", "Ziro"},
{"Barpeta", "Bishwanath Chariali", "Bongaigaon", "Dhemaji", "Dhubri", "Dibrugarh", "Diphu", "Garamur", "Goalpara", "Golaghat", "Goroimari", "Guwahati", "Haflong", "Hailakandi", "Hamren", "Hatsingimari", "Hojai", "Jorhat", "Kajalgaon", "Karimganj", "Kokrajhar", "Mangaldoi", "Marigaon", "Mushalpur", "Nagaon", "Nalbari", "North Lakhimpur", "Sibsagar", "Silchar", "Sonari", "Tezpur", "Tinsukia", "Udalguri"},
{"Araria", "Arrah", "Arwal", "Aurangabad", "Banka", "Begusarai", "Bettiah", "Bhabua", "Bhagalpur", "Bihar Sharif", "Buxar", "Chhapra", "Darbhanga", "Gaya", "Gopalganj", "Hajipur", "Jamui", "Jehanabad", "Katihar", "Khagaria", "Kishanganj", "Lakhisarai", "Madhepura", "Madhubani", "Motihari", "Munger", "Muzaffarpur", "Nawada", "Patna", "Purnia", "Saharsa", "Samastipur", "Sasaram", "Sheikhpura", "Sheohar", "Sitamarhi", "Siwan", "Supaul"},
{"Chandigarh"},
{"Ambikapur", "Baikunthpur", "Balod", "Baloda Bazar", "Balrampur", "Bemetara", "Bijapur", "Bilaspur", "Dantewada", "Dhamtari", "Durg", "Gariaband", "Gaurela Pendra Marwahi", "Jagdalpur", "Jashpur Nagar", "Kanker", "Kawardha", "Kondagaon", "Korba", "Mahasamund", "Mungeli", "Naila Janjgir", "Narayanpur", "Raigarh", "Raipur", "Rajnandgaon", "Sukma", "Surajpur"},
{"Silvassa"},
{"Daman","Diu"},
{"Daryaganj", "Defence Colony", "Kanjhawala", "New Delhi", "Preet Vihar", "Rajouri Garden", "Sadar Bazaar", "Saket", "Shahdara", "Vasant Vihar"},
{"Margao","Panaji"},
{"Ahmedabad", "Ahwa", "Amreli", "Anand", "Bharuch", "Bhavnagar", "Bhuj", "Botad", "Chhota Udepur", "Dahod", "Gandhinagar", "Godhra", "Himatnagar", "Jamnagar", "Junagadh", "Khambhalia", "Lunavada", "Mehsana", "Modasa", "Morbi", "Nadiad", "Navsari", "Palanpur", "Patan", "Porbandar", "Rajkot", "Rajpipla", "Surat", "Surendranagar", "Vadodara", "Valsad", "Veraval", "Vyara"},
{"Ambala", "Bhiwani", "Charkhi Dadri", "Faridabad", "Fatehabad", "Gurgaon", "Hissar", "Jhajjar", "Jind", "Kaithal", "Karnal", "Kurukshetra", "Narnaul", "Nuh", "Palwal", "Panchkula", "Panipat", "Rewari", "Rohtak", "Sirsa", "Sonipat", "Yamuna Nagar"},
{"Bilaspur", "Chamba", "Dharamshala", "Hamirpur", "Keylong", "Kullu", "Mandi", "Nahan", "Reckong Peo", "Shimla", "Solan", "Una"},
{"Anantnag", "Badgam", "Bandipore", "Baramulla", "Doda", "Ganderbal", "Jammu", "Kargil", "Kathua", "Kishtwar", "Kulgam", "Kupwara", "Leh", "Poonch", "Pulwama", "Rajouri", "Ramban", "Reasi", "Samba", "Shupiyan", "Srinagar", "Udhampur"},
{"Bokaro", "Chaibasa", "Chatra", "Daltonganj", "Deoghar", "Dhanbad", "Dumka", "Garhwa", "Giridih", "Godda", "Gumla", "Hazaribag", "Jamshedpur", "Jamtara", "Khunti", "Koderma", "Latehar", "Lohardaga", "Pakur", "Ramgarh", "Ranchi", "Sahebganj", "Seraikela", "Simdega"},
{"Bagalkot", "Bangalore", "Belgaum", "Bellary", "Bengaluru", "Bidar", "Chamarajanagar", "Chikkaballapur", "Chikmagalur", "Chitradurga", "Davangere", "Dharwad", "Gadag Betageri", "Gulbarga", "Hassan", "Haveri", "Karwar", "Kolar", "Koppal", "Madikeri", "Mandya", "Mangalore", "Mysore", "Raichur", "Ramanagara", "Shimoga", "Tumkur", "Udupi", "Vijayapura", "Yadgir"},
{"Alappuzha", "Ernakulam", "Kalpetta", "Kannur", "Kasaragod", "Kollam", "Kottayam", "Kozhikode", "Malappuram", "Painavu", "Palakkad", "Pathanamthitta", "Thiruvananthapuram", "Thrissur"},
{"Kavaratti"},
{"Agar", "Alirajpur", "Anuppur", "Ashok Nagar", "Balaghat", "Barwani", "Betul", "Bhind", "Bhopal", "Burhanpur", "Chachaura", "Chhatarpur", "Chhindwara", "Damoh", "Datia", "Dewas", "Dhar", "Dindori", "Guna", "Gwalior", "Harda", "Hoshangabad", "Indore", "Jabalpur", "Jhabua", "Katni", "Khandwa", "Khargone", "Maihar", "Mandla", "Mandsaur", "Morena", "Nagda", "Narsinghpur", "Neemuch", "Niwari", "Panna", "Raisen", "Rajgarh", "Ratlam", "Rewa", "Sagar", "Satna", "Sehore", "Seoni", "Shahdol", "Shajapur", "Sheopur", "Shivpuri", "Sidhi", "Tikamgarh", "Ujjain", "Umaria", "Vidisha", "Waidhan"},
{"Ahmednagar", "Akola", "Alibag", "Amravati", "Aurangabad", "Bandra (East)", "Beed", "Bhandara", "Buldhana", "Chandrapur", "Dhule", "Gadchiroli", "Gondia", "Hingoli", "Jalgaon", "Jalna", "Kolhapur", "Latur", "Mumbai", "Nagpur", "Nanded", "Nandurbar", "Nashik", "Oros", "Osmanabad", "Palghar", "Parbhani", "Pune", "Ratnagiri", "Sangli", "Satara", "Solapur", "Thane", "Wardha", "Washim", "Yavatmal"},
{"Bishnupur", "Chandel", "Churachandpur", "Imphal", "Jiribam", "Kakching", "Kamjong", "Kangpokpi", "Noney Longmai", "Pherzawl", "Porompat", "Senapati", "Tamenglong", "Tengnoupal", "Thoubal", "Ukhrul"},
{"Ampati", "Baghmara", "Jowai", "Khleihriat", "Mawkyrwat", "Nongpoh", "Nongstoin", "Resubelpara", "Shillong", "Tura", "Williamnagar"},
{"Aizawl", "Champhai", "Kolasib", "Lawngtlai", "Lunglei", "Mamit", "Saiha", "Serchhip"},
{"Dimapur", "Kiphire", "Kohima", "Longleng", "Mokokchung", "Mon", "Noklak", "Peren", "Phek", "Tuensang", "Wokha", "Zunheboto"},
{"Angul", "Balangir", "Balasore", "Bargarh", "Baripada", "Bhadrak", "Bhawanipatna", "Bhubaneswar", "Boudh", "Chhatrapur", "Cuttack", "Debagarh", "Dhenkanal", "Jagatsinghpur", "Jharsuguda", "Kendrapara", "Kendujhar", "Koraput", "Malkangiri", "Nabarangpur", "Nayagarh", "Nuapada", "Panikoili", "Paralakhemundi", "Phulbani", "Puri", "Rayagada", "Sambalpur", "Subarnapur", "Sundargarh"},
{"Karaikal","Mahe","Pondicherry","Yanam"},
{"Amritsar", "Barnala", "Bathinda", "Faridkot", "Fatehgarh Sahib", "Fazilka", "Firozpur", "Gurdaspur", "Hoshiarpur", "Jalandhar", "Kapurthala", "Ludhiana", "Mansa", "Moga", "Mohali", "Nawanshahr", "Pathankot", "Patiala", "Rupnagar", "Sangrur", "Sri Muktsar Sahib", "Tarn Taran Sahib"},
{"Ajmer", "Alwar", "Banswara", "Baran", "Barmer", "Bharatpur", "Bhilwara", "Bikaner", "Bundi", "Chittorgarh", "Churu", "Dausa", "Dholpur", "Dungarpur", "Ganganagar", "Hanumangarh", "Jaipur", "Jaisalmer", "Jalore", "Jhalawar", "Jhunjhunu", "Jodhpur", "Karauli", "Kota", "Nagaur", "Pali", "Pratapgarh", "Rajsamand", "Sawai Madhopur", "Sikar", "Sirohi", "Tonk", "Udaipur"},
{"Gangtok", "Geyzing", "Mangan", "Namchi"},
{"Ariyalur", "Chengalpattu", "Chennai", "Coimbatore", "Cuddalore", "Dharmapuri", "Dindigul", "Erode", "Hosur", "Kallakurichi", "Kanchipuram", "Karur", "Krishnagiri", "Madurai", "Mayiladuthurai", "Nagapattinam", "Nagercoil", "Namakkal", "Perambalur", "Pudukkottai", "Ramanathapuram", "Ranipet", "Salem", "Sivaganga", "Tenkasi", "Thanjavur", "Theni", "Thoothukudi", "Thoothukudi (Tuticorin)", "Tiruchirappalli", "Tirunelveli", "Tirupattur", "Tirupur", "Tiruvallur", "Tiruvannaamalai", "Tiruvarur", "Udagamandalam (Ooty)", "Vellore", "Viluppuram", "Virudhunagar"},
{"Adilabad", "Bhongiri", "Bhupalpalle", "Gadwal", "Geesugonda", "Hyderabad", "Jagtial", "Jangaon", "Kamareddy", "Karimnagar", "Khammam", "Komaram Bheem", "Kothagudem", "Mahabubabad", "Mahbubnagar", "Mancherial", "Medak", "Mulugu", "Nagarkurnool", "Nalgonda", "Narayanpet", "Nirmal", "Nizamabad", "Peddapalle", "Sangareddy", "Shamirpet", "Shamshabad", "Siddipet", "Sircilla", "Suryapet", "Vikarabad", "Wanaparthy", "Warangal"},
{"Agartala", "Ambassa", "Belonia", "Bishramganj", "Dharmanagar", "Kailashahar", "Khowai", "Udaipur Tripura"},
{"Agra", "Akbarpur", "Akbarpur (Mati)", "Aligarh", "Allahabad", "Amroha", "Auraiya", "Azamgarh", "Baghpat", "Bahraich", "Ballia", "Balrampur", "Banda", "Barabanki", "Bareilly", "Basti", "Bijnor", "Budaun", "Bulandshahr", "Chandauli", "Deoria", "Etah", "Etawah", "Faizabad", "Fatehgarh", "Fatehpur", "Firozabad", "Gauriganj", "Ghaziabad", "Ghazipur", "Gonda", "Gorakhpur", "Gyanpur", "Hamirpur", "Hapur", "Hardoi", "Hathras", "Jaunpur", "Jhansi", "Kannauj", "Kanpur", "Karwi", "Kasganj", "Khalilabad", "Lakhimpur", "Lalitpur", "Lucknow", "Maharajganj", "Mahoba", "Mainpuri", "Manjhanpur", "Mathura", "Mau", "Meerut", "Mirzapur", "Moradabad", "Muzaffarnagar", "Naugarh", "Noida", "Orai", "Padrauna", "Pilibhit", "Pratapgarh", "Raebareli", "Rampur", "Robertsganj", "Saharanpur", "Sambhal", "Shahjahanpur", "Shamli", "Shravasti", "Sitapur", "Sultanpur", "Unnao", "Varanasi"},
{"Almora", "Bageshwar", "Champawat", "Dehradun", "Gopeshwar", "Haridwar", "Nainital", "New Tehri", "Pauri", "Pithoragarh", "Rudraprayag", "Rudrapur", "Uttarkashi"},
{"Alipore", "Alipurduar", "Baharampur", "Balurghat", "Bankura", "Barasat", "Bardhaman", "Chinsurah", "Cooch Behar", "Darjeeling", "English Bazar", "Howrah", "Jalpaiguri", "Kolkata", "Krishnanagar", "Midnapore", "Purulia", "Raiganj", "Suri", "Tamluk"}
};
ArrayAdapter<String> userStateAdapter;
Button btn;
// private AViewModel aViewModel;
private int onViewStateRestoredCallBack = 0;
private String selectedUserState = "Select";
private String selectedUserCity = "Select";
private Switch soundToggle;
private SoundManager soundManager;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_d, container, false);
if(!InternetConnectivityUtil.isConnected(getContext())) {
InternetConnectivityUtil.closeApp(getContext(), this.getActivity());
}
for (int i = 0; i < STATES.length; i++) {
stateIndexMap.put(STATES[i], i);
}
soundToggle = view.findViewById(R.id.soundToggle);
soundManager = SoundManager.getInstance(requireContext());
retrieveSoundToggle();
loadStatesArray();
autoCompleteTextView = view.findViewById(R.id.auto_complete_text);
adapterItems = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, STATES);
autoCompleteTextView.setAdapter(adapterItems);
// For city
autoCompleteTextView1 = view.findViewById(R.id.auto_complete_text_city);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
saveSelectedUserState(item); saveSelectedUserCity("");
autoCompleteTextView1.setText("");
autoCompleteTextView.setText(item);
autoCompleteTextView.setSelection(item.length());
int index = stateIndexMap.get(item);
System.out.println("Saved index: " + index);
saveStatePosition(index);
saveStateChangeFlag(true);
saveStateChangeFlag_B_o(true);
Toast.makeText(getContext(), "State: " + item, Toast.LENGTH_SHORT).show();
String[] filteredCities = filterCitiesByState(index);
// System.out.println("Cities list");
// for(String s: filter)
adapterItems1 = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, filteredCities);
autoCompleteTextView1.setAdapter(adapterItems1);
}
});
if(retrieveStatePosition() != -1){
System.out.println("Retrieved index: " + retrieveStatePosition());
String[] filteredCities = filterCitiesByState(retrieveStatePosition());
adapterItems1 = new ArrayAdapter<String>(getContext(), R.layout.custom_drop_down, filteredCities);
autoCompleteTextView1.setAdapter(adapterItems1);
}
autoCompleteTextView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
saveSelectedUserCity(item);
autoCompleteTextView1.setText(item); autoCompleteTextView1.setSelection(item.length());
saveStateChangeFlag(true); saveStateChangeFlag_B_o(true);
Toast.makeText(getContext(), "City: " + item, Toast.LENGTH_SHORT).show();
}
});
soundToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) soundManager.enableSound(); // Enable sound
else soundManager.disableSound(); // Disable sound
storingSoundToggle();
}
});
return view;
}
private void loadStatesArray() {
states = Arrays.asList(new String[]{"Andaman and Nicobar", "Andhra Pradesh", "Arunachal Pradesh", "Assam", "Bihar", "Chandigarh", "Chhattisgarh", "Dadra and Nagar Haveli", "Daman and Diu", "Delhi", "Goa", "Gujarat", "Haryana", "Himachal Pradesh", "Jammu and Kashmir", "Jharkhand", "Karnataka", "Kerala", "Lakshadweep", "Madhya Pradesh", "Maharashtra", "Manipur", "Meghalaya", "Mizoram", "Nagaland", "Odisha", "Puducherry",
"Punjab", "Rajasthan", "Sikkim", "Tamil Nadu", "Telangana", "Tripura", "Uttar Pradesh", "Uttarakhand", "West Bengal"});
}
String[] filterCitiesByState (int index){
return CITIES[index];
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getId() == R.id.presentStateSpinner1) {
selectedUserState = parent.getItemAtPosition(position).toString();
saveSelectedUserState(selectedUserState);
autoCompleteTextView.setText(selectedUserState);
autoCompleteTextView.setSelection(selectedUserState.length());
System.out.println("onItemSelected() > " + selectedUserState);
if(onViewStateRestoredCallBack == 0){
saveStateChangeFlag(true); saveStateChangeFlag_B_o(true);
}
onViewStateRestoredCallBack = 0;
}
}
private void saveStatePosition(int flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("Position_flag " + flag);
editor.putInt("state_change_position", flag);
editor.apply();
}
private int retrieveStatePosition() {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
return sharedPreferences.getInt("state_change_position", -1);
}
private void saveStateChangeFlag(boolean flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("flag " + flag);
editor.putBoolean("state_change_flag", flag);
editor.apply();
}
private void saveStateChangeFlag_B_o(boolean flag) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
System.out.println("flag_B_o " + flag);
editor.putBoolean("state_change_flag_B_o", flag);
editor.apply();
}
private void saveSelectedUserState(String selectedUserState) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("selected_userState", selectedUserState);
editor.apply();
}
private void saveSelectedUserCity(String selectedUserCity) {
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("selected_userCity", selectedUserCity);
editor.apply();
}
//
// @Override
public void onNothingSelected(AdapterView<?> parent) {
System.out.println("onNothingSelected() ");
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
selectedUserState = sharedPreferences.getString("selected_userState", "Telangana");
autoCompleteTextView.setText(selectedUserState);
autoCompleteTextView.setSelection(selectedUserState.length());
selectedUserCity = sharedPreferences.getString("selected_userCity", "Kamareddy");
autoCompleteTextView1.setText(selectedUserCity);
autoCompleteTextView1.setSelection(selectedUserCity.length());
}
public void storingSoundToggle(){
// Get a reference to the SharedPreferences
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Get the SharedPreferences editor
SharedPreferences.Editor editor = sharedPreferences.edit();
// Get the current state of the soundToggle and store it
boolean isSoundEnabled = soundManager.isSoundEnabled();
editor.putBoolean("soundEnabled", isSoundEnabled);
// Apply the changes
editor.apply();
}
public void retrieveSoundToggle(){
// Get a reference to the SharedPreferences
SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
// Retrieve the stored boolean value
boolean isSoundEnabled = sharedPreferences.getBoolean("soundEnabled", true); // Default value<SUF>
// Set the soundToggle based on the retrieved value
soundToggle.setChecked(isSoundEnabled);
}
}
| False |
2,563 | 69191_0 | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de score met berekening A
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| diorcula/OOAD_casestudy-parola | source/src/nl/han/Antwoordformulier.java | 293 | //Bereken de score met berekening A | line_comment | nl | package nl.han;
import java.util.ArrayList;
public class Antwoordformulier {
private ArrayList<String> gegevenAntwoorden;
private int aantalGoed;
private Score score;
private Long startTijd;
public Antwoordformulier(){
gegevenAntwoorden = new ArrayList<>();
score = new Score();
startTijd = System.currentTimeMillis();
aantalGoed = 0;
}
public void vraagGoed(){ aantalGoed++;};
public void addAntwoord(String gegevenAntwoord){
gegevenAntwoorden.add(gegevenAntwoord);
}
public String getAntwoord(int i){
return gegevenAntwoorden.get(i);
}
public void maakWoord(String woord){
score.checkWoord(woord);
}
public int berekenScore(Berekening berekening){
var verstrekenTijd = System.currentTimeMillis() - startTijd;
//Bereken de<SUF>
return score.berekenScore(berekening, verstrekenTijd, aantalGoed);
}
}
| True |
4,279 | 118739_2 | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.selendroid.server.handler;
import io.selendroid.server.common.Response;
import io.selendroid.server.common.SelendroidResponse;
import io.selendroid.server.common.http.HttpRequest;
import io.selendroid.server.model.AndroidElement;
import io.selendroid.server.model.Session;
import io.selendroid.server.util.SelendroidLogger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Send keys to a given element.
*/
public class SendKeysToElement extends SafeRequestHandler {
public SendKeysToElement(String mappedUri) {
super(mappedUri);
}
@Override
public Response safeHandle(HttpRequest request) throws JSONException {
SelendroidLogger.info("send keys to element command");
String id = getElementId(request);
AndroidElement element = getElementFromCache(request, id);
String[] keysToSend = extractKeysToSendFromPayload(request);
if (isNativeEvents(request)) {
element.enterText(keysToSend);
}else{
element.setText(keysToSend);
}
return new SelendroidResponse(getSessionId(request), "");
}
boolean isNativeEvents(HttpRequest request) {
JSONObject config =
getSelendroidDriver(request).getSession().getCommandConfiguration(
Session.SEND_KEYS_TO_ELEMENT);
if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) {
try {
return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY);
} catch (JSONException e) {}
}
// default is native events
return true;
}
}
| selendroid/selendroid | selendroid-server/src/main/java/io/selendroid/server/handler/SendKeysToElement.java | 608 | // default is native events | line_comment | nl | /*
* Copyright 2012-2014 eBay Software Foundation and selendroid committers.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package io.selendroid.server.handler;
import io.selendroid.server.common.Response;
import io.selendroid.server.common.SelendroidResponse;
import io.selendroid.server.common.http.HttpRequest;
import io.selendroid.server.model.AndroidElement;
import io.selendroid.server.model.Session;
import io.selendroid.server.util.SelendroidLogger;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Send keys to a given element.
*/
public class SendKeysToElement extends SafeRequestHandler {
public SendKeysToElement(String mappedUri) {
super(mappedUri);
}
@Override
public Response safeHandle(HttpRequest request) throws JSONException {
SelendroidLogger.info("send keys to element command");
String id = getElementId(request);
AndroidElement element = getElementFromCache(request, id);
String[] keysToSend = extractKeysToSendFromPayload(request);
if (isNativeEvents(request)) {
element.enterText(keysToSend);
}else{
element.setText(keysToSend);
}
return new SelendroidResponse(getSessionId(request), "");
}
boolean isNativeEvents(HttpRequest request) {
JSONObject config =
getSelendroidDriver(request).getSession().getCommandConfiguration(
Session.SEND_KEYS_TO_ELEMENT);
if (config != null && config.has(Session.NATIVE_EVENTS_PROPERTY)) {
try {
return config.getBoolean(Session.NATIVE_EVENTS_PROPERTY);
} catch (JSONException e) {}
}
// default is<SUF>
return true;
}
}
| False |
276 | 141676_10 | /***************************************************************************
* (C) Copyright 2003-2022 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(
new QuestActiveCondition("campfire"),
new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan city gardens
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start"))
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom")
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| C8620/stendhal | src/games/stendhal/server/core/rp/achievement/factory/FriendAchievementFactory.java | 1,834 | // Annie, Kalavan city gardens | line_comment | nl | /***************************************************************************
* (C) Copyright 2003-2022 - Stendhal *
***************************************************************************
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
package games.stendhal.server.core.rp.achievement.factory;
import java.util.Collection;
import java.util.LinkedList;
import games.stendhal.common.parser.Sentence;
import games.stendhal.server.core.rp.achievement.Achievement;
import games.stendhal.server.core.rp.achievement.Category;
import games.stendhal.server.core.rp.achievement.condition.QuestWithPrefixCompletedCondition;
import games.stendhal.server.entity.Entity;
import games.stendhal.server.entity.npc.ChatCondition;
import games.stendhal.server.entity.npc.condition.AndCondition;
import games.stendhal.server.entity.npc.condition.QuestActiveCondition;
import games.stendhal.server.entity.npc.condition.QuestCompletedCondition;
import games.stendhal.server.entity.npc.condition.QuestNotInStateCondition;
import games.stendhal.server.entity.npc.condition.QuestStartedCondition;
import games.stendhal.server.entity.npc.condition.QuestStateStartsWithCondition;
import games.stendhal.server.entity.player.Player;
/**
* Factory for quest achievements
*
* @author kymara
*/
public class FriendAchievementFactory extends AbstractAchievementFactory {
public static final String ID_CHILD_FRIEND = "friend.quests.children";
public static final String ID_PRIVATE_DETECTIVE = "friend.quests.find";
public static final String ID_GOOD_SAMARITAN = "friend.karma.250";
public static final String ID_STILL_BELIEVING = "friend.meet.seasonal";
@Override
protected Category getCategory() {
return Category.FRIEND;
}
@Override
public Collection<Achievement> createAchievements() {
final LinkedList<Achievement> achievements = new LinkedList<Achievement>();
// TODO: add Pacifist achievement for not participating in pvp for 6 months or more (last_pvp_action_time)
// Befriend Susi and complete quests for all children
achievements.add(createAchievement(
ID_CHILD_FRIEND, "Childrens' Friend",
"Complete quests for all children",
Achievement.MEDIUM_BASE_SCORE, true,
new AndCondition(
// Susi Quest is never set to done, therefore we check just if the quest has been started (condition "anyFriends" from FoundGirl.java)
new QuestStartedCondition("susi"),
// Help Tad, Semos Town Hall (Medicine for Tad)
new QuestCompletedCondition("introduce_players"),
// Plink, Semos Plains North
new QuestCompletedCondition("plinks_toy"),
// Anna, in Ados
new QuestCompletedCondition("toys_collector"),
// Sally, Orril River
// 'completed' doesn't work for Sally - return player.hasQuest(QUEST_SLOT) && !"start".equals(player.getQuest(QUEST_SLOT)) && !"rejected".equals(player.getQuest(QUEST_SLOT));
new AndCondition(
new QuestActiveCondition("campfire"),
new QuestNotInStateCondition("campfire", "start")),
// Annie, Kalavan<SUF>
new QuestStateStartsWithCondition("icecream_for_annie","eating;"),
// Elisabeth, Kirdneh
new QuestStateStartsWithCondition("chocolate_for_elisabeth","eating;"),
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom"),
// Hughie, Ados farmhouse
new AndCondition(
new QuestActiveCondition("fishsoup_for_hughie"),
new QuestNotInStateCondition("fishsoup_for_hughie", "start")),
// Finn Farmer, George
new QuestCompletedCondition("coded_message"),
// Marianne, Deniran City S
new AndCondition(
new QuestActiveCondition("eggs_for_marianne"),
new QuestNotInStateCondition("eggs_for_marianne", "start"))
)));
// quests about finding people
achievements.add(createAchievement(
ID_PRIVATE_DETECTIVE, "Private Detective",
"Find all lost and hidden people",
Achievement.HARD_BASE_SCORE, true,
new AndCondition(
// Rat Children (Agnus)
new QuestCompletedCondition("find_rat_kids"),
// Find Ghosts (Carena)
new QuestCompletedCondition("find_ghosts"),
// Meet Angels (any of the cherubs)
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
if (!player.hasQuest("seven_cherubs")) {
return false;
}
final String npcDoneText = player.getQuest("seven_cherubs");
final String[] done = npcDoneText.split(";");
final int left = 7 - done.length;
return left < 0;
}
},
// Jef, Kirdneh
new QuestCompletedCondition("find_jefs_mom")
)));
// earn over 250 karma
achievements.add(createAchievement(
ID_GOOD_SAMARITAN, "Good Samaritan",
"Earn a very good karma",
Achievement.MEDIUM_BASE_SCORE, true,
new ChatCondition() {
@Override
public boolean fire(final Player player, final Sentence sentence, final Entity entity) {
return player.getKarma() > 250;
}
}));
// meet Santa Claus and Easter Bunny
achievements.add(createAchievement(
ID_STILL_BELIEVING, "Still Believing",
"Meet Santa Claus and Easter Bunny",
Achievement.EASY_BASE_SCORE, true,
new AndCondition(
new QuestWithPrefixCompletedCondition("meet_santa_"),
new QuestWithPrefixCompletedCondition("meet_bunny_"))));
return achievements;
}
}
| False |
1,989 | 192437_0 | package com.aivarsliepa.budgetappapi.integrationtests;
import com.aivarsliepa.budgetappapi.constants.URLPaths;
import com.aivarsliepa.budgetappapi.data.payloads.JwtAuthResponseBody;
import com.aivarsliepa.budgetappapi.data.payloads.LoginRequestBody;
import com.aivarsliepa.budgetappapi.data.payloads.RegisterRequestBody;
import com.aivarsliepa.budgetappapi.data.user.UserModel;
import com.aivarsliepa.budgetappapi.data.user.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static io.jsonwebtoken.lang.Assert.hasText;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class AuthTest {
private static final String REGISTER_URL = URLPaths.Auth.BASE + URLPaths.Auth.REGISTER;
private static final String LOGIN_URL = URLPaths.Auth.BASE + URLPaths.Auth.LOGIN;
private static final String USERNAME_1 = "username_1";
private static final String PASSWORD_1 = "password_1";
private static final String PASSWORD_2 = "password_2";
@Autowired
private MockMvc mvc;
@Autowired
private UserRepository userRepository;
@Autowired
private ObjectMapper mapper;
@Autowired
private PasswordEncoder passwordEncoder;
@Before
public void setUp() {
userRepository.deleteAll();
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
@Test
public void register_happyPath() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
var response = mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
// validate that registered user is persisted
var persistedUserOpt = userRepository.findByUsername(USERNAME_1);
if (persistedUserOpt.isEmpty()) {
fail("User not persisted");
}
assertEquals(persistedUserOpt.get().getUsername(), USERNAME_1);
}
@Test
public void register_invalidInputData_usernameNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_usernameEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername("");
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setPassword("");
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword("");
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordsDoesNotMatch() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_usernameAlreadyExists() throws Exception {
// make sure user exists
var existingUser = new UserModel();
var encodedPassword = passwordEncoder.encode(PASSWORD_1);
existingUser.setPassword(encodedPassword);
existingUser.setUsername(USERNAME_1);
userRepository.save(existingUser);
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
// verify that user count is still 1
var userList = userRepository.findAll();
assertEquals(1, userList.size());
// verify that user password was not overwritten
var user = userRepository.findByUsername(USERNAME_1);
if (user.isEmpty()) {
fail("User should be not be empty!");
}
assertEquals(encodedPassword, user.get().getPassword());
}
@Test
public void login_happyPath() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
var response = mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
}
@Test
public void login_invalidPassword() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isUnauthorized())
.andExpect(content().string(""));
}
}
| aivarsliepa/budget-app-api | src/test/java/com/aivarsliepa/budgetappapi/integrationtests/AuthTest.java | 2,840 | // validate jwt is in response | line_comment | nl | package com.aivarsliepa.budgetappapi.integrationtests;
import com.aivarsliepa.budgetappapi.constants.URLPaths;
import com.aivarsliepa.budgetappapi.data.payloads.JwtAuthResponseBody;
import com.aivarsliepa.budgetappapi.data.payloads.LoginRequestBody;
import com.aivarsliepa.budgetappapi.data.payloads.RegisterRequestBody;
import com.aivarsliepa.budgetappapi.data.user.UserModel;
import com.aivarsliepa.budgetappapi.data.user.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static io.jsonwebtoken.lang.Assert.hasText;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:application-integrationtest.properties")
public class AuthTest {
private static final String REGISTER_URL = URLPaths.Auth.BASE + URLPaths.Auth.REGISTER;
private static final String LOGIN_URL = URLPaths.Auth.BASE + URLPaths.Auth.LOGIN;
private static final String USERNAME_1 = "username_1";
private static final String PASSWORD_1 = "password_1";
private static final String PASSWORD_2 = "password_2";
@Autowired
private MockMvc mvc;
@Autowired
private UserRepository userRepository;
@Autowired
private ObjectMapper mapper;
@Autowired
private PasswordEncoder passwordEncoder;
@Before
public void setUp() {
userRepository.deleteAll();
}
@After
public void cleanUp() {
userRepository.deleteAll();
}
@Test
public void register_happyPath() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
var response = mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt<SUF>
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
// validate that registered user is persisted
var persistedUserOpt = userRepository.findByUsername(USERNAME_1);
if (persistedUserOpt.isEmpty()) {
fail("User not persisted");
}
assertEquals(persistedUserOpt.get().getUsername(), USERNAME_1);
}
@Test
public void register_invalidInputData_usernameNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordNull() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_usernameEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername("");
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setUsername(USERNAME_1);
requestBody.setPassword("");
requestBody.setConfirmPassword(PASSWORD_1);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_confirmPasswordEmpty() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword("");
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_invalidInputData_passwordsDoesNotMatch() throws Exception {
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
}
@Test
public void register_usernameAlreadyExists() throws Exception {
// make sure user exists
var existingUser = new UserModel();
var encodedPassword = passwordEncoder.encode(PASSWORD_1);
existingUser.setPassword(encodedPassword);
existingUser.setUsername(USERNAME_1);
userRepository.save(existingUser);
var requestBody = new RegisterRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
requestBody.setConfirmPassword(PASSWORD_2);
mvc.perform(post(REGISTER_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isBadRequest())
.andExpect(content().string(""));
// verify that user count is still 1
var userList = userRepository.findAll();
assertEquals(1, userList.size());
// verify that user password was not overwritten
var user = userRepository.findByUsername(USERNAME_1);
if (user.isEmpty()) {
fail("User should be not be empty!");
}
assertEquals(encodedPassword, user.get().getPassword());
}
@Test
public void login_happyPath() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_1);
requestBody.setUsername(USERNAME_1);
var response = mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
// validate jwt is in response
var responseBody = mapper.readValue(response, JwtAuthResponseBody.class);
hasText(responseBody.getToken());
}
@Test
public void login_invalidPassword() throws Exception {
// make sure user exists
var user = new UserModel();
user.setPassword(passwordEncoder.encode(PASSWORD_1));
user.setUsername(USERNAME_1);
userRepository.save(user);
var requestBody = new LoginRequestBody();
requestBody.setPassword(PASSWORD_2);
requestBody.setUsername(USERNAME_1);
mvc.perform(post(LOGIN_URL)
.content(mapper.writeValueAsString(requestBody))
.contentType(MediaType.APPLICATION_JSON_UTF8))
.andExpect(status().isUnauthorized())
.andExpect(content().string(""));
}
}
| False |
4,752 | 16548_3 | /*--------------------------------------------------------------------------
* Copyright 2008 Taro L. Saito
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
// --------------------------------------
// sqlite-jdbc Project
//
// OSInfo.java
// Since: May 20, 2008
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Locale;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides OS name and architecture name.
*
* @author leo
*/
public class OSInfo {
protected static ProcessRunner processRunner = new ProcessRunner();
private static final HashMap<String, String> archMapping = new HashMap<>();
public static final String X86 = "x86";
public static final String X86_64 = "x86_64";
public static final String IA64_32 = "ia64_32";
public static final String IA64 = "ia64";
public static final String PPC = "ppc";
public static final String PPC64 = "ppc64";
static {
// x86 mappings
archMapping.put(X86, X86);
archMapping.put("i386", X86);
archMapping.put("i486", X86);
archMapping.put("i586", X86);
archMapping.put("i686", X86);
archMapping.put("pentium", X86);
// x86_64 mappings
archMapping.put(X86_64, X86_64);
archMapping.put("amd64", X86_64);
archMapping.put("em64t", X86_64);
archMapping.put("universal", X86_64); // Needed for openjdk7 in Mac
// Itanium 64-bit mappings
archMapping.put(IA64, IA64);
archMapping.put("ia64w", IA64);
// Itanium 32-bit mappings, usually an HP-UX construct
archMapping.put(IA64_32, IA64_32);
archMapping.put("ia64n", IA64_32);
// PowerPC mappings
archMapping.put(PPC, PPC);
archMapping.put("power", PPC);
archMapping.put("powerpc", PPC);
archMapping.put("power_pc", PPC);
archMapping.put("power_rs", PPC);
// TODO: PowerPC 64bit mappings
archMapping.put(PPC64, PPC64);
archMapping.put("power64", PPC64);
archMapping.put("powerpc64", PPC64);
archMapping.put("power_pc64", PPC64);
archMapping.put("power_rs64", PPC64);
archMapping.put("ppc64el", PPC64);
archMapping.put("ppc64le", PPC64);
}
public static void main(String[] args) {
if (args.length >= 1) {
if ("--os".equals(args[0])) {
System.out.print(getOSName());
return;
} else if ("--arch".equals(args[0])) {
System.out.print(getArchName());
return;
}
}
System.out.print(getNativeLibFolderPathForCurrentOS());
}
public static String getNativeLibFolderPathForCurrentOS() {
return getOSName() + "/" + getArchName();
}
public static String getOSName() {
return translateOSNameToFolderName(System.getProperty("os.name"));
}
public static boolean isAndroid() {
return isAndroidRuntime() || isAndroidTermux();
}
public static boolean isAndroidRuntime() {
return System.getProperty("java.runtime.name", "").toLowerCase().contains("android");
}
public static boolean isAndroidTermux() {
try {
return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android");
} catch (Exception ignored) {
return false;
}
}
public static boolean isMusl() {
Path mapFilesDir = Paths.get("/proc/self/map_files");
try (Stream<Path> dirStream = Files.list(mapFilesDir)) {
return dirStream
.map(
path -> {
try {
return path.toRealPath().toString();
} catch (IOException e) {
return "";
}
})
.anyMatch(s -> s.toLowerCase().contains("musl"));
} catch (Exception ignored) {
// fall back to checking for alpine linux in the event we're using an older kernel which
// may not fail the above check
return isAlpineLinux();
}
}
private static boolean isAlpineLinux() {
try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) {
return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine"));
} catch (Exception ignored2) {
}
return false;
}
static String getHardwareName() {
try {
return processRunner.runAndWaitFor("uname -m");
} catch (Throwable e) {
LogHolder.logger.error("Error while running uname -m", e);
return "unknown";
}
}
static String resolveArmArchType() {
if (System.getProperty("os.name").contains("Linux")) {
String armType = getHardwareName();
// armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l,
// aarch64, i686
// for Android, we fold everything that is not aarch64 into arm
if (isAndroid()) {
if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
} else {
return "arm";
}
}
if (armType.startsWith("armv6")) {
// Raspberry PI
return "armv6";
} else if (armType.startsWith("armv7")) {
// Generic
return "armv7";
} else if (armType.startsWith("armv5")) {
// Use armv5, soft-float ABI
return "arm";
} else if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
}
// Java 1.8 introduces a system property to determine armel or armhf
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545
String abi = System.getProperty("sun.arch.abi");
if (abi != null && abi.startsWith("gnueabihf")) {
return "armv7";
}
// For java7, we still need to run some shell commands to determine ABI of JVM
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if (exitCode == 0) {
String[] cmdarray = {
"/bin/sh",
"-c",
"find '"
+ javaHome
+ "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ "grep 'Tag_ABI_VFP_args: VFP registers'"
};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return "armv7";
}
} else {
LogHolder.logger.warn(
"readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed");
}
} catch (IOException | InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
// Use armv5, soft-float ABI
return "arm";
}
public static String getArchName() {
String override = System.getProperty("org.sqlite.osinfo.architecture");
if (override != null) {
return override;
}
String osArch = System.getProperty("os.arch");
if (osArch.startsWith("arm")) {
osArch = resolveArmArchType();
} else {
String lc = osArch.toLowerCase(Locale.US);
if (archMapping.containsKey(lc)) return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
static String translateOSNameToFolderName(String osName) {
if (osName.contains("Windows")) {
return "Windows";
} else if (osName.contains("Mac") || osName.contains("Darwin")) {
return "Mac";
} else if (osName.contains("AIX")) {
return "AIX";
} else if (isMusl()) {
return "Linux-Musl";
} else if (isAndroid()) {
return "Linux-Android";
} else if (osName.contains("Linux")) {
return "Linux";
} else {
return osName.replaceAll("\\W", "");
}
}
static String translateArchNameToFolderName(String archName) {
return archName.replaceAll("\\W", "");
}
/**
* Class-wrapper around the logger object to avoid build-time initialization of the logging
* framework in native-image
*/
private static class LogHolder {
private static final Logger logger = LoggerFactory.getLogger(OSInfo.class);
}
}
| xerial/sqlite-jdbc | src/main/java/org/sqlite/util/OSInfo.java | 2,785 | // Needed for openjdk7 in Mac | line_comment | nl | /*--------------------------------------------------------------------------
* Copyright 2008 Taro L. Saito
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*--------------------------------------------------------------------------*/
// --------------------------------------
// sqlite-jdbc Project
//
// OSInfo.java
// Since: May 20, 2008
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite.util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Locale;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides OS name and architecture name.
*
* @author leo
*/
public class OSInfo {
protected static ProcessRunner processRunner = new ProcessRunner();
private static final HashMap<String, String> archMapping = new HashMap<>();
public static final String X86 = "x86";
public static final String X86_64 = "x86_64";
public static final String IA64_32 = "ia64_32";
public static final String IA64 = "ia64";
public static final String PPC = "ppc";
public static final String PPC64 = "ppc64";
static {
// x86 mappings
archMapping.put(X86, X86);
archMapping.put("i386", X86);
archMapping.put("i486", X86);
archMapping.put("i586", X86);
archMapping.put("i686", X86);
archMapping.put("pentium", X86);
// x86_64 mappings
archMapping.put(X86_64, X86_64);
archMapping.put("amd64", X86_64);
archMapping.put("em64t", X86_64);
archMapping.put("universal", X86_64); // Needed for<SUF>
// Itanium 64-bit mappings
archMapping.put(IA64, IA64);
archMapping.put("ia64w", IA64);
// Itanium 32-bit mappings, usually an HP-UX construct
archMapping.put(IA64_32, IA64_32);
archMapping.put("ia64n", IA64_32);
// PowerPC mappings
archMapping.put(PPC, PPC);
archMapping.put("power", PPC);
archMapping.put("powerpc", PPC);
archMapping.put("power_pc", PPC);
archMapping.put("power_rs", PPC);
// TODO: PowerPC 64bit mappings
archMapping.put(PPC64, PPC64);
archMapping.put("power64", PPC64);
archMapping.put("powerpc64", PPC64);
archMapping.put("power_pc64", PPC64);
archMapping.put("power_rs64", PPC64);
archMapping.put("ppc64el", PPC64);
archMapping.put("ppc64le", PPC64);
}
public static void main(String[] args) {
if (args.length >= 1) {
if ("--os".equals(args[0])) {
System.out.print(getOSName());
return;
} else if ("--arch".equals(args[0])) {
System.out.print(getArchName());
return;
}
}
System.out.print(getNativeLibFolderPathForCurrentOS());
}
public static String getNativeLibFolderPathForCurrentOS() {
return getOSName() + "/" + getArchName();
}
public static String getOSName() {
return translateOSNameToFolderName(System.getProperty("os.name"));
}
public static boolean isAndroid() {
return isAndroidRuntime() || isAndroidTermux();
}
public static boolean isAndroidRuntime() {
return System.getProperty("java.runtime.name", "").toLowerCase().contains("android");
}
public static boolean isAndroidTermux() {
try {
return processRunner.runAndWaitFor("uname -o").toLowerCase().contains("android");
} catch (Exception ignored) {
return false;
}
}
public static boolean isMusl() {
Path mapFilesDir = Paths.get("/proc/self/map_files");
try (Stream<Path> dirStream = Files.list(mapFilesDir)) {
return dirStream
.map(
path -> {
try {
return path.toRealPath().toString();
} catch (IOException e) {
return "";
}
})
.anyMatch(s -> s.toLowerCase().contains("musl"));
} catch (Exception ignored) {
// fall back to checking for alpine linux in the event we're using an older kernel which
// may not fail the above check
return isAlpineLinux();
}
}
private static boolean isAlpineLinux() {
try (Stream<String> osLines = Files.lines(Paths.get("/etc/os-release"))) {
return osLines.anyMatch(l -> l.startsWith("ID") && l.contains("alpine"));
} catch (Exception ignored2) {
}
return false;
}
static String getHardwareName() {
try {
return processRunner.runAndWaitFor("uname -m");
} catch (Throwable e) {
LogHolder.logger.error("Error while running uname -m", e);
return "unknown";
}
}
static String resolveArmArchType() {
if (System.getProperty("os.name").contains("Linux")) {
String armType = getHardwareName();
// armType (uname -m) can be armv5t, armv5te, armv5tej, armv5tejl, armv6, armv7, armv7l,
// aarch64, i686
// for Android, we fold everything that is not aarch64 into arm
if (isAndroid()) {
if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
} else {
return "arm";
}
}
if (armType.startsWith("armv6")) {
// Raspberry PI
return "armv6";
} else if (armType.startsWith("armv7")) {
// Generic
return "armv7";
} else if (armType.startsWith("armv5")) {
// Use armv5, soft-float ABI
return "arm";
} else if (armType.startsWith("aarch64")) {
// Use arm64
return "aarch64";
}
// Java 1.8 introduces a system property to determine armel or armhf
// http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8005545
String abi = System.getProperty("sun.arch.abi");
if (abi != null && abi.startsWith("gnueabihf")) {
return "armv7";
}
// For java7, we still need to run some shell commands to determine ABI of JVM
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if (exitCode == 0) {
String[] cmdarray = {
"/bin/sh",
"-c",
"find '"
+ javaHome
+ "' -name 'libjvm.so' | head -1 | xargs readelf -A | "
+ "grep 'Tag_ABI_VFP_args: VFP registers'"
};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return "armv7";
}
} else {
LogHolder.logger.warn(
"readelf not found. Cannot check if running on an armhf system, armel architecture will be presumed");
}
} catch (IOException | InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
// Use armv5, soft-float ABI
return "arm";
}
public static String getArchName() {
String override = System.getProperty("org.sqlite.osinfo.architecture");
if (override != null) {
return override;
}
String osArch = System.getProperty("os.arch");
if (osArch.startsWith("arm")) {
osArch = resolveArmArchType();
} else {
String lc = osArch.toLowerCase(Locale.US);
if (archMapping.containsKey(lc)) return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
static String translateOSNameToFolderName(String osName) {
if (osName.contains("Windows")) {
return "Windows";
} else if (osName.contains("Mac") || osName.contains("Darwin")) {
return "Mac";
} else if (osName.contains("AIX")) {
return "AIX";
} else if (isMusl()) {
return "Linux-Musl";
} else if (isAndroid()) {
return "Linux-Android";
} else if (osName.contains("Linux")) {
return "Linux";
} else {
return osName.replaceAll("\\W", "");
}
}
static String translateArchNameToFolderName(String archName) {
return archName.replaceAll("\\W", "");
}
/**
* Class-wrapper around the logger object to avoid build-time initialization of the logging
* framework in native-image
*/
private static class LogHolder {
private static final Logger logger = LoggerFactory.getLogger(OSInfo.class);
}
}
| False |
4,221 | 174768_5 | // ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package com.amalto.workbench.editors;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amalto.workbench.dialogs.DOMViewDialog;
import com.amalto.workbench.i18n.Messages;
import com.amalto.workbench.image.ImageCache;
import com.amalto.workbench.models.IXObjectModelListener;
import com.amalto.workbench.models.TreeObject;
import com.amalto.workbench.providers.XObjectBrowserInput;
import com.amalto.workbench.utils.Util;
import com.amalto.workbench.utils.XtentisException;
import com.amalto.workbench.webservices.TMDMService;
import com.amalto.workbench.webservices.WSDataClusterPK;
import com.amalto.workbench.webservices.WSGetView;
import com.amalto.workbench.webservices.WSQuickSearch;
import com.amalto.workbench.webservices.WSStringPredicate;
import com.amalto.workbench.webservices.WSView;
import com.amalto.workbench.webservices.WSViewPK;
import com.amalto.workbench.webservices.WSViewSearch;
import com.amalto.workbench.webservices.WSWhereAnd;
import com.amalto.workbench.webservices.WSWhereCondition;
import com.amalto.workbench.webservices.WSWhereItem;
import com.amalto.workbench.webservices.WSWhereOperator;
public class ViewBrowserMainPage extends AMainPage implements IXObjectModelListener {
private static Log log = LogFactory.getLog(ViewBrowserMainPage.class);
protected Combo dataClusterCombo;
protected Text searchText;
protected TableViewer resultsViewer;
protected List viewableBEsList;
protected List searchableBEsList;
protected ListViewer wcListViewer;
protected Label resultsLabel;
protected Button matchAllWordsBtn;
private Combo searchItemCombo;
private final String FULL_TEXT = Messages.ViewBrowserMainPage_fullText;
protected Combo clusterTypeCombo;
public ViewBrowserMainPage(FormEditor editor) {
super(editor, ViewBrowserMainPage.class.getName(), Messages.ViewBrowserMainPage_ViewBrowser
+ ((XObjectBrowserInput) editor.getEditorInput()).getName());
// listen to events
((XObjectBrowserInput) editor.getEditorInput()).addListener(this);
}
@Override
protected void createCharacteristicsContent(FormToolkit toolkit, Composite charComposite) {
try {
Label vbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_ViewableElements, SWT.NULL);
vbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
Label sbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_SearchableElements, SWT.NULL);
sbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
viewableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
viewableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
((GridData) viewableBEsList.getLayoutData()).heightHint = 100;
searchableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
searchableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
((GridData) searchableBEsList.getLayoutData()).heightHint = 100;
Label wcLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_Conditions, SWT.NULL);
wcLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1));
wcListViewer = new ListViewer(charComposite, SWT.BORDER);
wcListViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
((GridData) wcListViewer.getControl().getLayoutData()).minimumHeight = 100;
wcListViewer.setContentProvider(new IStructuredContentProvider() {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object inputElement) {
return ((WSView) inputElement).getWhereConditions().toArray();
}
});
wcListViewer.setLabelProvider(new ILabelProvider() {
public Image getImage(Object element) {
return null;
}
public String getText(Object element) {
WSWhereCondition wc = (WSWhereCondition) element;
String text = wc.getLeftPath() + " ";//$NON-NLS-1$
if (wc.getOperator().equals(WSWhereOperator.CONTAINS)) {
text += "Contains";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.CONTAINS_TEXT_OF)) {
text += "Contains Text Of";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.EQUALS)) {
text += "=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN)) {
text += ">";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN_OR_EQUAL)) {
text += ">=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "Joins With";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN)) {
text += "<";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN_OR_EQUAL)) {
text += "<=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.NOT_EQUALS)) {
text += "!=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.STARTSWITH)) {
text += "Starts With";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.STRICTCONTAINS)) {
text += "Strict Contains";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.EMPTY_NULL)) {
text += "Is Empty Or Null";//$NON-NLS-1$
}
text += " ";//$NON-NLS-1$
if (!wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "\"";//$NON-NLS-1$
}
text += wc.getRightValueOrPath();
if (!wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "\"";//$NON-NLS-1$
}
text += " ";//$NON-NLS-1$
if (wc.getStringPredicate().equals(WSStringPredicate.AND)) {
text += "[and]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.EXACTLY)) {
text += "[exactly]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NONE)) {
text += "";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) {
text += "[not]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) {
text += "[or]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.STRICTAND)) {
text += "[strict and]";//$NON-NLS-1$
}
return text;
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
});
int columns = 6;
Composite resultsGroup = this.getNewSectionComposite(Messages.ViewBrowserMainPage_SearchAndResults);
resultsGroup.setLayout(new GridLayout(columns, false));
Composite createComposite = toolkit.createComposite(resultsGroup);
GridLayout layout = new GridLayout(3, false);
layout.marginWidth = 0;
createComposite.setLayout(layout);
createComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
Label containerLabel = toolkit.createLabel(createComposite, Messages.ViewBrowserMainPage_Container, SWT.NULL);
containerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
dataClusterCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE);
dataClusterCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
((GridData) dataClusterCombo.getLayoutData()).minimumWidth = 100;
clusterTypeCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.SINGLE);
GridData typeLayout = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1);
typeLayout.horizontalIndent = 10;
clusterTypeCombo.setLayoutData(typeLayout);
Label searchOnLabel = toolkit.createLabel(resultsGroup, Messages.ViewBrowserMainPage_SearchOn, SWT.NULL);
GridData layoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
layoutData.horizontalIndent = 20;
searchOnLabel.setLayoutData(layoutData);
searchItemCombo = new Combo(resultsGroup, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE);
searchItemCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
((GridData) searchItemCombo.getLayoutData()).minimumWidth = 100;
searchItemCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (FULL_TEXT.equals(searchItemCombo.getText())) {
matchAllWordsBtn.setEnabled(true);
} else {
matchAllWordsBtn.setSelection(false);
matchAllWordsBtn.setEnabled(false);
}
}
});
searchText = toolkit.createText(resultsGroup, "", SWT.BORDER);//$NON-NLS-1$
searchText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
searchText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if ((e.stateMask == 0) && (e.character == SWT.CR)) {
ViewBrowserMainPage.this.resultsViewer.setInput(getResults());
}
}// keyReleased
}// keyListener
);
Button bSearch = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_Search, SWT.CENTER);
bSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
bSearch.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ViewBrowserMainPage.this.resultsViewer.setInput(getResults());
};
});
matchAllWordsBtn = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_MatchWholeSentence, SWT.CHECK);
matchAllWordsBtn.setSelection(true);
resultsLabel = toolkit.createLabel(resultsGroup, "", SWT.NULL); //$NON-NLS-1$
GridData resultLayoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, columns - 1, 1);
resultLayoutData.widthHint = 100;
resultsLabel.setLayoutData(resultLayoutData);
resultsViewer = new TableViewer(resultsGroup);
resultsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1));
((GridData) resultsViewer.getControl().getLayoutData()).heightHint = 500;
resultsViewer.setContentProvider(new ArrayContentProvider());
resultsViewer.setLabelProvider(new XMLTableLabelProvider());
resultsViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
resultsViewer.setSelection(event.getSelection());
try {
new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), resultsViewer).run();
} catch (Exception e) {
MessageDialog.openError(
ViewBrowserMainPage.this.getSite().getShell(),
Messages._Error,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg, e.getClass().getName(),
e.getLocalizedMessage()));
}
}
});
hookContextMenu();
addListener();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}// createCharacteristicsContent
@Override
protected void refreshData() {
try {
if (viewableBEsList.isDisposed() || searchableBEsList.isDisposed() || wcListViewer.getList().isDisposed()
|| searchItemCombo.isDisposed() || dataClusterCombo.isDisposed()) {
return;
}
WSView view = null;
if (getXObject().getWsObject() == null) { // then fetch from server
TMDMService port = getMDMService();
view = port.getView(new WSGetView((WSViewPK) getXObject().getWsKey()));
getXObject().setWsObject(view);
} else { // it has been opened by an editor - use the object there
view = (WSView) getXObject().getWsObject();
}
java.util.List<String> paths = view.getViewableBusinessElements();
// Fill the vbe List
viewableBEsList.removeAll();
for (String path : paths) {
viewableBEsList.add(path);
}
paths = view.getSearchableBusinessElements();
searchableBEsList.removeAll();
searchItemCombo.removeAll();
if (paths != null) {
for (String path : paths) {
searchableBEsList.add(path);
searchItemCombo.add(path);
}
}
searchItemCombo.add(FULL_TEXT);
searchItemCombo.setText(FULL_TEXT);
wcListViewer.setInput(view);
wcListViewer.refresh();
dataClusterCombo.removeAll();
java.util.List<WSDataClusterPK> dataClusterPKs = getDataClusterPKs();
if ((dataClusterPKs == null) || (dataClusterPKs.size() == 0)) {
MessageDialog.openError(this.getSite().getShell(), Messages._Error, Messages.ViewBrowserMainPage_ErrorMsg1);
return;
}
for (WSDataClusterPK pk : dataClusterPKs) {
dataClusterCombo.add(pk.getPk());
}
dataClusterCombo.select(0);
clusterTypeCombo.setItems(getClusterTypes());
clusterTypeCombo.select(0);
this.getManagedForm().reflow(true);
searchText.setFocus();
} catch (Exception e) {
log.error(e.getMessage(), e);
if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle2)) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle2,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg2, e.getLocalizedMessage()));
}
}
}
protected String[] getClusterTypes() {
return new String[0];
}
protected java.util.List<WSDataClusterPK> getDataClusterPKs() throws MalformedURLException, XtentisException {
return Util.getAllDataClusterPKs(new URL(getXObject().getEndpointAddress()), getXObject().getUsername(), getXObject()
.getPassword());
}
@Override
protected void commit() {
try {
} catch (Exception e) {
log.error(e.getMessage(), e);
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle3,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg3, e.getLocalizedMessage()));
}
}
@Override
protected void createActions() {
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(),
ViewBrowserMainPage.this.resultsViewer));
}
});
Menu menu = menuMgr.createContextMenu(resultsViewer.getControl());
resultsViewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, resultsViewer);
}
private void addListener() {
dataClusterCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clusterTypeCombo.setItems(getClusterTypes());
clusterTypeCombo.select(0);
}
});
}
protected void fillContextMenu(IMenuManager manager) {
return;
}
protected WSViewPK getViewPK() {
return (WSViewPK) getXObject().getWsKey();
}
public String[] getResults() {
Cursor waitCursor = null;
try {
Display display = getEditor().getSite().getPage().getWorkbenchWindow().getWorkbench().getDisplay();
waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
this.getSite().getShell().setCursor(waitCursor);
TMDMService service = getMDMService();
java.util.List<String> results = null;
int maxItem = 10;
String search = "".equals(searchText.getText()) ? "*" : searchText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataClusterCombo.getText() + getPkAddition());
if (FULL_TEXT.equals(searchItemCombo.getText())) {
boolean matchAllWords = matchAllWordsBtn.getSelection();
results = service.quickSearch(
new WSQuickSearch(null, matchAllWords, maxItem, null, search, 0, Integer.MAX_VALUE, wsDataClusterPK,
getViewPK())).getStrings();
} else {
WSView wsview = (WSView) wcListViewer.getInput();
java.util.List<WSWhereCondition> array = wsview.getWhereConditions();
java.util.List<WSWhereItem> conditions = new ArrayList<WSWhereItem>();
for (WSWhereCondition condition : array) {
WSWhereItem item = new WSWhereItem(null, condition, null);
conditions.add(item);
}
WSWhereCondition condition = new WSWhereCondition(searchItemCombo.getText(), WSWhereOperator.CONTAINS, search,
true, WSStringPredicate.AND);
WSWhereItem item = new WSWhereItem(null, condition, null);
conditions.add(item);
WSWhereAnd and = new WSWhereAnd(conditions);
WSWhereItem wi = new WSWhereItem(and, null, null);
results = service.viewSearch(
new WSViewSearch("ascending", maxItem, null, 0, -1, wi, wsDataClusterPK, getViewPK())).getStrings(); //$NON-NLS-1$
}
resultsLabel.setText(Messages.bind(Messages.ViewBrowserMainPage_Results, results.size() - 1));
if (results.size() > 1) {
return results.subList(1, results.size()).toArray(new String[0]);
}
return new String[0];
} catch (Exception e) {
log.error(e.getMessage(), e);
if ((e.getLocalizedMessage() != null) && e.getLocalizedMessage().contains("10000")) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle4,
Messages.ViewBrowserMainPage_ErrorMsg4);
} else if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle5)) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle5,
e.getLocalizedMessage());
}
return null;
} finally {
try {
this.getSite().getShell().setCursor(null);
waitCursor.dispose();
} catch (Exception e) {
}
}
}
protected String getPkAddition() {
return ""; //$NON-NLS-1$
}
class DOMViewAction extends Action {
private Shell shell = null;
private Viewer viewer;
public DOMViewAction(Shell shell, Viewer viewer) {
super();
this.shell = shell;
this.viewer = viewer;
setImageDescriptor(ImageCache.getImage("icons/add_obj.gif"));//$NON-NLS-1$
setText(Messages.ViewBrowserMainPage_ViewTree);
setToolTipText(Messages.ViewBrowserMainPage_ViewAsDOMTree);
}
@Override
public void run() {
try {
super.run();
IStructuredSelection selection = ((IStructuredSelection) viewer.getSelection());
String xml = (String) selection.getFirstElement();
// clean up highlights
xml = xml.replaceAll("\\s*__h", "").replaceAll("h__\\s*", "");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
final DOMViewDialog d = new DOMViewDialog(ViewBrowserMainPage.this.getSite().getShell(), Util.parse(xml));
d.addListener(new Listener() {
public void handleEvent(Event event) {
if (event.button == DOMViewDialog.BUTTON_CLOSE) {
d.close();
}
}
});
d.setBlockOnOpen(true);
d.open();
d.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
MessageDialog.openError(shell, Messages._Error,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg5, e.getLocalizedMessage()));
}
}
@Override
public void runWithEvent(Event event) {
super.runWithEvent(event);
}
}
protected static Pattern highlightLeft = Pattern.compile("\\s*__h");//$NON-NLS-1$
protected static Pattern highlightRight = Pattern.compile("h__\\s*");//$NON-NLS-1$
protected static Pattern emptyTags = Pattern.compile("\\s*<(.*?)\\/>\\s*");//$NON-NLS-1$
protected static Pattern openingTags = Pattern.compile("\\s*<([^\\/].*?[^\\/])>\\s*");//$NON-NLS-1$
protected static Pattern closingTags = Pattern.compile("\\s*</(.*?)>\\s*");//$NON-NLS-1$
class XMLTableLabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
String xml = (String) element;
xml = highlightLeft.matcher(xml).replaceAll("");//$NON-NLS-1$
xml = highlightRight.matcher(xml).replaceAll("");//$NON-NLS-1$
xml = emptyTags.matcher(xml).replaceAll("[$1]");//$NON-NLS-1$
xml = openingTags.matcher(xml).replaceAll("[$1: ");//$NON-NLS-1$
xml = closingTags.matcher(xml).replaceAll("]");//$NON-NLS-1$
if (xml.length() >= 150) {
return xml.substring(0, 150) + "...";//$NON-NLS-1$
}
return xml;
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
}
/*********************************
* IXObjectModelListener interface
*/
public void handleEvent(int type, TreeObject parent, TreeObject child) {
refreshData();
}
}
| rubikloud/tmdm-studio-se | main/plugins/org.talend.mdm.workbench/src/com/amalto/workbench/editors/ViewBrowserMainPage.java | 7,952 | // listen to events | line_comment | nl | // ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package com.amalto.workbench.editors;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.widgets.FormToolkit;
import com.amalto.workbench.dialogs.DOMViewDialog;
import com.amalto.workbench.i18n.Messages;
import com.amalto.workbench.image.ImageCache;
import com.amalto.workbench.models.IXObjectModelListener;
import com.amalto.workbench.models.TreeObject;
import com.amalto.workbench.providers.XObjectBrowserInput;
import com.amalto.workbench.utils.Util;
import com.amalto.workbench.utils.XtentisException;
import com.amalto.workbench.webservices.TMDMService;
import com.amalto.workbench.webservices.WSDataClusterPK;
import com.amalto.workbench.webservices.WSGetView;
import com.amalto.workbench.webservices.WSQuickSearch;
import com.amalto.workbench.webservices.WSStringPredicate;
import com.amalto.workbench.webservices.WSView;
import com.amalto.workbench.webservices.WSViewPK;
import com.amalto.workbench.webservices.WSViewSearch;
import com.amalto.workbench.webservices.WSWhereAnd;
import com.amalto.workbench.webservices.WSWhereCondition;
import com.amalto.workbench.webservices.WSWhereItem;
import com.amalto.workbench.webservices.WSWhereOperator;
public class ViewBrowserMainPage extends AMainPage implements IXObjectModelListener {
private static Log log = LogFactory.getLog(ViewBrowserMainPage.class);
protected Combo dataClusterCombo;
protected Text searchText;
protected TableViewer resultsViewer;
protected List viewableBEsList;
protected List searchableBEsList;
protected ListViewer wcListViewer;
protected Label resultsLabel;
protected Button matchAllWordsBtn;
private Combo searchItemCombo;
private final String FULL_TEXT = Messages.ViewBrowserMainPage_fullText;
protected Combo clusterTypeCombo;
public ViewBrowserMainPage(FormEditor editor) {
super(editor, ViewBrowserMainPage.class.getName(), Messages.ViewBrowserMainPage_ViewBrowser
+ ((XObjectBrowserInput) editor.getEditorInput()).getName());
// listen to<SUF>
((XObjectBrowserInput) editor.getEditorInput()).addListener(this);
}
@Override
protected void createCharacteristicsContent(FormToolkit toolkit, Composite charComposite) {
try {
Label vbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_ViewableElements, SWT.NULL);
vbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
Label sbeLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_SearchableElements, SWT.NULL);
sbeLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1));
viewableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
viewableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
((GridData) viewableBEsList.getLayoutData()).heightHint = 100;
searchableBEsList = new List(charComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
searchableBEsList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
((GridData) searchableBEsList.getLayoutData()).heightHint = 100;
Label wcLabel = toolkit.createLabel(charComposite, Messages.ViewBrowserMainPage_Conditions, SWT.NULL);
wcLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 2, 1));
wcListViewer = new ListViewer(charComposite, SWT.BORDER);
wcListViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
((GridData) wcListViewer.getControl().getLayoutData()).minimumHeight = 100;
wcListViewer.setContentProvider(new IStructuredContentProvider() {
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
public Object[] getElements(Object inputElement) {
return ((WSView) inputElement).getWhereConditions().toArray();
}
});
wcListViewer.setLabelProvider(new ILabelProvider() {
public Image getImage(Object element) {
return null;
}
public String getText(Object element) {
WSWhereCondition wc = (WSWhereCondition) element;
String text = wc.getLeftPath() + " ";//$NON-NLS-1$
if (wc.getOperator().equals(WSWhereOperator.CONTAINS)) {
text += "Contains";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.CONTAINS_TEXT_OF)) {
text += "Contains Text Of";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.EQUALS)) {
text += "=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN)) {
text += ">";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.GREATER_THAN_OR_EQUAL)) {
text += ">=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "Joins With";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN)) {
text += "<";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.LOWER_THAN_OR_EQUAL)) {
text += "<=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.NOT_EQUALS)) {
text += "!=";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.STARTSWITH)) {
text += "Starts With";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.STRICTCONTAINS)) {
text += "Strict Contains";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.EMPTY_NULL)) {
text += "Is Empty Or Null";//$NON-NLS-1$
}
text += " ";//$NON-NLS-1$
if (!wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "\"";//$NON-NLS-1$
}
text += wc.getRightValueOrPath();
if (!wc.getOperator().equals(WSWhereOperator.JOIN)) {
text += "\"";//$NON-NLS-1$
}
text += " ";//$NON-NLS-1$
if (wc.getStringPredicate().equals(WSStringPredicate.AND)) {
text += "[and]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.EXACTLY)) {
text += "[exactly]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NONE)) {
text += "";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) {
text += "[not]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) {
text += "[or]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.STRICTAND)) {
text += "[strict and]";//$NON-NLS-1$
}
return text;
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
});
int columns = 6;
Composite resultsGroup = this.getNewSectionComposite(Messages.ViewBrowserMainPage_SearchAndResults);
resultsGroup.setLayout(new GridLayout(columns, false));
Composite createComposite = toolkit.createComposite(resultsGroup);
GridLayout layout = new GridLayout(3, false);
layout.marginWidth = 0;
createComposite.setLayout(layout);
createComposite.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
Label containerLabel = toolkit.createLabel(createComposite, Messages.ViewBrowserMainPage_Container, SWT.NULL);
containerLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
dataClusterCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE);
dataClusterCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
((GridData) dataClusterCombo.getLayoutData()).minimumWidth = 100;
clusterTypeCombo = new Combo(createComposite, SWT.READ_ONLY | SWT.SINGLE);
GridData typeLayout = new GridData(SWT.CENTER, SWT.CENTER, true, false, 1, 1);
typeLayout.horizontalIndent = 10;
clusterTypeCombo.setLayoutData(typeLayout);
Label searchOnLabel = toolkit.createLabel(resultsGroup, Messages.ViewBrowserMainPage_SearchOn, SWT.NULL);
GridData layoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
layoutData.horizontalIndent = 20;
searchOnLabel.setLayoutData(layoutData);
searchItemCombo = new Combo(resultsGroup, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE);
searchItemCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1));
((GridData) searchItemCombo.getLayoutData()).minimumWidth = 100;
searchItemCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (FULL_TEXT.equals(searchItemCombo.getText())) {
matchAllWordsBtn.setEnabled(true);
} else {
matchAllWordsBtn.setSelection(false);
matchAllWordsBtn.setEnabled(false);
}
}
});
searchText = toolkit.createText(resultsGroup, "", SWT.BORDER);//$NON-NLS-1$
searchText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
searchText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
if ((e.stateMask == 0) && (e.character == SWT.CR)) {
ViewBrowserMainPage.this.resultsViewer.setInput(getResults());
}
}// keyReleased
}// keyListener
);
Button bSearch = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_Search, SWT.CENTER);
bSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
bSearch.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
ViewBrowserMainPage.this.resultsViewer.setInput(getResults());
};
});
matchAllWordsBtn = toolkit.createButton(resultsGroup, Messages.ViewBrowserMainPage_MatchWholeSentence, SWT.CHECK);
matchAllWordsBtn.setSelection(true);
resultsLabel = toolkit.createLabel(resultsGroup, "", SWT.NULL); //$NON-NLS-1$
GridData resultLayoutData = new GridData(SWT.LEFT, SWT.CENTER, false, false, columns - 1, 1);
resultLayoutData.widthHint = 100;
resultsLabel.setLayoutData(resultLayoutData);
resultsViewer = new TableViewer(resultsGroup);
resultsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, columns, 1));
((GridData) resultsViewer.getControl().getLayoutData()).heightHint = 500;
resultsViewer.setContentProvider(new ArrayContentProvider());
resultsViewer.setLabelProvider(new XMLTableLabelProvider());
resultsViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
resultsViewer.setSelection(event.getSelection());
try {
new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(), resultsViewer).run();
} catch (Exception e) {
MessageDialog.openError(
ViewBrowserMainPage.this.getSite().getShell(),
Messages._Error,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg, e.getClass().getName(),
e.getLocalizedMessage()));
}
}
});
hookContextMenu();
addListener();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}// createCharacteristicsContent
@Override
protected void refreshData() {
try {
if (viewableBEsList.isDisposed() || searchableBEsList.isDisposed() || wcListViewer.getList().isDisposed()
|| searchItemCombo.isDisposed() || dataClusterCombo.isDisposed()) {
return;
}
WSView view = null;
if (getXObject().getWsObject() == null) { // then fetch from server
TMDMService port = getMDMService();
view = port.getView(new WSGetView((WSViewPK) getXObject().getWsKey()));
getXObject().setWsObject(view);
} else { // it has been opened by an editor - use the object there
view = (WSView) getXObject().getWsObject();
}
java.util.List<String> paths = view.getViewableBusinessElements();
// Fill the vbe List
viewableBEsList.removeAll();
for (String path : paths) {
viewableBEsList.add(path);
}
paths = view.getSearchableBusinessElements();
searchableBEsList.removeAll();
searchItemCombo.removeAll();
if (paths != null) {
for (String path : paths) {
searchableBEsList.add(path);
searchItemCombo.add(path);
}
}
searchItemCombo.add(FULL_TEXT);
searchItemCombo.setText(FULL_TEXT);
wcListViewer.setInput(view);
wcListViewer.refresh();
dataClusterCombo.removeAll();
java.util.List<WSDataClusterPK> dataClusterPKs = getDataClusterPKs();
if ((dataClusterPKs == null) || (dataClusterPKs.size() == 0)) {
MessageDialog.openError(this.getSite().getShell(), Messages._Error, Messages.ViewBrowserMainPage_ErrorMsg1);
return;
}
for (WSDataClusterPK pk : dataClusterPKs) {
dataClusterCombo.add(pk.getPk());
}
dataClusterCombo.select(0);
clusterTypeCombo.setItems(getClusterTypes());
clusterTypeCombo.select(0);
this.getManagedForm().reflow(true);
searchText.setFocus();
} catch (Exception e) {
log.error(e.getMessage(), e);
if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle2)) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle2,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg2, e.getLocalizedMessage()));
}
}
}
protected String[] getClusterTypes() {
return new String[0];
}
protected java.util.List<WSDataClusterPK> getDataClusterPKs() throws MalformedURLException, XtentisException {
return Util.getAllDataClusterPKs(new URL(getXObject().getEndpointAddress()), getXObject().getUsername(), getXObject()
.getPassword());
}
@Override
protected void commit() {
try {
} catch (Exception e) {
log.error(e.getMessage(), e);
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle3,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg3, e.getLocalizedMessage()));
}
}
@Override
protected void createActions() {
}
private void hookContextMenu() {
MenuManager menuMgr = new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
manager.add(new DOMViewAction(ViewBrowserMainPage.this.getSite().getShell(),
ViewBrowserMainPage.this.resultsViewer));
}
});
Menu menu = menuMgr.createContextMenu(resultsViewer.getControl());
resultsViewer.getControl().setMenu(menu);
getSite().registerContextMenu(menuMgr, resultsViewer);
}
private void addListener() {
dataClusterCombo.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
clusterTypeCombo.setItems(getClusterTypes());
clusterTypeCombo.select(0);
}
});
}
protected void fillContextMenu(IMenuManager manager) {
return;
}
protected WSViewPK getViewPK() {
return (WSViewPK) getXObject().getWsKey();
}
public String[] getResults() {
Cursor waitCursor = null;
try {
Display display = getEditor().getSite().getPage().getWorkbenchWindow().getWorkbench().getDisplay();
waitCursor = new Cursor(display, SWT.CURSOR_WAIT);
this.getSite().getShell().setCursor(waitCursor);
TMDMService service = getMDMService();
java.util.List<String> results = null;
int maxItem = 10;
String search = "".equals(searchText.getText()) ? "*" : searchText.getText(); //$NON-NLS-1$ //$NON-NLS-2$
WSDataClusterPK wsDataClusterPK = new WSDataClusterPK(dataClusterCombo.getText() + getPkAddition());
if (FULL_TEXT.equals(searchItemCombo.getText())) {
boolean matchAllWords = matchAllWordsBtn.getSelection();
results = service.quickSearch(
new WSQuickSearch(null, matchAllWords, maxItem, null, search, 0, Integer.MAX_VALUE, wsDataClusterPK,
getViewPK())).getStrings();
} else {
WSView wsview = (WSView) wcListViewer.getInput();
java.util.List<WSWhereCondition> array = wsview.getWhereConditions();
java.util.List<WSWhereItem> conditions = new ArrayList<WSWhereItem>();
for (WSWhereCondition condition : array) {
WSWhereItem item = new WSWhereItem(null, condition, null);
conditions.add(item);
}
WSWhereCondition condition = new WSWhereCondition(searchItemCombo.getText(), WSWhereOperator.CONTAINS, search,
true, WSStringPredicate.AND);
WSWhereItem item = new WSWhereItem(null, condition, null);
conditions.add(item);
WSWhereAnd and = new WSWhereAnd(conditions);
WSWhereItem wi = new WSWhereItem(and, null, null);
results = service.viewSearch(
new WSViewSearch("ascending", maxItem, null, 0, -1, wi, wsDataClusterPK, getViewPK())).getStrings(); //$NON-NLS-1$
}
resultsLabel.setText(Messages.bind(Messages.ViewBrowserMainPage_Results, results.size() - 1));
if (results.size() > 1) {
return results.subList(1, results.size()).toArray(new String[0]);
}
return new String[0];
} catch (Exception e) {
log.error(e.getMessage(), e);
if ((e.getLocalizedMessage() != null) && e.getLocalizedMessage().contains("10000")) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle4,
Messages.ViewBrowserMainPage_ErrorMsg4);
} else if (!Util.handleConnectionException(this.getSite().getShell(), e, Messages.ViewBrowserMainPage_ErrorTitle5)) {
MessageDialog.openError(this.getSite().getShell(), Messages.ViewBrowserMainPage_ErrorTitle5,
e.getLocalizedMessage());
}
return null;
} finally {
try {
this.getSite().getShell().setCursor(null);
waitCursor.dispose();
} catch (Exception e) {
}
}
}
protected String getPkAddition() {
return ""; //$NON-NLS-1$
}
class DOMViewAction extends Action {
private Shell shell = null;
private Viewer viewer;
public DOMViewAction(Shell shell, Viewer viewer) {
super();
this.shell = shell;
this.viewer = viewer;
setImageDescriptor(ImageCache.getImage("icons/add_obj.gif"));//$NON-NLS-1$
setText(Messages.ViewBrowserMainPage_ViewTree);
setToolTipText(Messages.ViewBrowserMainPage_ViewAsDOMTree);
}
@Override
public void run() {
try {
super.run();
IStructuredSelection selection = ((IStructuredSelection) viewer.getSelection());
String xml = (String) selection.getFirstElement();
// clean up highlights
xml = xml.replaceAll("\\s*__h", "").replaceAll("h__\\s*", "");//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
final DOMViewDialog d = new DOMViewDialog(ViewBrowserMainPage.this.getSite().getShell(), Util.parse(xml));
d.addListener(new Listener() {
public void handleEvent(Event event) {
if (event.button == DOMViewDialog.BUTTON_CLOSE) {
d.close();
}
}
});
d.setBlockOnOpen(true);
d.open();
d.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
MessageDialog.openError(shell, Messages._Error,
Messages.bind(Messages.ViewBrowserMainPage_ErrorMsg5, e.getLocalizedMessage()));
}
}
@Override
public void runWithEvent(Event event) {
super.runWithEvent(event);
}
}
protected static Pattern highlightLeft = Pattern.compile("\\s*__h");//$NON-NLS-1$
protected static Pattern highlightRight = Pattern.compile("h__\\s*");//$NON-NLS-1$
protected static Pattern emptyTags = Pattern.compile("\\s*<(.*?)\\/>\\s*");//$NON-NLS-1$
protected static Pattern openingTags = Pattern.compile("\\s*<([^\\/].*?[^\\/])>\\s*");//$NON-NLS-1$
protected static Pattern closingTags = Pattern.compile("\\s*</(.*?)>\\s*");//$NON-NLS-1$
class XMLTableLabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
String xml = (String) element;
xml = highlightLeft.matcher(xml).replaceAll("");//$NON-NLS-1$
xml = highlightRight.matcher(xml).replaceAll("");//$NON-NLS-1$
xml = emptyTags.matcher(xml).replaceAll("[$1]");//$NON-NLS-1$
xml = openingTags.matcher(xml).replaceAll("[$1: ");//$NON-NLS-1$
xml = closingTags.matcher(xml).replaceAll("]");//$NON-NLS-1$
if (xml.length() >= 150) {
return xml.substring(0, 150) + "...";//$NON-NLS-1$
}
return xml;
}
public void addListener(ILabelProviderListener listener) {
}
public void dispose() {
}
public boolean isLabelProperty(Object element, String property) {
return false;
}
public void removeListener(ILabelProviderListener listener) {
}
}
/*********************************
* IXObjectModelListener interface
*/
public void handleEvent(int type, TreeObject parent, TreeObject child) {
refreshData();
}
}
| False |
1,078 | 145235_18 | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden behoben.
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
| MartinSteffen/pest | src/Pest2/TESC1/TESCLabelParser.java | 1,009 | // gegeben werden behoben. | line_comment | nl | package tesc1;
import java.io.*;
import java.lang.String;
import java.util.Vector;
import absyn.*;
import util.*;
/**
* Label-Parser fuer den Editor.
* <p>
* @author Michael Suelzer, Christoph Schuette.
* @version $Id: TESCLabelParser.java,v 1.5 1999-02-07 11:58:30 swtech20 Exp $
*/
class TESCLabelParser extends TESCParser {
protected Statechart statechart;
// Der Standard-Ktor muss verborgen werden, da
// das Parsen eines Labels ohne Statechart
// keinen Sinn macht.
private TESCLabelParser() {};
/**
* Constructor.
*/
public TESCLabelParser (Statechart sc) {
statechart = sc;
eventlist = sc.events;
bvarlist = sc.bvars;
pathlist = sc.cnames;
}
/**
* Startet den Parsevorgang fuer ein Label.
*/
public TLabel readLabel (BufferedReader br) throws IOException {
warningText = new Vector ();
warningCount = 0 ;
errorText = new Vector ();
errorCount = 0;
lexer = new TESCTokenizer (br);
token = lexer.getNextToken ();
debug ("parseLabel");
TLabel label = parseLabel ();
// Die geaenderten Listen nach aussen geben
statechart.bvars = bvarlist;
statechart.events = eventlist;
statechart.cnames = pathlist;
return label;
}
/**
* LABEL ::= {GUARD} {"/" ACTION}
*/
public TLabel parseLabel () throws IOException {
//debug ("Enter parseLabel");
Guard guard = parseGuardSTMStyle ();
Action action = null;
if (token.getId () == Token.TOK_SLASH) {
matchToken (Token.Slash);
action = parseActions ();
}
else
action = new ActionEmpty (new Dummy ());
// Caption fuer TLabel aufbauen.
TLabel label = new TLabel (guard, action);
TESCSaver saver = new TESCSaver (null);
saver.setCaption (label);
// Sollte wider Erwarten ein Fehler auftreten, dann merken
errorCount += saver.getErrorCount ();
for (int i=0; i < saver.getErrorCount (); i++)
Error (saver.getErrorText (i));
//debug ("Leave parseLabel");
return label;
}
}
//----------------------------------------------------------------------
// Label-Parser
// ------------
//
// $Log: not supported by cvs2svn $
// Revision 1.4 1999/02/01 11:52:58 swtech20
// - globaler Debug-Schalter
//
// Revision 1.3 1999/01/20 17:32:10 swtech20
// - Status und Doku aktualisiert
// - Fehler, dass Anderungen an Bvarlisten ... nicht nach aussen-
// gegeben werden<SUF>
//
// Revision 1.2 1999/01/18 17:08:52 swtech20
// - okDialog -> userMessage
// - Pruefung auf gui==null
// - package visibility fuer Nicht-Schnittstellenklassen
//
// Revision 1.1 1999/01/17 17:16:41 swtech20
// Umstellung der Guard-Syntax auf Statemate-Style, Implementierung des
// LabelParsers fuer den Editor. Anpassung der Schnittstelle.
//
//
//
//
//----------------------------------------------------------------------
| False |
4,382 | 131187_8 | package week2;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class GlobalTransitionSystemTest {
@Test
void hasExecutionTest1() {
String s = "g0 ";
s += "g0--a@p->g1 g1--b@p->g2 g2--e@r->g3 g3--f@r->g4 g4--d@q->g5 ";
s += "g6--b@p->g7 g7--e@r->g8 g8--f@r->g9 g9--d@q->g10 ";
s += "g1--c@q->g6 g2--c@q->g7 g3--c@q->g8 g4--c@q->g9 g5--c@q->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest2() {
String s = "g0 ";
s += "g0--c@q->g1 g1--d@q->g2 g2--a@p->g3 g3--b@p->g4 g4--e@q->g5 ";
s += "g6--d@q->g7 g7--a@p->g8 g8--b@p->g9 g9--e@q->g10 ";
s += "g1--f@r->g6 g2--f@r->g7 g3--f@r->g8 g4--f@r->g9 g5--f@r->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest3() {
String s = "g0 ";
s += "g0--a@p->g1 g1--c@r->g2 ";
s += "g3--a@p->g4 g4--c@r->g5 ";
s += "g6--a@p->g7 g7--c@r->g8 ";
s += "g0--b@q->g3 g1--b@q->g4 g2--b@q->g5 ";
s += "g3--d@r->g6 g4--d@r->g7 g5--d@r->g8";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g6 g7 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g5 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g9 g8", configurations)));
}
@Test
void hasExecutionTest4() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest5() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest6() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest7() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 100; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest8() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
assertFalse(system.hasExecution(new ArrayList<>()));
}
// @Test
// void parseTest1() {
// String s = "g0 g0--a@p->g1";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest2() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest3() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g1--s(p,q,2)->g4 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
}
| sschivo/ib2302 | Opdrachten/src/week2/GlobalTransitionSystemTest.java | 2,554 | // void parseTest3() { | line_comment | nl | package week2;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
class GlobalTransitionSystemTest {
@Test
void hasExecutionTest1() {
String s = "g0 ";
s += "g0--a@p->g1 g1--b@p->g2 g2--e@r->g3 g3--f@r->g4 g4--d@q->g5 ";
s += "g6--b@p->g7 g7--e@r->g8 g8--f@r->g9 g9--d@q->g10 ";
s += "g1--c@q->g6 g2--c@q->g7 g3--c@q->g8 g4--c@q->g9 g5--c@q->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest2() {
String s = "g0 ";
s += "g0--c@q->g1 g1--d@q->g2 g2--a@p->g3 g3--b@p->g4 g4--e@q->g5 ";
s += "g6--d@q->g7 g7--a@p->g8 g8--b@p->g9 g9--e@q->g10 ";
s += "g1--f@r->g6 g2--f@r->g7 g3--f@r->g8 g4--f@r->g9 g5--f@r->g10";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g7 g8 g9 g10", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g6 g7 g8 g9 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g3 g4 g5 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g10", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g3 g4 g5 g11 g10", configurations)));
}
@Test
void hasExecutionTest3() {
String s = "g0 ";
s += "g0--a@p->g1 g1--c@r->g2 ";
s += "g3--a@p->g4 g4--c@r->g5 ";
s += "g6--a@p->g7 g7--c@r->g8 ";
s += "g0--b@q->g3 g1--b@q->g4 g2--b@q->g5 ";
s += "g3--d@r->g6 g4--d@r->g7 g5--d@r->g8";
Map<String, Configuration> configurations = new HashMap<>();
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g5 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g4 g7 g8", configurations)));
assertTrue(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g3 g6 g7 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g1 g2 g5 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g8", configurations)));
assertFalse(GlobalTransitionSystem.parse(s, configurations)
.hasExecution(Configuration.parseList("g0 g1 g2 g5 g9 g8", configurations)));
}
@Test
void hasExecutionTest4() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest5() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 10; i++) {
assertTrue(system.hasExecution(system.randomExecution(i)));
}
}
@Test
void hasExecutionTest6() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 3, 4, 12);
for (int i = 0; i < 10; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest7() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
for (int i = 0; i < 100; i++) {
assertFalse(system.hasExecution(system.randomNonExecution(i)));
}
}
@Test
void hasExecutionTest8() {
GlobalTransitionSystem system = GlobalTransitionSystem.random(0, 30, 40, 120);
assertFalse(system.hasExecution(new ArrayList<>()));
}
// @Test
// void parseTest1() {
// String s = "g0 g0--a@p->g1";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest2() {
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
//
// @Test
// void parseTest3()<SUF>
// String s = "g0 g0--s(p,q,1)->g1 g1--r(p,q,1)->g2 g1--s(p,q,2)->g4 g3--a@q->g0";
// Map<String, Configuration> configurations = new LinkedHashMap<>();
//
// assertEquals(s, GlobalTransitionSystem.parse(s, configurations).toString(configurations));
// }
}
| False |
1,419 | 31184_12 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class World3 extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public World3() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{129,129,129,129,129,129,129,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,130,143,142,128,-1,-1,-1,-1,-1,168,62,62,62,62,62,62,62,62,62,62,168,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,143,129,129,129,129,129,129,129,17,17,17,17,17,17,17,17,17,17,129,129,129,129,129,129,129,129,129,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,94,94,94,94,94,94,94,94,94,94,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,129,-1,-1,129,-1,-1,129,-1,-1,129,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,94,94,94,129,129,129,129,15,15,15,129,129,94,94,94,129,94,94,94,129,94,94,94,129,129,129,129,129,129,-1,-1,129,-1,-1,-1,129,129,129,129,129},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,94,94,94,94,94,94,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,93,93,93,93,93,93,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,93,93,93,93,93,93,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,131,131,131,131,131,131,131,15,15,15,130,130,130,130,130,130,130,130,130,130,131,131,131,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,61,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,60,-1,-1,-1,-1,-1,-1,-1,175,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero(3);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 73, 140);
showText("Level 3", 100, 120);
addObject(new HUD(), 0, 0);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
} | ROCMondriaanTIN/project-greenfoot-game-skiffa070 | World3.java | 4,847 | // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class World3 extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public World3() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("bg.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{129,129,129,129,129,129,129,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,130,143,142,128,-1,-1,-1,-1,-1,168,62,62,62,62,62,62,62,62,62,62,168,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,143,129,129,129,129,129,129,129,17,17,17,17,17,17,17,17,17,17,129,129,129,129,129,129,129,129,129,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,94,94,94,94,94,94,94,94,94,94,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,93,93,93,93,93,93,93,93,93,93,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,142,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,143,142,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,129,-1,-1,129,-1,-1,129,-1,-1,129,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,176,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,129,94,94,94,129,129,129,129,15,15,15,129,129,94,94,94,129,94,94,94,129,94,94,94,129,129,129,129,129,129,-1,-1,129,-1,-1,-1,129,129,129,129,129},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,94,94,94,94,94,94,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,93,93,93,93,93,93,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,93,93,93,131,131,131,131,15,15,15,130,130,93,93,93,130,93,93,93,130,93,93,93,130,130,130,130,130,130,93,93,93,93,93,93,130,130,130,130,130},
{130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,131,131,131,131,131,131,131,131,131,131,131,131,15,15,15,130,130,130,130,130,130,130,130,130,130,131,131,131,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,61,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,60,-1,-1,-1,-1,-1,-1,-1,175,-1,-1,-1,-1,-1,-1,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,130,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero(3);
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 73, 140);
showText("Level 3", 100, 120);
addObject(new HUD(), 0, 0);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van<SUF>
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
} | True |
1,433 | 39552_5 | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | Rakky88/InitiativeTracker | src/main/java/controller/InitiativeController.java | 2,231 | /**Met deze methode wordt een creature uit de initiativeList gehaald.
*
*/ | block_comment | nl | package controller;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import model.Creature;
import view.Main;
import view.SceneManager;
import java.util.ArrayList;
import java.util.stream.Collectors;
/**Deze class is gelinkt met initiativeScene.fxml en geeft een scherm weer waar je creatures kan invoeren voor
* initiative, voordat je naar het echte initiative bijhoudt scherm gaat.
*
* @author R.Groot
*/
public class InitiativeController {
private final SceneManager SCENEMANAGER = Main.getSceneManager();
private ArrayList<Creature> initiative = new ArrayList<>();
//Checkboxxes
@FXML
private CheckBox lairActionCheckBox;
@FXML
private ListView<Creature> initiativeList;
@FXML
private TextField nameTextField;
@FXML
private TextField initiativeTextField;
@FXML
private TextField hpTextField;
@FXML
private TextField maxHPTextField;
@FXML
private TextField legResTextField;
@FXML
private TextField legActTextField;
@FXML
private VBox legendaryControls;
@FXML
private CheckBox legendaryCheckBox;
/**Deze methode wordt gestart wanneer naar dit scherm wordt gegaan. Momenteel doet deze methode niets, maar
* in de toekomst kunnen hier dingen aan toegevoegd worden als nodig.
*/
public void setup() {
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
}
/**Deze methode zet de initiativeList op volgorde van initiative (hoog naar laag).
*
*/
public void orderList() {
initiative.sort((c1, c2) -> Double.compare(c2.getInitiative(), c1.getInitiative()));
initiativeList.getItems().setAll(initiative);
}
public void handleLegendaryCheckBox(){
legendaryControls.setVisible(legendaryCheckBox.isSelected());
if(legendaryCheckBox.isSelected()) {
legendaryControls.setVisible(true);
legResTextField.setText(String.valueOf(0));
} else{
legendaryControls.setVisible(false);
}
}
/**Met deze methode wordt een creature toegevoegd aan de initiativeList.
*
*/
public void doAdd() {
if(validateCreature()) {
try {
double getInitiative = Double.parseDouble(initiativeTextField.getText());
int getHP = Integer.parseInt(hpTextField.getText());
int getMaxHP = Integer.parseInt(maxHPTextField.getText());
int legRes = 0;
int legAct = 0;
if (!legResTextField.getText().isEmpty()) {
legRes = Integer.parseInt(legResTextField.getText());
}
if (!legActTextField.getText().isEmpty()) {
legAct = Integer.parseInt(legActTextField.getText());
}
initiative.add(new Creature(nameTextField.getText(), getInitiative, getHP, getMaxHP, legRes, legAct));
nameTextField.setText("");
initiativeTextField.setText("");
hpTextField.setText("");
maxHPTextField.setText("");
legResTextField.setText("0");
legActTextField.setText("0");
legendaryCheckBox.setSelected(false);
legendaryControls.setVisible(false);
orderList();
} catch (NumberFormatException exception) {
showAlert("Initiative and HP must be valid numbers!");
}
}
}
/**Met deze methode wordt de gebruiker naar de initiativeTracker scherm gebracht.
*
*/
public void doTracker() {
if(initiative == null) {
showAlert("Your initiative list is empty!");
}
SCENEMANAGER.showInitiativeTrackerScene(initiative, lairActionCheckBox.isSelected());
}
/**Met deze methode<SUF>*/
public void doDelete() {
Creature selectedCreature = initiativeList.getSelectionModel().getSelectedItem();
if (selectedCreature != null) {
initiative.remove(selectedCreature);
initiativeList.getItems().remove(selectedCreature);
}
}
/**Met deze methode wordt een creature die de gebruiker probeert toe te voegen gevallideerd op een aantal
* punten. De creature kan alleen toegevoegd worden als het overal aan voldoet.
*
* @return: true als het overal aan voldoet.
*/
public boolean validateCreature() {
String name = nameTextField.getText();
String initiativeText = initiativeTextField.getText();
String hpText = hpTextField.getText();
String maxHPText = maxHPTextField.getText();
if (name.isEmpty() || initiativeText.isEmpty() || hpText.isEmpty() || maxHPText.isEmpty()) {
showAlert("All fields are required!");
return false;
}
if(initiative != null) {
ArrayList<String> names = initiative.stream().map(Creature::getName).collect(Collectors.toCollection(ArrayList::new));
for (String creatureName : names) {
if(name.equalsIgnoreCase(creatureName)) {
showAlert("This name is already in the initiative list!");
return false;
}
}
}
if (Integer.parseInt(hpText) < 0 || Integer.parseInt(maxHPText) < 0) {
showAlert("You can't add a creature with less then 0 (max) HP.");
return false;
}
if(nameTextField.getText().length() > 20) {
showAlert("The creature's name can't be more then 20 characters long.");
return false;
}
if (Integer.parseInt(hpText) > Integer.parseInt(maxHPText)) {
showAlert("HP can't be higher than max HP!");
return false;
}
return true;
}
public void lowerLegRes(){
int newLegRes = Integer.parseInt(legResTextField.getText()) - 1;
if(newLegRes < 0) {
showAlert("A creature can't have less then 0 legendary resistances!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void addLegRes(){
if(legResTextField.getText().isEmpty()) {
legResTextField.setText("0");
}
int newLegRes = Integer.parseInt(legResTextField.getText()) + 1;
if(newLegRes > 5) {
showAlert("A creature can't have more then 5 legendary resistances in this program!");
return;
}
legResTextField.setText(String.valueOf(newLegRes));
}
public void lowerLegAct(){
int newLegAct = Integer.parseInt(legActTextField.getText()) - 1;
if(newLegAct < 0) {
showAlert("A creature can't have less then 0 legendary actions!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void addLegAct(){
if(legActTextField.getText().isEmpty()) {
legActTextField.setText("0");
}
int newLegAct = Integer.parseInt(legActTextField.getText()) + 1;
if(newLegAct > 5) {
showAlert("A creature can't have more then 5 legendary actions in this program!");
return;
}
legActTextField.setText(String.valueOf(newLegAct));
}
public void doMenu(){
SCENEMANAGER.showMenuScene();
}
/**Geeft een error message als deze methode wordt aangeroepen.
*
* @param message: het bericht dat weergegeven wordt in de error message.
*/
public void showAlert(String message) {
Alert errorMessage = new Alert(Alert.AlertType.ERROR);
errorMessage.setContentText(message);
errorMessage.show();
}
} | True |
3,696 | 27754_20 | /*
This software is OSI Certified Open Source Software.
OSI Certified is a certification mark of the Open Source Initiative.
The license (Mozilla version 1.0) can be read at the MMBase site.
See http://www.MMBase.org/license
*/
package org.mmbase.util;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.util.regex.*;
import org.mmbase.util.logging.Logger;
import org.mmbase.util.logging.Logging;
/**
* Wrapper around the response. It collects all data that is sent to it, and makes it available
* through a toString() method. It is used by taglib's Include-Tag, but it might find more general
* use, outside taglib.
*
* @author Kees Jongenburger
* @author Johannes Verelst
* @author Michiel Meeuwissen
* @since MMBase-1.7
* @version $Id$
*/
public class GenericResponseWrapper extends HttpServletResponseWrapper {
private static final Logger log = Logging.getLoggerInstance(GenericResponseWrapper.class);
/**
* If this pattern matched the first line of an InputStream then it is a XML. The encoding is in
* matching group 1 (when using " as quote) or 2 (when using ' as quote)
*/
private static final Pattern XMLHEADER = Pattern.compile("<\\?xml.*?(?:\\sencoding=(?:\"([^\"]+?)\"|'([^']+?)'))?\\s*\\?>.*", Pattern.DOTALL);
private static String UNSET_CHARSET = "iso-8859-1";
public static String TEXT_XML_DEFAULT_CHARSET = "US-ASCII";
private static String DEFAULT_CONTENTTYPE = "text/html";
private static String[] IGNORED_HEADERS = new String[]{"Last-Modified", "ETag"};
private PrintWriter writer;
private StringWriter string; // wrapped by writer
private ServletOutputStream outputStream; // wrapped by outputStream
private ByteArrayOutputStream bytes;
private String characterEncoding = UNSET_CHARSET;
private HttpServletResponse wrappedResponse;
protected String redirected = null;
/**
* Public constructor
*/
public GenericResponseWrapper(HttpServletResponse resp) {
super(resp);
wrappedResponse = resp; // I don't understand why this object is not super.getResponse();
}
/**
* Sets also a value for the characterEncoding which must be supposed.
* Normally it would be determined automaticly right, but if for some reason it doesn't you can override it.
*/
public GenericResponseWrapper(HttpServletResponse resp, String encoding) {
this(resp);
characterEncoding = encoding;
wrappedResponse = resp; //
}
/**
* Gets the response object which this wrapper is wrapping. You might need this when giving a
* redirect or so.
* @since MMBase-1.7.1
*/
public HttpServletResponse getHttpServletResponse() {
//return (HttpServletResponse) getResponse(); // should work, I think, but doesn't
HttpServletResponse response = wrappedResponse;
while (response instanceof HttpServletResponseWrapper) {
if (response instanceof GenericResponseWrapper) { // if this happens in an 'mm:included' page.
response = ((GenericResponseWrapper) response).wrappedResponse;
} else {
response = (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse();
}
}
return response;
}
private boolean mayAddHeader(String header) {
for (String element : IGNORED_HEADERS) {
if (element.equalsIgnoreCase(header)) {
return false;
}
}
return true;
}
@Override
public void sendRedirect(String location) throws IOException {
redirected = location;
getHttpServletResponse().sendRedirect(location);
}
/**
* @since MMBase-1.8.5
*/
public String getRedirected() {
return redirected;
}
@Override
public void setStatus(int s) {
getHttpServletResponse().setStatus(s);
}
@Override
public void addCookie(Cookie c) {
getHttpServletResponse().addCookie(c);
}
@Override
public void setHeader(String header, String value) {
if (mayAddHeader(header)) {
getHttpServletResponse().setHeader(header,value);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String, long)
*/
@Override
public void addDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String)
*/
@Override
public void addHeader(String arg0, String arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String, int)
*/
@Override
public void addIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
*/
@Override
public boolean containsHeader(String arg0) {
return getHttpServletResponse().containsHeader(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String)
*/
@Override
public String encodeRedirectURL(String arg0) {
return getHttpServletResponse().encodeRedirectURL(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
*/
@Override
public String encodeURL(String arg0) {
return getHttpServletResponse().encodeURL(arg0);
}
/**
* @see javax.servlet.ServletResponse#getLocale()
*/
@Override
public Locale getLocale() {
return getHttpServletResponse().getLocale();
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int, java.lang.String)
*/
@Override
public void sendError(int arg0, String arg1) throws IOException {
getHttpServletResponse().sendError(arg0, arg1);
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
*/
@Override
public void sendError(int arg0) throws IOException {
getHttpServletResponse().sendError(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long)
*/
@Override
public void setDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String, int)
*/
@Override
public void setIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
*/
@Override
public void setLocale(Locale arg0) {
getHttpServletResponse().setLocale(arg0);
}
/**
* Return the OutputStream. This is a 'MyServletOutputStream'.
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputStream != null) return outputStream;
if (writer != null) {
outputStream = new MyServletOutputStream(new WriterOutputStream(writer, characterEncoding));
return outputStream;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
bytes = new ByteArrayOutputStream();
outputStream = new MyServletOutputStream(bytes);
return outputStream;
}
/**
* Return the PrintWriter
*/
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) return writer;
if (outputStream != null) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, characterEncoding)));
return writer;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
string = new StringWriter();
writer = new PrintWriter(string);
return writer;
}
/**
* Sets the content type of the response being sent to the
* client. The content type may include the type of character
* encoding used, for example, text/html; charset=ISO-8859-4. If
* obtaining a PrintWriter, this method should be called first.
*/
@Override
public void setContentType(String ct) {
String contentType = DEFAULT_CONTENTTYPE;
if (ct == null) {
contentType = DEFAULT_CONTENTTYPE;
} else {
contentType = ct;
characterEncoding = getEncoding(ct); // gets char-encoding from content type
if (characterEncoding == null) {
characterEncoding = getDefaultEncoding(contentType);
}
}
if (log.isDebugEnabled()) {
log.debug("set contenttype of include page to: '" + contentType + "' (and character encoding to '" + characterEncoding + "')");
}
}
/**
* Returns the name of the charset used for the MIME body sent in this response.
* If no charset has been assigned, it is implicitly set to ISO-8859-1 (Latin-1).
* See <a href="http://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a> for more information about character encoding and MIME.
* returns the encoding
*/
@Override
public String getCharacterEncoding() {
log.debug(characterEncoding);
/*
if (characterEncoding == UNSET_CHARSET && outputStream != null) {
determinXMLEncoding();
}
*/
return characterEncoding;
}
protected byte[] determinXMLEncoding() {
byte[] allBytes = bytes.toByteArray();
characterEncoding = getXMLEncoding(allBytes);
if (characterEncoding == null) characterEncoding = "UTF-8"; // missing <?xml header, but we _know_ it is XML.
return allBytes;
}
/**
* Return all data that has been written to the PrintWriter.
*/
@Override
public String toString() {
if (string != null) {
return string.toString();
} else if (outputStream != null) {
try {
byte[] allBytes;
if (TEXT_XML_DEFAULT_CHARSET.equals(characterEncoding)) {
// see comments in getDefaultEncoding
allBytes = determinXMLEncoding();
} else {
allBytes = bytes.toByteArray();
}
return new String(allBytes, getCharacterEncoding());
} catch (Exception e) {
return bytes.toString();
}
} else {
return "";
}
}
/**
* Takes a String, which is considered to be (the first) part of an XML, and returns the
* encoding (the specified one, or the XML default)
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (no <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(byte[])
*/
public static String getXMLEncoding(String xmlString) {
Matcher m = XMLHEADER.matcher(xmlString);
if (! m.matches()) {
return null; // No <? xml header found, this file is probably not XML.
} else {
String encoding = m.group(1);
if (encoding == null) encoding = m.group(2);
if (encoding == null) encoding = "UTF-8"; // default encoding for XML.
return encoding;
}
}
/**
* Takes a ByteArrayInputStream, which is considered to be (the first) part of an XML, and returns the encoding.
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (not <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(String)
*/
public static String getXMLEncoding(byte[] allBytes) {
byte[] firstBytes = allBytes;
if (allBytes.length > 100) {
firstBytes = new byte[100];
System.arraycopy(allBytes, 0, firstBytes, 0, 100);
}
try {
return getXMLEncoding(new String(firstBytes, "US-ASCII"));
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen, US-ASCII is known
}
return "UTF-8"; // cannot come here.
}
/**
* Takes the value of a Content-Type header, and tries to find the encoding from it.
* @since MMBase-1.7.1
* @return The found charset if found, otherwise 'null'
*/
public static String getEncoding(String contentType) {
String contentTypeLowerCase = contentType.toLowerCase();
int cs = contentTypeLowerCase.indexOf("charset=");
if (cs > 0) {
return contentType.substring(cs + 8);
} else {
return null;
}
}
/**
* Supposes that no explicit charset is mentioned in a contentType, and returns a default. (UTF-8 or US-ASCII
* for XML types and ISO-8859-1 otherwise).
* @since MMBase-1.7.1
* @return A charset.
*/
public static String getDefaultEncoding(String contentType) {
if ("text/xml".equals(contentType)) {
return TEXT_XML_DEFAULT_CHARSET; // = us-ascii, See
// http://www.rfc-editor.org/rfc/rfc3023.txt. We will
// ignore it, because if not not ascii, it will never
// work, and all known charset are superset of us-ascii
// (so the response _is_ correct it will work).
} else if ("application/xml".equals(contentType) || "application/xhtml+xml".equals(contentType)) {
return "UTF-8";
} else {
return "iso-8859-1";
}
}
}
/**
* Implements ServletOutputStream.
*/
class MyServletOutputStream extends ServletOutputStream {
private OutputStream stream;
public MyServletOutputStream(OutputStream output) {
stream = output;
}
public void write(int b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
}
| mmbase/mmbase-utils | src/main/java/org/mmbase/util/GenericResponseWrapper.java | 4,077 | /**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
*/ | block_comment | nl | /*
This software is OSI Certified Open Source Software.
OSI Certified is a certification mark of the Open Source Initiative.
The license (Mozilla version 1.0) can be read at the MMBase site.
See http://www.MMBase.org/license
*/
package org.mmbase.util;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Locale;
import java.util.regex.*;
import org.mmbase.util.logging.Logger;
import org.mmbase.util.logging.Logging;
/**
* Wrapper around the response. It collects all data that is sent to it, and makes it available
* through a toString() method. It is used by taglib's Include-Tag, but it might find more general
* use, outside taglib.
*
* @author Kees Jongenburger
* @author Johannes Verelst
* @author Michiel Meeuwissen
* @since MMBase-1.7
* @version $Id$
*/
public class GenericResponseWrapper extends HttpServletResponseWrapper {
private static final Logger log = Logging.getLoggerInstance(GenericResponseWrapper.class);
/**
* If this pattern matched the first line of an InputStream then it is a XML. The encoding is in
* matching group 1 (when using " as quote) or 2 (when using ' as quote)
*/
private static final Pattern XMLHEADER = Pattern.compile("<\\?xml.*?(?:\\sencoding=(?:\"([^\"]+?)\"|'([^']+?)'))?\\s*\\?>.*", Pattern.DOTALL);
private static String UNSET_CHARSET = "iso-8859-1";
public static String TEXT_XML_DEFAULT_CHARSET = "US-ASCII";
private static String DEFAULT_CONTENTTYPE = "text/html";
private static String[] IGNORED_HEADERS = new String[]{"Last-Modified", "ETag"};
private PrintWriter writer;
private StringWriter string; // wrapped by writer
private ServletOutputStream outputStream; // wrapped by outputStream
private ByteArrayOutputStream bytes;
private String characterEncoding = UNSET_CHARSET;
private HttpServletResponse wrappedResponse;
protected String redirected = null;
/**
* Public constructor
*/
public GenericResponseWrapper(HttpServletResponse resp) {
super(resp);
wrappedResponse = resp; // I don't understand why this object is not super.getResponse();
}
/**
* Sets also a value for the characterEncoding which must be supposed.
* Normally it would be determined automaticly right, but if for some reason it doesn't you can override it.
*/
public GenericResponseWrapper(HttpServletResponse resp, String encoding) {
this(resp);
characterEncoding = encoding;
wrappedResponse = resp; //
}
/**
* Gets the response object which this wrapper is wrapping. You might need this when giving a
* redirect or so.
* @since MMBase-1.7.1
*/
public HttpServletResponse getHttpServletResponse() {
//return (HttpServletResponse) getResponse(); // should work, I think, but doesn't
HttpServletResponse response = wrappedResponse;
while (response instanceof HttpServletResponseWrapper) {
if (response instanceof GenericResponseWrapper) { // if this happens in an 'mm:included' page.
response = ((GenericResponseWrapper) response).wrappedResponse;
} else {
response = (HttpServletResponse) ((HttpServletResponseWrapper) response).getResponse();
}
}
return response;
}
private boolean mayAddHeader(String header) {
for (String element : IGNORED_HEADERS) {
if (element.equalsIgnoreCase(header)) {
return false;
}
}
return true;
}
@Override
public void sendRedirect(String location) throws IOException {
redirected = location;
getHttpServletResponse().sendRedirect(location);
}
/**
* @since MMBase-1.8.5
*/
public String getRedirected() {
return redirected;
}
@Override
public void setStatus(int s) {
getHttpServletResponse().setStatus(s);
}
@Override
public void addCookie(Cookie c) {
getHttpServletResponse().addCookie(c);
}
@Override
public void setHeader(String header, String value) {
if (mayAddHeader(header)) {
getHttpServletResponse().setHeader(header,value);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addDateHeader(java.lang.String, long)
*/
@Override
public void addDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addHeader(java.lang.String, java.lang.String)
*/
@Override
public void addHeader(String arg0, String arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#addIntHeader(java.lang.String, int)
*/
@Override
public void addIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().addIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#containsHeader(java.lang.String)
*/
@Override
public boolean containsHeader(String arg0) {
return getHttpServletResponse().containsHeader(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeRedirectURL(java.lang.String)
*/
@Override
public String encodeRedirectURL(String arg0) {
return getHttpServletResponse().encodeRedirectURL(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#encodeURL(java.lang.String)
*/
@Override
public String encodeURL(String arg0) {
return getHttpServletResponse().encodeURL(arg0);
}
/**
* @see javax.servlet.ServletResponse#getLocale()
*/
@Override
public Locale getLocale() {
return getHttpServletResponse().getLocale();
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int, java.lang.String)
*/
@Override
public void sendError(int arg0, String arg1) throws IOException {
getHttpServletResponse().sendError(arg0, arg1);
}
/**
* @see javax.servlet.http.HttpServletResponse#sendError(int)
<SUF>*/
@Override
public void sendError(int arg0) throws IOException {
getHttpServletResponse().sendError(arg0);
}
/**
* @see javax.servlet.http.HttpServletResponse#setDateHeader(java.lang.String, long)
*/
@Override
public void setDateHeader(String arg0, long arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setDateHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.http.HttpServletResponse#setIntHeader(java.lang.String, int)
*/
@Override
public void setIntHeader(String arg0, int arg1) {
if (mayAddHeader(arg0)) {
getHttpServletResponse().setIntHeader(arg0, arg1);
}
}
/**
* @see javax.servlet.ServletResponse#setLocale(java.util.Locale)
*/
@Override
public void setLocale(Locale arg0) {
getHttpServletResponse().setLocale(arg0);
}
/**
* Return the OutputStream. This is a 'MyServletOutputStream'.
*/
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (outputStream != null) return outputStream;
if (writer != null) {
outputStream = new MyServletOutputStream(new WriterOutputStream(writer, characterEncoding));
return outputStream;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
bytes = new ByteArrayOutputStream();
outputStream = new MyServletOutputStream(bytes);
return outputStream;
}
/**
* Return the PrintWriter
*/
@Override
public PrintWriter getWriter() throws IOException {
if (writer != null) return writer;
if (outputStream != null) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, characterEncoding)));
return writer;
//throw new RuntimeException("Should use getOutputStream _or_ getWriter");
}
string = new StringWriter();
writer = new PrintWriter(string);
return writer;
}
/**
* Sets the content type of the response being sent to the
* client. The content type may include the type of character
* encoding used, for example, text/html; charset=ISO-8859-4. If
* obtaining a PrintWriter, this method should be called first.
*/
@Override
public void setContentType(String ct) {
String contentType = DEFAULT_CONTENTTYPE;
if (ct == null) {
contentType = DEFAULT_CONTENTTYPE;
} else {
contentType = ct;
characterEncoding = getEncoding(ct); // gets char-encoding from content type
if (characterEncoding == null) {
characterEncoding = getDefaultEncoding(contentType);
}
}
if (log.isDebugEnabled()) {
log.debug("set contenttype of include page to: '" + contentType + "' (and character encoding to '" + characterEncoding + "')");
}
}
/**
* Returns the name of the charset used for the MIME body sent in this response.
* If no charset has been assigned, it is implicitly set to ISO-8859-1 (Latin-1).
* See <a href="http://www.ietf.org/rfc/rfc2047.txt">RFC 2047</a> for more information about character encoding and MIME.
* returns the encoding
*/
@Override
public String getCharacterEncoding() {
log.debug(characterEncoding);
/*
if (characterEncoding == UNSET_CHARSET && outputStream != null) {
determinXMLEncoding();
}
*/
return characterEncoding;
}
protected byte[] determinXMLEncoding() {
byte[] allBytes = bytes.toByteArray();
characterEncoding = getXMLEncoding(allBytes);
if (characterEncoding == null) characterEncoding = "UTF-8"; // missing <?xml header, but we _know_ it is XML.
return allBytes;
}
/**
* Return all data that has been written to the PrintWriter.
*/
@Override
public String toString() {
if (string != null) {
return string.toString();
} else if (outputStream != null) {
try {
byte[] allBytes;
if (TEXT_XML_DEFAULT_CHARSET.equals(characterEncoding)) {
// see comments in getDefaultEncoding
allBytes = determinXMLEncoding();
} else {
allBytes = bytes.toByteArray();
}
return new String(allBytes, getCharacterEncoding());
} catch (Exception e) {
return bytes.toString();
}
} else {
return "";
}
}
/**
* Takes a String, which is considered to be (the first) part of an XML, and returns the
* encoding (the specified one, or the XML default)
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (no <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(byte[])
*/
public static String getXMLEncoding(String xmlString) {
Matcher m = XMLHEADER.matcher(xmlString);
if (! m.matches()) {
return null; // No <? xml header found, this file is probably not XML.
} else {
String encoding = m.group(1);
if (encoding == null) encoding = m.group(2);
if (encoding == null) encoding = "UTF-8"; // default encoding for XML.
return encoding;
}
}
/**
* Takes a ByteArrayInputStream, which is considered to be (the first) part of an XML, and returns the encoding.
* @return The XML Encoding, or <code>null</code> if the String was not recognized as XML (not <?xml> header found)
* @since MMBase-1.7.1
* @see #getXMLEncoding(String)
*/
public static String getXMLEncoding(byte[] allBytes) {
byte[] firstBytes = allBytes;
if (allBytes.length > 100) {
firstBytes = new byte[100];
System.arraycopy(allBytes, 0, firstBytes, 0, 100);
}
try {
return getXMLEncoding(new String(firstBytes, "US-ASCII"));
} catch (java.io.UnsupportedEncodingException uee) {
// cannot happen, US-ASCII is known
}
return "UTF-8"; // cannot come here.
}
/**
* Takes the value of a Content-Type header, and tries to find the encoding from it.
* @since MMBase-1.7.1
* @return The found charset if found, otherwise 'null'
*/
public static String getEncoding(String contentType) {
String contentTypeLowerCase = contentType.toLowerCase();
int cs = contentTypeLowerCase.indexOf("charset=");
if (cs > 0) {
return contentType.substring(cs + 8);
} else {
return null;
}
}
/**
* Supposes that no explicit charset is mentioned in a contentType, and returns a default. (UTF-8 or US-ASCII
* for XML types and ISO-8859-1 otherwise).
* @since MMBase-1.7.1
* @return A charset.
*/
public static String getDefaultEncoding(String contentType) {
if ("text/xml".equals(contentType)) {
return TEXT_XML_DEFAULT_CHARSET; // = us-ascii, See
// http://www.rfc-editor.org/rfc/rfc3023.txt. We will
// ignore it, because if not not ascii, it will never
// work, and all known charset are superset of us-ascii
// (so the response _is_ correct it will work).
} else if ("application/xml".equals(contentType) || "application/xhtml+xml".equals(contentType)) {
return "UTF-8";
} else {
return "iso-8859-1";
}
}
}
/**
* Implements ServletOutputStream.
*/
class MyServletOutputStream extends ServletOutputStream {
private OutputStream stream;
public MyServletOutputStream(OutputStream output) {
stream = output;
}
public void write(int b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b) throws IOException {
stream.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
stream.write(b, off, len);
}
}
| False |
3,335 | 47139_3 | package src.engine.core.tools;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.sound.sampled.*;
public class MusicPlayer {
// enum for sound effects
public enum SoundEffect {
//Pistol SFX
MORE_BULLETS("src/sound/guns/moreBullets.wav"),
BIGGER_GUN("src/sound/guns/biggerWeapons.wav"),
PICKUP_PISTOL("src/sound/guns/pistol/pickupPistol.wav"),
SHOOT_PISTOL("src/sound/guns/pistol/pistolShot.wav"),
RELOAD_PISTOL("src/sound/guns/pistol/pistolReload.wav"),
//Shotgun SFX
PICKUP_SHOTGUN("src/sound/guns/shotgun/pickupShotgun.wav"),
SHOOT_SHOTGUN("src/sound/guns/shotgun/shotgunShot.wav"),
RELOAD_SHOTGUN("src/sound/guns/shotgun/reloadShotgun.wav"),
//AK SFX
SHOOT_AK("src/sound/guns/AKM/AKM_shoot.wav"),
PICKUP_AK("src/sound/guns/AKM/AKM_rack.wav"),
RELOAD_AK("src/sound/guns/AKM/AKM_reload.wav"),
//Sniper SFX
SHOOT_SNIPER("src/sound/guns/sniper/sniperShot.wav"),
PICKUP_SNIPER("src/sound/guns/sniper/sniperPickup.wav"),
RELOAD_SNIPER("src/sound/guns/sniper/sniperReload.wav"),
SCOPE("src/sound/guns/sniper/scope.wav"),
Knife("src/sound/misc/knife.wav"),
//Round over SFX
LEVEL_FINISHED("src/sound/misc/newRound.wav"),
//player Death SFX
GAME_OVER("src/sound/misc/gameOver.wav"),
//Enemy SFX
GE_DEATH("src/sound/enemies/groundEnemy/groundEnemy_death.wav"),
GUNNER_DEATH("src/sound/enemies/gunTurret/gunTurret_death.wav"),
SIGHSEEKER_ATTACK("src/sound/misc/shoot.wav"),
SIGHTSEEKER_DEATH("src/sound/enemies/sightSeeker/sightSeeker_death.wav"),
MALTESEEKER_RANDOMTALK1("src/sound/enemies/malteSeeker/Alter_marcel.wav"),
MALTESEEKER_RANDOMTALK2("src/sound/enemies/malteSeeker/Alter_marcel_tief_schnell.wav"),
MALTESEEKER_SPAWN_AND_ATTACK("src/sound/enemies/malteSeeker/hallo.wav"),
MALTESEEKER_RANDOMTALK3("src/sound/enemies/malteSeeker/Marcel_ist_immer_schuld.wav");
private final String path;
SoundEffect(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
private static volatile MusicPlayer instance;
private ExecutorService threadPool;
private HashMap<String, Clip> soundClips;
public float volume = 0.8f;
private MusicPlayer() {
threadPool = Executors.newCachedThreadPool();
soundClips = new HashMap<>();
// Initialize resources
}
//adjust volume
public void changeVolume(float volume) {
this.volume = volume;
}
public void setVolume(Clip clip){
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
double gain = volume; // number between 0 and 1 (loudest)
float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
//singleton
public static MusicPlayer getInstance() {
if (instance == null) {
synchronized (MusicPlayer.class) {
if (instance == null)
instance = new MusicPlayer();
}
}
return instance;
}
public void playSound(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
setVolume(clip);
clip.start();
});
}
public void playSound(SoundEffect sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound.getPath()); // Implement loadClip to load and return a Clip
soundClips.put(sound.getPath(), clip);
setVolume(clip);
clip.start();
});
}
public void playRandomPlayerSound() {
String[] playerSounds = {"src/sound/player/player_damage_1.wav",
"src/sound/player/player_damage_2.wav",
"src/sound/player/player_damage_3.wav",
"src/sound/player/player_damage_4.wav",
"src/sound/player/player_damage_5.wav",
"src/sound/player/player_damage_6.wav",
"src/sound/player/player_damage_7.wav",
"src/sound/player/player_damage_8.wav"
};
threadPool.execute(() -> {
int random = (int) (Math.random() * playerSounds.length);
Clip clip = loadClip(playerSounds[random]); // Implement loadClip to load and return a Clip
soundClips.put(playerSounds[random], clip);
setVolume(clip);
clip.start();
});
}
private Clip loadClip(String filePath) {
try {
// Open an audio input stream from the file path
File audioFile = new File(filePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Get a clip resource
Clip clip = AudioSystem.getClip();
// Open the clip and load samples from the audio input stream
clip.open(audioStream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace(); // Handle exceptions appropriately
return null;
}
}
public void loopMusic(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
clip.loop(Clip.LOOP_CONTINUOUSLY);
});
}
public void pauseResume(String sound) {
threadPool.execute(() -> {
Clip clip = soundClips.get(sound);
setVolume(clip);
if (clip.isActive()) {
clip.stop();
} else {
clip.start();
}
});
}
public void stopGameMusic(){
for (Clip clip : soundClips.values()) {
if (clip.isRunning()) {
clip.stop(); // Stop the clip if it is running
}
clip.close(); // Close the clip to release resources
}
soundClips.clear();
}
}
| kastanileel/CPUCrunchEngine | src/engine/core/tools/MusicPlayer.java | 2,123 | // number between 0 and 1 (loudest) | line_comment | nl | package src.engine.core.tools;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.sound.sampled.*;
public class MusicPlayer {
// enum for sound effects
public enum SoundEffect {
//Pistol SFX
MORE_BULLETS("src/sound/guns/moreBullets.wav"),
BIGGER_GUN("src/sound/guns/biggerWeapons.wav"),
PICKUP_PISTOL("src/sound/guns/pistol/pickupPistol.wav"),
SHOOT_PISTOL("src/sound/guns/pistol/pistolShot.wav"),
RELOAD_PISTOL("src/sound/guns/pistol/pistolReload.wav"),
//Shotgun SFX
PICKUP_SHOTGUN("src/sound/guns/shotgun/pickupShotgun.wav"),
SHOOT_SHOTGUN("src/sound/guns/shotgun/shotgunShot.wav"),
RELOAD_SHOTGUN("src/sound/guns/shotgun/reloadShotgun.wav"),
//AK SFX
SHOOT_AK("src/sound/guns/AKM/AKM_shoot.wav"),
PICKUP_AK("src/sound/guns/AKM/AKM_rack.wav"),
RELOAD_AK("src/sound/guns/AKM/AKM_reload.wav"),
//Sniper SFX
SHOOT_SNIPER("src/sound/guns/sniper/sniperShot.wav"),
PICKUP_SNIPER("src/sound/guns/sniper/sniperPickup.wav"),
RELOAD_SNIPER("src/sound/guns/sniper/sniperReload.wav"),
SCOPE("src/sound/guns/sniper/scope.wav"),
Knife("src/sound/misc/knife.wav"),
//Round over SFX
LEVEL_FINISHED("src/sound/misc/newRound.wav"),
//player Death SFX
GAME_OVER("src/sound/misc/gameOver.wav"),
//Enemy SFX
GE_DEATH("src/sound/enemies/groundEnemy/groundEnemy_death.wav"),
GUNNER_DEATH("src/sound/enemies/gunTurret/gunTurret_death.wav"),
SIGHSEEKER_ATTACK("src/sound/misc/shoot.wav"),
SIGHTSEEKER_DEATH("src/sound/enemies/sightSeeker/sightSeeker_death.wav"),
MALTESEEKER_RANDOMTALK1("src/sound/enemies/malteSeeker/Alter_marcel.wav"),
MALTESEEKER_RANDOMTALK2("src/sound/enemies/malteSeeker/Alter_marcel_tief_schnell.wav"),
MALTESEEKER_SPAWN_AND_ATTACK("src/sound/enemies/malteSeeker/hallo.wav"),
MALTESEEKER_RANDOMTALK3("src/sound/enemies/malteSeeker/Marcel_ist_immer_schuld.wav");
private final String path;
SoundEffect(String path) {
this.path = path;
}
public String getPath() {
return path;
}
}
private static volatile MusicPlayer instance;
private ExecutorService threadPool;
private HashMap<String, Clip> soundClips;
public float volume = 0.8f;
private MusicPlayer() {
threadPool = Executors.newCachedThreadPool();
soundClips = new HashMap<>();
// Initialize resources
}
//adjust volume
public void changeVolume(float volume) {
this.volume = volume;
}
public void setVolume(Clip clip){
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
double gain = volume; // number between<SUF>
float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
gainControl.setValue(dB);
}
//singleton
public static MusicPlayer getInstance() {
if (instance == null) {
synchronized (MusicPlayer.class) {
if (instance == null)
instance = new MusicPlayer();
}
}
return instance;
}
public void playSound(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
setVolume(clip);
clip.start();
});
}
public void playSound(SoundEffect sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound.getPath()); // Implement loadClip to load and return a Clip
soundClips.put(sound.getPath(), clip);
setVolume(clip);
clip.start();
});
}
public void playRandomPlayerSound() {
String[] playerSounds = {"src/sound/player/player_damage_1.wav",
"src/sound/player/player_damage_2.wav",
"src/sound/player/player_damage_3.wav",
"src/sound/player/player_damage_4.wav",
"src/sound/player/player_damage_5.wav",
"src/sound/player/player_damage_6.wav",
"src/sound/player/player_damage_7.wav",
"src/sound/player/player_damage_8.wav"
};
threadPool.execute(() -> {
int random = (int) (Math.random() * playerSounds.length);
Clip clip = loadClip(playerSounds[random]); // Implement loadClip to load and return a Clip
soundClips.put(playerSounds[random], clip);
setVolume(clip);
clip.start();
});
}
private Clip loadClip(String filePath) {
try {
// Open an audio input stream from the file path
File audioFile = new File(filePath);
AudioInputStream audioStream = AudioSystem.getAudioInputStream(audioFile);
// Get a clip resource
Clip clip = AudioSystem.getClip();
// Open the clip and load samples from the audio input stream
clip.open(audioStream);
return clip;
} catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
e.printStackTrace(); // Handle exceptions appropriately
return null;
}
}
public void loopMusic(String sound) {
threadPool.execute(() -> {
Clip clip = loadClip(sound); // Implement loadClip to load and return a Clip
soundClips.put(sound, clip);
clip.loop(Clip.LOOP_CONTINUOUSLY);
});
}
public void pauseResume(String sound) {
threadPool.execute(() -> {
Clip clip = soundClips.get(sound);
setVolume(clip);
if (clip.isActive()) {
clip.stop();
} else {
clip.start();
}
});
}
public void stopGameMusic(){
for (Clip clip : soundClips.values()) {
if (clip.isRunning()) {
clip.stop(); // Stop the clip if it is running
}
clip.close(); // Close the clip to release resources
}
soundClips.clear();
}
}
| False |
3,558 | 10984_12 | package com.nedap.go.server;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.nedap.go.Game;
import com.nedap.go.Player;
public class GameHandler extends Thread {
private volatile List<ClientHandler> cHandlers;
private Player[] players; // players in the game
private Game game;
private int gameID;
private ClientHandler black; // colour = 1
private ClientHandler white; // colour = 2
private final int pass = -1;
// variables to set up game
private int handshakesCount;
private int boardsize;
private String player1; // name of first player to send handshake
private String player2; // name of second player to send handshake
private ClientHandler leader;
private ClientHandler opponant;
private int prefColour;
private int rematchCount;
private int setRematch;
// States
private boolean isFinished;
private boolean isConfigured;
private boolean isWaiting;
// lengths commands
private final int handshakeL = 2;
private final int setConfigL = 4;
private final int rematchL = 2;
private final int moveL = 4;
private final int exitL = 3;
// errors
private final String unknown = "UNKNOWN_COMMAND+";
private final String invalidM = "INVALID_MOVE+";
//-------------- Constructor ------------------------------------
public GameHandler(int gameID) {
this.gameID = gameID;
isFinished = false;
isConfigured = false;
handshakesCount = 0;
rematchCount = 0;
player1 = "";
player2 = "";
cHandlers = new CopyOnWriteArrayList<ClientHandler>();
isWaiting = false;
}
//-------------- Run ---------------------------------------
public void run() {
System.out.println("runGame started");
while (!isFinished) {
for (ClientHandler player : cHandlers) {
String input = player.readQueue();
this.handleInput(input, player);
}
}
// TODO: als iemand weg gaat, gameFinished try en verwijder diegene uit lijst
}
private void handleInput(String line, ClientHandler player) {
if (line.startsWith("EXIT") || line.equals("FAIL")) {
this.handleExitAndDisconnect(line, player);
} else if (!isConfigured && handshakesCount <= 2) {
this.configGame(line, player);
} else if (isConfigured) {
this.playGame(line, player);
} else {
System.out.println("No input expected, but received: " + line);
}
}
// --------------- Handle user input before game -----------------------------
private void configGame(String input, ClientHandler player) {
if (input.equals("EmptyQueue")) {
// TODO: als langer dan ... niet reageert dan eruit
} else if (input.startsWith("HANDSHAKE")) {
System.out.println("Server received handshake");
this.checkHandshakes(input, player);
} else if (input.startsWith("SET_CONFIG") && player.equals(leader)) {
System.out.println("Server received set configuration ");
this.checkSetConfig(input, player);
} else {
player.sendMessage("UNKNOWN_COMMAND+Handshake or "
+ "set_config required");
}
}
public void checkHandshakes(String input, ClientHandler player) {
String[] handshake = input.split("\\+");
if (handshake.length == handshakeL) {
if (handshakesCount == 0) {
player1 = handshake[1];
leader = player;
player.sendMessage("ACKNOWLEDGE_HANDSHAKE+" + gameID + "+" + 1);
player.sendMessage("REQUEST_CONFIG+Please provide a preferred configuration. "
+ "(preferred colour and board size");
System.out.println("Config requested");
handshakesCount++;
} else if (handshakesCount == 1) {
player2 = handshake[1];
opponant = player;
player.sendMessage("ACKNOWLEDGE_HANDSHAKE+" + gameID + "+" + 0);
System.out.println("Second player found");
handshakesCount++;
if (isWaiting == true) {
createGame();
sendAckConfig();
isConfigured = true;
System.out.println("No longer waiting on second player, configuration is done");
}
}
} else {
player.sendMessage(unknown + "Handshake command length is not 2");
}
}
public void checkSetConfig(String input, ClientHandler player) {
String[] setConfig = input.split("\\+");
if (player.equals(leader)) {
if (setConfig.length == setConfigL && setConfig[1].equals(Integer.toString(gameID))) {
prefColour = Integer.parseInt(setConfig[2]);
if (prefColour == 1 || prefColour == 2) {
boardsize = Integer.parseInt(setConfig[3]);
System.out.println("Set config is received");
if (handshakesCount == 2) {
createGame();
sendAckConfig();
isConfigured = true;
System.out.println("Ack config is send");
} else {
isWaiting = true;
System.out.println("Waiting on second player");
}
} else {
player.sendMessage(unknown + "preffered colour needs to be 1 or 2");
}
} else {
player.sendMessage(unknown + "Set config command length is not 4 "
+ "or gameID is incorrect");
}
} else {
player.sendMessage("you are not the leader of this game, wait for opponant"
+ " to configurate this game");
}
}
public void createGame() {
if (this.full()) {
players = new Player[2];
if (prefColour == 1) {
players[0] = new Player(player1, prefColour);
players[1] = new Player(player2, 2);
black = leader;
white = opponant;
} else {
players[0] = new Player(player2, 1);
players[1] = new Player(player1, prefColour);
black = opponant;
white = leader;
}
game = new Game(players, boardsize, gameID);
}
}
public void sendAckConfig() {
//ACKNOWLEDGE_CONFIG+$PLAYER_NAME+$COLOR+$SIZE+$GAME_SATE+$OPPONENT
String gameState = "PLAYING" + ";" + game.currentPlayer() + ";" + game.getCurrentBoard();
String messageblack = "ACKNOWLEDGE_CONFIG+" + players[0].getName() + "+" + "1+"
+ game.getBoardSizeN() + "+" + gameState + "+" + players[1].getName();
String messagewhite = "ACKNOWLEDGE_CONFIG+" + players[1].getName() + "+" + "2+"
+ game.getBoardSizeN() + "+" + gameState + "+" + players[0].getName();
black.sendMessage(messageblack);
white.sendMessage(messagewhite);
}
// ---------------- Handle user input when game is started --------------
private void playGame(String input, ClientHandler player) {
if (game.currentPlayer() == 1 && player.equals(black)) {
if (input != "EmptyQueue") {
this.handleGame(input, player);
}
} else if (game.currentPlayer() == 2 && player.equals(white)) {
if (input != "EmptyQueue") {
this.handleGame(input, player);
}
} else {
//TODO: het is niet jouw beurt
}
if (game.isFinished()) {
System.out.println("Game is finished");
sendGameFinished(game.determineWinner(), "Game ended");
handleRequestRematch();
}
}
public void handleGame(String input, ClientHandler colour) {
if (input.startsWith("MOVE")) {
this.handleMove(input, colour);
} else {
colour.sendMessage((unknown + "Please enter MOVE or EXIT command"));
}
}
public void handleMove(String input, ClientHandler colour) {
//MOVE+$GAME_ID+$PLAYER_NAME+$TILE_INDEX
Player playingPlayer;
int capturedColour;
if (colour.equals(black)) {
playingPlayer = players[0];
capturedColour = players[1].getColour();
} else {
playingPlayer = players[1];
capturedColour = players[0].getColour();
}
String[] move = input.split("\\+");
if (move.length == moveL) {
int moveInt = Integer.parseInt(move[3]);
// TODO: try
if (move[1].equals(Integer.toString(gameID)) &&
move[2].equals(playingPlayer.getName())) {
if (moveInt == pass) {
game.doPass();
sendAckMove(pass, playingPlayer.getColour());
} else {
if (game.isValidMove(moveInt, playingPlayer.getColour()).equals("Move valid")) {
game.doMove(moveInt, playingPlayer.getColour());
game.removeCaptured(capturedColour, playingPlayer.getColour(), game.getBoard());
// need to check both ways since you can suicide a group and don't recreate
// a previous board state (since the other player did moves)
game.removeCaptured(playingPlayer.getColour(), capturedColour, game.getBoard());
game.addCurrentBoardToHistory();
sendAckMove(moveInt, playingPlayer.getColour());
} else {
colour.sendMessage(invalidM +
game.isValidMove(moveInt, playingPlayer.getColour()));
}
}
} else {
colour.sendMessage(invalidM + "GameID is not correct or "
+ "you are not the current player");
}
} else {
System.out.println(unknown + "Move command length is not 4");
}
}
public void sendAckMove(int move, int colour) {
// ACKNOWLEDGE_MOVE+$GAME_ID+$MOVE+$GAME_STATE
String status;
if (game.isFinished()) {
status = "FINISHED";
} else {
status = "PLAYING";
}
String gameState = status + ";" + game.currentPlayer() + ";" + game.getCurrentBoard();
String message = "ACKNOWLEDGE_MOVE+" + gameID + "+" + move + ";" + colour + "+" + gameState;
black.sendMessage(message);
white.sendMessage(message);
}
public void sendGameFinished(String winner, String reason) {
// GAME_FINISHED+$GAME_ID+$WINNER+$SCORE+$MESSAGE
String message = "GAME_FINISHED+" + gameID + "+" + winner + "+"
+ game.getScore(1) + ";" + game.getScore(2) + "+" + reason;
for (ClientHandler player: cHandlers) {
player.sendMessage(message);
}
// TODO: dit moet niet hier?
// this.isFinished = true;
}
// --------------------- exit -------------------------
public void handleExitAndDisconnect(String input, ClientHandler colour) {
// EXIT+$GAME_ID+$PLAYER_NAME
System.out.println("An exit or disconnect is received");
Player exitPlayer;
Player winner;
if (colour.equals(black)) {
exitPlayer = players[0];
winner = players[1];
} else {
exitPlayer = players[1];
winner = players[0];
}
System.out.println("Determined winner");
if (input.startsWith("EXIT")) {
String[] exit = input.split("\\+");
if (exit.length == exitL && exit[1].equals(Integer.toString(gameID)) &&
exit[2].equals(exitPlayer.getName())) {
System.out.println("EXIT correct");
colour.shutdown();
System.out.println("Shutdown clienthandler");
this.removeClientHandler(colour);
System.out.println("Removed clienthandler");
sendGameFinished(winner.getName(), (exitPlayer.getName() + "left the game"));
System.out.println("Send game finished");
this.handleRequestRematch();
} else {
System.out.println(unknown + "Exit command length, GameID and/or player "
+ "name is not correct");
}
} else if (input.equals("FAIL")) {
colour.shutdown();
this.removeClientHandler(colour);
sendGameFinished(winner.getName(), exitPlayer.getName() + " left the game");
this.handleRequestRematch();
}
}
// -------------------- Handle rematch -------------------------
public void handleRequestRematch() {
this.sendRequestRematch();
System.out.println("Request for rematch send");
setRematch = 0;
while (setRematch != this.cHandlers.size()) {
this.readSetRematch();
}
if (rematchCount == this.cHandlers.size()) {
this.resetGame();
} else {
for (ClientHandler player: cHandlers) {
player.sendMessage("ACKNOWLEDGE_REMATCH+0");
System.out.println("No rematch");
System.out.println("Acknowledge rematch send to player");
player.shutdown();
this.removeClientHandler(player);
}
isFinished = true;
}
}
public void sendRequestRematch() {
for (ClientHandler player: cHandlers) {
player.sendMessage("REQUEST_REMATCH");
}
}
public void readSetRematch() {
for (ClientHandler player: cHandlers) {
String input = player.readQueue();
if (!input.equals("EmptyQueue")) {
this.handleSetRematch(input);
setRematch++;
System.out.println("A set rematch received");
}
}
}
public void resetGame() {
System.out.println("Game will now be reset");
for (ClientHandler player: cHandlers) {
player.sendMessage("ACKNOWLEDGE_REMATCH+1");
}
System.out.println("Acknowledge rematch sent to players");
isFinished = false;
isConfigured = false;
handshakesCount = 0;
rematchCount = 0;
player1 = "";
player2 = "";
isWaiting = false;
}
public void handleSetRematch(String input) {
String[] setRematchInput = input.split("\\+");
if (setRematchInput.length == rematchL) {
if (setRematchInput[1].equals("1")) {
rematchCount++;
}
} else {
System.out.println(unknown + "Set rematch command length is not 2");
}
}
// -------------- Queries ---------------------------------------
public List<ClientHandler> getClientHandlers() {
return cHandlers;
}
public boolean full() {
return cHandlers.size() == 2;
}
public boolean empty() {
return cHandlers.size() == 0;
}
public void addClientHandler(ClientHandler player) {
cHandlers.add(player);
}
public void removeClientHandler(ClientHandler player) {
cHandlers.remove(player);
}
}
| marijelinthorst/Final-Assigment-Go-Game | src/main/java/com/nedap/go/server/GameHandler.java | 4,328 | //TODO: het is niet jouw beurt | line_comment | nl | package com.nedap.go.server;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import com.nedap.go.Game;
import com.nedap.go.Player;
public class GameHandler extends Thread {
private volatile List<ClientHandler> cHandlers;
private Player[] players; // players in the game
private Game game;
private int gameID;
private ClientHandler black; // colour = 1
private ClientHandler white; // colour = 2
private final int pass = -1;
// variables to set up game
private int handshakesCount;
private int boardsize;
private String player1; // name of first player to send handshake
private String player2; // name of second player to send handshake
private ClientHandler leader;
private ClientHandler opponant;
private int prefColour;
private int rematchCount;
private int setRematch;
// States
private boolean isFinished;
private boolean isConfigured;
private boolean isWaiting;
// lengths commands
private final int handshakeL = 2;
private final int setConfigL = 4;
private final int rematchL = 2;
private final int moveL = 4;
private final int exitL = 3;
// errors
private final String unknown = "UNKNOWN_COMMAND+";
private final String invalidM = "INVALID_MOVE+";
//-------------- Constructor ------------------------------------
public GameHandler(int gameID) {
this.gameID = gameID;
isFinished = false;
isConfigured = false;
handshakesCount = 0;
rematchCount = 0;
player1 = "";
player2 = "";
cHandlers = new CopyOnWriteArrayList<ClientHandler>();
isWaiting = false;
}
//-------------- Run ---------------------------------------
public void run() {
System.out.println("runGame started");
while (!isFinished) {
for (ClientHandler player : cHandlers) {
String input = player.readQueue();
this.handleInput(input, player);
}
}
// TODO: als iemand weg gaat, gameFinished try en verwijder diegene uit lijst
}
private void handleInput(String line, ClientHandler player) {
if (line.startsWith("EXIT") || line.equals("FAIL")) {
this.handleExitAndDisconnect(line, player);
} else if (!isConfigured && handshakesCount <= 2) {
this.configGame(line, player);
} else if (isConfigured) {
this.playGame(line, player);
} else {
System.out.println("No input expected, but received: " + line);
}
}
// --------------- Handle user input before game -----------------------------
private void configGame(String input, ClientHandler player) {
if (input.equals("EmptyQueue")) {
// TODO: als langer dan ... niet reageert dan eruit
} else if (input.startsWith("HANDSHAKE")) {
System.out.println("Server received handshake");
this.checkHandshakes(input, player);
} else if (input.startsWith("SET_CONFIG") && player.equals(leader)) {
System.out.println("Server received set configuration ");
this.checkSetConfig(input, player);
} else {
player.sendMessage("UNKNOWN_COMMAND+Handshake or "
+ "set_config required");
}
}
public void checkHandshakes(String input, ClientHandler player) {
String[] handshake = input.split("\\+");
if (handshake.length == handshakeL) {
if (handshakesCount == 0) {
player1 = handshake[1];
leader = player;
player.sendMessage("ACKNOWLEDGE_HANDSHAKE+" + gameID + "+" + 1);
player.sendMessage("REQUEST_CONFIG+Please provide a preferred configuration. "
+ "(preferred colour and board size");
System.out.println("Config requested");
handshakesCount++;
} else if (handshakesCount == 1) {
player2 = handshake[1];
opponant = player;
player.sendMessage("ACKNOWLEDGE_HANDSHAKE+" + gameID + "+" + 0);
System.out.println("Second player found");
handshakesCount++;
if (isWaiting == true) {
createGame();
sendAckConfig();
isConfigured = true;
System.out.println("No longer waiting on second player, configuration is done");
}
}
} else {
player.sendMessage(unknown + "Handshake command length is not 2");
}
}
public void checkSetConfig(String input, ClientHandler player) {
String[] setConfig = input.split("\\+");
if (player.equals(leader)) {
if (setConfig.length == setConfigL && setConfig[1].equals(Integer.toString(gameID))) {
prefColour = Integer.parseInt(setConfig[2]);
if (prefColour == 1 || prefColour == 2) {
boardsize = Integer.parseInt(setConfig[3]);
System.out.println("Set config is received");
if (handshakesCount == 2) {
createGame();
sendAckConfig();
isConfigured = true;
System.out.println("Ack config is send");
} else {
isWaiting = true;
System.out.println("Waiting on second player");
}
} else {
player.sendMessage(unknown + "preffered colour needs to be 1 or 2");
}
} else {
player.sendMessage(unknown + "Set config command length is not 4 "
+ "or gameID is incorrect");
}
} else {
player.sendMessage("you are not the leader of this game, wait for opponant"
+ " to configurate this game");
}
}
public void createGame() {
if (this.full()) {
players = new Player[2];
if (prefColour == 1) {
players[0] = new Player(player1, prefColour);
players[1] = new Player(player2, 2);
black = leader;
white = opponant;
} else {
players[0] = new Player(player2, 1);
players[1] = new Player(player1, prefColour);
black = opponant;
white = leader;
}
game = new Game(players, boardsize, gameID);
}
}
public void sendAckConfig() {
//ACKNOWLEDGE_CONFIG+$PLAYER_NAME+$COLOR+$SIZE+$GAME_SATE+$OPPONENT
String gameState = "PLAYING" + ";" + game.currentPlayer() + ";" + game.getCurrentBoard();
String messageblack = "ACKNOWLEDGE_CONFIG+" + players[0].getName() + "+" + "1+"
+ game.getBoardSizeN() + "+" + gameState + "+" + players[1].getName();
String messagewhite = "ACKNOWLEDGE_CONFIG+" + players[1].getName() + "+" + "2+"
+ game.getBoardSizeN() + "+" + gameState + "+" + players[0].getName();
black.sendMessage(messageblack);
white.sendMessage(messagewhite);
}
// ---------------- Handle user input when game is started --------------
private void playGame(String input, ClientHandler player) {
if (game.currentPlayer() == 1 && player.equals(black)) {
if (input != "EmptyQueue") {
this.handleGame(input, player);
}
} else if (game.currentPlayer() == 2 && player.equals(white)) {
if (input != "EmptyQueue") {
this.handleGame(input, player);
}
} else {
//TODO: het<SUF>
}
if (game.isFinished()) {
System.out.println("Game is finished");
sendGameFinished(game.determineWinner(), "Game ended");
handleRequestRematch();
}
}
public void handleGame(String input, ClientHandler colour) {
if (input.startsWith("MOVE")) {
this.handleMove(input, colour);
} else {
colour.sendMessage((unknown + "Please enter MOVE or EXIT command"));
}
}
public void handleMove(String input, ClientHandler colour) {
//MOVE+$GAME_ID+$PLAYER_NAME+$TILE_INDEX
Player playingPlayer;
int capturedColour;
if (colour.equals(black)) {
playingPlayer = players[0];
capturedColour = players[1].getColour();
} else {
playingPlayer = players[1];
capturedColour = players[0].getColour();
}
String[] move = input.split("\\+");
if (move.length == moveL) {
int moveInt = Integer.parseInt(move[3]);
// TODO: try
if (move[1].equals(Integer.toString(gameID)) &&
move[2].equals(playingPlayer.getName())) {
if (moveInt == pass) {
game.doPass();
sendAckMove(pass, playingPlayer.getColour());
} else {
if (game.isValidMove(moveInt, playingPlayer.getColour()).equals("Move valid")) {
game.doMove(moveInt, playingPlayer.getColour());
game.removeCaptured(capturedColour, playingPlayer.getColour(), game.getBoard());
// need to check both ways since you can suicide a group and don't recreate
// a previous board state (since the other player did moves)
game.removeCaptured(playingPlayer.getColour(), capturedColour, game.getBoard());
game.addCurrentBoardToHistory();
sendAckMove(moveInt, playingPlayer.getColour());
} else {
colour.sendMessage(invalidM +
game.isValidMove(moveInt, playingPlayer.getColour()));
}
}
} else {
colour.sendMessage(invalidM + "GameID is not correct or "
+ "you are not the current player");
}
} else {
System.out.println(unknown + "Move command length is not 4");
}
}
public void sendAckMove(int move, int colour) {
// ACKNOWLEDGE_MOVE+$GAME_ID+$MOVE+$GAME_STATE
String status;
if (game.isFinished()) {
status = "FINISHED";
} else {
status = "PLAYING";
}
String gameState = status + ";" + game.currentPlayer() + ";" + game.getCurrentBoard();
String message = "ACKNOWLEDGE_MOVE+" + gameID + "+" + move + ";" + colour + "+" + gameState;
black.sendMessage(message);
white.sendMessage(message);
}
public void sendGameFinished(String winner, String reason) {
// GAME_FINISHED+$GAME_ID+$WINNER+$SCORE+$MESSAGE
String message = "GAME_FINISHED+" + gameID + "+" + winner + "+"
+ game.getScore(1) + ";" + game.getScore(2) + "+" + reason;
for (ClientHandler player: cHandlers) {
player.sendMessage(message);
}
// TODO: dit moet niet hier?
// this.isFinished = true;
}
// --------------------- exit -------------------------
public void handleExitAndDisconnect(String input, ClientHandler colour) {
// EXIT+$GAME_ID+$PLAYER_NAME
System.out.println("An exit or disconnect is received");
Player exitPlayer;
Player winner;
if (colour.equals(black)) {
exitPlayer = players[0];
winner = players[1];
} else {
exitPlayer = players[1];
winner = players[0];
}
System.out.println("Determined winner");
if (input.startsWith("EXIT")) {
String[] exit = input.split("\\+");
if (exit.length == exitL && exit[1].equals(Integer.toString(gameID)) &&
exit[2].equals(exitPlayer.getName())) {
System.out.println("EXIT correct");
colour.shutdown();
System.out.println("Shutdown clienthandler");
this.removeClientHandler(colour);
System.out.println("Removed clienthandler");
sendGameFinished(winner.getName(), (exitPlayer.getName() + "left the game"));
System.out.println("Send game finished");
this.handleRequestRematch();
} else {
System.out.println(unknown + "Exit command length, GameID and/or player "
+ "name is not correct");
}
} else if (input.equals("FAIL")) {
colour.shutdown();
this.removeClientHandler(colour);
sendGameFinished(winner.getName(), exitPlayer.getName() + " left the game");
this.handleRequestRematch();
}
}
// -------------------- Handle rematch -------------------------
public void handleRequestRematch() {
this.sendRequestRematch();
System.out.println("Request for rematch send");
setRematch = 0;
while (setRematch != this.cHandlers.size()) {
this.readSetRematch();
}
if (rematchCount == this.cHandlers.size()) {
this.resetGame();
} else {
for (ClientHandler player: cHandlers) {
player.sendMessage("ACKNOWLEDGE_REMATCH+0");
System.out.println("No rematch");
System.out.println("Acknowledge rematch send to player");
player.shutdown();
this.removeClientHandler(player);
}
isFinished = true;
}
}
public void sendRequestRematch() {
for (ClientHandler player: cHandlers) {
player.sendMessage("REQUEST_REMATCH");
}
}
public void readSetRematch() {
for (ClientHandler player: cHandlers) {
String input = player.readQueue();
if (!input.equals("EmptyQueue")) {
this.handleSetRematch(input);
setRematch++;
System.out.println("A set rematch received");
}
}
}
public void resetGame() {
System.out.println("Game will now be reset");
for (ClientHandler player: cHandlers) {
player.sendMessage("ACKNOWLEDGE_REMATCH+1");
}
System.out.println("Acknowledge rematch sent to players");
isFinished = false;
isConfigured = false;
handshakesCount = 0;
rematchCount = 0;
player1 = "";
player2 = "";
isWaiting = false;
}
public void handleSetRematch(String input) {
String[] setRematchInput = input.split("\\+");
if (setRematchInput.length == rematchL) {
if (setRematchInput[1].equals("1")) {
rematchCount++;
}
} else {
System.out.println(unknown + "Set rematch command length is not 2");
}
}
// -------------- Queries ---------------------------------------
public List<ClientHandler> getClientHandlers() {
return cHandlers;
}
public boolean full() {
return cHandlers.size() == 2;
}
public boolean empty() {
return cHandlers.size() == 0;
}
public void addClientHandler(ClientHandler player) {
cHandlers.add(player);
}
public void removeClientHandler(ClientHandler player) {
cHandlers.remove(player);
}
}
| False |
4,801 | 109159_20 | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/04/16 Support for running ZAP as a daemon
// ZAP: 2012/03/15 Removed unnecessary castings from methods parse, getArgument and getHelp.
// Changed to use the class StringBuilder instead of the class StringBuffer in the method
// getHelp.
// ZAP: 2012/10/15 Issue 397: Support weekly builds
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/03/20 Issue 568: Allow extensions to run from the command line
// ZAP: 2013/08/30 Issue 775: Allow host to be set via the command line
// ZAP: 2013/12/03 Issue 933: Automatically determine install dir
// ZAP: 2013/12/03 Issue 934: Handle files on the command line via extension
// ZAP: 2014/01/17 Issue 987: Allow arbitrary config file values to be set via the command line
// ZAP: 2014/05/20 Issue 1191: Cmdline session params have no effect
// ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option
// ZAP: 2015/10/06 Issue 1962: Install and update add-ons from the command line
// ZAP: 2016/08/19 Issue 2782: Support -configfile
// ZAP: 2016/09/22 JavaDoc tweaks
// ZAP: 2016/11/07 Allow to disable default standard output logging
// ZAP: 2017/03/26 Allow to obtain configs in the order specified
// ZAP: 2017/05/12 Issue 3460: Support -suppinfo
// ZAP: 2017/05/31 Handle null args and include a message in all exceptions.
// ZAP: 2017/08/31 Use helper method I18N.getString(String, Object...).
// ZAP: 2017/11/21 Validate that -cmd and -daemon are not set at the same time (they are mutually
// exclusive).
// ZAP: 2017/12/26 Remove unused command line arg SP.
// ZAP: 2018/06/29 Add command line to run ZAP in dev mode.
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/10/09 Issue 5619: Ensure -configfile maintains key order
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/05/14 Remove redundant type arguments.
// ZAP: 2022/02/09 No longer parse host/port and deprecate related code.
// ZAP: 2022/02/28 Remove code deprecated in 2.6.0
// ZAP: 2022/04/11 Remove -nouseragent option.
// ZAP: 2022/08/18 Support parameters supplied to newly installed or updated add-ons.
// ZAP: 2023/01/10 Tidy up logger.
// ZAP: 2023/03/23 Read ZAP_SILENT env var.
// ZAP: 2023/10/10 Add -sbomzip option.
// ZAP: 2024/01/13 Add -loglevel option.
package org.parosproxy.paros;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.UnaryOperator;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.extension.CommandLineArgument;
import org.parosproxy.paros.extension.CommandLineListener;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.extension.autoupdate.ExtensionAutoUpdate;
public class CommandLine {
private static final Logger LOGGER = LogManager.getLogger(CommandLine.class);
// ZAP: Made public
public static final String SESSION = "-session";
public static final String NEW_SESSION = "-newsession";
public static final String DAEMON = "-daemon";
public static final String HELP = "-help";
public static final String HELP2 = "-h";
public static final String DIR = "-dir";
public static final String VERSION = "-version";
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated public static final String PORT = "-port";
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated public static final String HOST = "-host";
public static final String CMD = "-cmd";
public static final String INSTALL_DIR = "-installdir";
public static final String CONFIG = "-config";
public static final String CONFIG_FILE = "-configfile";
public static final String LOG_LEVEL = "-loglevel";
public static final String LOWMEM = "-lowmem";
public static final String EXPERIMENTALDB = "-experimentaldb";
public static final String SUPPORT_INFO = "-suppinfo";
public static final String SBOM_ZIP = "-sbomzip";
public static final String SILENT = "-silent";
static final String SILENT_ENV_VAR = "ZAP_SILENT";
/**
* Command line option to disable the default logging through standard output.
*
* @see #isNoStdOutLog()
* @since 2.6.0
*/
public static final String NOSTDOUT = "-nostdout";
/**
* Command line option to enable "dev mode".
*
* <p>With this option development related utilities/functionalities are enabled. For example,
* it's shown an error counter in the footer tool bar and license is implicitly accepted (thus
* not requiring to show/accept the license each time a new home is used).
*
* <p><strong>Note:</strong> this mode is always enabled when running ZAP directly from source
* (i.e. not packaged in a JAR) or using a dev build.
*
* @see #isDevMode()
* @since 2.8.0
*/
public static final String DEV_MODE = "-dev";
private boolean GUI = true;
private boolean daemon = false;
private boolean reportVersion = false;
private boolean displaySupportInfo = false;
private boolean lowMem = false;
private boolean experimentalDb = false;
private boolean silent = false;
private File saveSbomZip;
private String[] args;
private String[] argsBackup;
private final Map<String, String> configs = new LinkedHashMap<>();
private final Hashtable<String, String> keywords = new Hashtable<>();
private List<CommandLineArgument[]> commandList = null;
/**
* Flag that indicates whether or not the default logging through standard output should be
* disabled.
*/
private boolean noStdOutLog;
/** Flag that indicates whether or not the "dev mode" is enabled. */
private boolean devMode;
private Level logLevel;
public CommandLine(String[] args) throws Exception {
this(args, System::getenv);
}
CommandLine(String[] args, UnaryOperator<String> env) throws Exception {
this.args = args == null ? new String[0] : args;
this.argsBackup = new String[this.args.length];
System.arraycopy(this.args, 0, argsBackup, 0, this.args.length);
parseFirst(this.args);
readEnv(env);
if (isEnabled(CommandLine.CMD) && isEnabled(CommandLine.DAEMON)) {
throw new IllegalArgumentException(
"Command line arguments "
+ CommandLine.CMD
+ " and "
+ CommandLine.DAEMON
+ " cannot be used at the same time.");
}
}
private void readEnv(UnaryOperator<String> env) {
if (env.apply(SILENT_ENV_VAR) != null) {
setSilent();
}
}
private void setSilent() {
silent = true;
Constant.setSilent(true);
}
private boolean checkPair(String[] args, String paramName, int i) throws Exception {
String key = args[i];
String value = null;
if (key == null) {
return false;
}
if (key.equalsIgnoreCase(paramName)) {
value = args[i + 1];
if (value == null) {
throw new Exception("Missing parameter for keyword '" + paramName + "'.");
}
keywords.put(paramName, value);
args[i] = null;
args[i + 1] = null;
return true;
}
return false;
}
private boolean checkSwitch(String[] args, String paramName, int i) throws Exception {
String key = args[i];
if (key == null) {
return false;
}
if (key.equalsIgnoreCase(paramName)) {
keywords.put(paramName, "");
args[i] = null;
return true;
}
return false;
}
private void parseFirst(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
if (parseSwitchs(args, i)) {
continue;
}
if (parseKeywords(args, i)) {
continue;
}
}
}
public void parse(
List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap)
throws Exception {
this.parse(commandList, extMap, true);
}
/**
* Parse the command line arguments
*
* @param commandList the list of commands
* @param extMap a map of the extensions which support command line args
* @param reportUnsupported if true will report unsupported args
* @throws Exception
* @since 2.12.0
*/
public void parse(
List<CommandLineArgument[]> commandList,
Map<String, CommandLineListener> extMap,
boolean reportUnsupported)
throws Exception {
this.commandList = commandList;
CommandLineArgument lastArg = null;
boolean found = false;
int remainingValueCount = 0;
boolean installingAddons = false;
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
found = false;
for (int j = 0; j < commandList.size() && !found; j++) {
CommandLineArgument[] extArg = commandList.get(j);
for (int k = 0; k < extArg.length && !found; k++) {
if (args[i].compareToIgnoreCase(extArg[k].getName()) == 0) {
// check if previous keyword satisfied its required no. of parameters
if (remainingValueCount > 0) {
throw new Exception(
"Missing parameters for keyword '" + lastArg.getName() + "'.");
}
// process this keyword
lastArg = extArg[k];
lastArg.setEnabled(true);
found = true;
if (ExtensionAutoUpdate.ADDON_INSTALL.equals(args[i])
|| ExtensionAutoUpdate.ADDON_INSTALL_ALL.equals(args[i])) {
installingAddons = true;
}
args[i] = null;
remainingValueCount = lastArg.getNumOfArguments();
}
}
}
// check if current string is a keyword preceded by '-'
if (args[i] != null && args[i].startsWith("-")) {
continue;
}
// check if there is no more expected param value
if (lastArg != null && remainingValueCount == 0) {
continue;
}
// check if consume remaining for last matched keywords
if (!found && lastArg != null) {
if (lastArg.getPattern() == null || lastArg.getPattern().matcher(args[i]).find()) {
lastArg.getArguments().add(args[i]);
if (remainingValueCount > 0) {
remainingValueCount--;
}
args[i] = null;
} else {
throw new Exception(lastArg.getErrorMessage());
}
}
}
// check if the last keyword satisfied its no. of parameters.
if (lastArg != null && remainingValueCount > 0) {
throw new Exception("Missing parameters for keyword '" + lastArg.getName() + "'.");
}
// check for supported extensions
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
int dotIndex = args[i].lastIndexOf(".");
if (dotIndex < 0) {
// Only support files with extensions
continue;
}
File file = new File(args[i]);
if (!file.exists() || !file.canRead()) {
// Not there or cant read .. move on
continue;
}
String ext = args[i].substring(dotIndex + 1);
CommandLineListener cll = extMap.get(ext);
if (cll != null) {
if (cll.handleFile(file)) {
found = true;
args[i] = null;
}
}
}
if (reportUnsupported && !installingAddons) {
// check if there is some unknown keywords or parameters
for (String arg : args) {
if (arg != null) {
if (arg.startsWith("-")) {
throw new Exception(
Constant.messages.getString("start.cmdline.badparam", arg));
} else {
// Assume they were trying to specify a file
File f = new File(arg);
if (!f.exists()) {
throw new Exception(
Constant.messages.getString("start.cmdline.nofile", arg));
} else if (!f.canRead()) {
throw new Exception(
Constant.messages.getString("start.cmdline.noread", arg));
} else {
// We probably dont handle this sort of file
throw new Exception(
Constant.messages.getString("start.cmdline.badfile", arg));
}
}
}
}
}
}
private boolean parseSwitchs(String[] args, int i) throws Exception {
boolean result = false;
if (checkSwitch(args, CMD, i)) {
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, DAEMON, i)) {
setDaemon(true);
setGUI(false);
} else if (checkSwitch(args, LOWMEM, i)) {
setLowMem(true);
} else if (checkSwitch(args, EXPERIMENTALDB, i)) {
setExperimentalDb(true);
} else if (checkSwitch(args, HELP, i)) {
result = true;
setGUI(false);
} else if (checkSwitch(args, HELP2, i)) {
result = true;
setGUI(false);
} else if (checkSwitch(args, VERSION, i)) {
reportVersion = true;
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, NOSTDOUT, i)) {
noStdOutLog = true;
} else if (checkSwitch(args, SUPPORT_INFO, i)) {
displaySupportInfo = true;
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, DEV_MODE, i)) {
devMode = true;
Constant.setDevMode(true);
} else if (checkSwitch(args, SILENT, i)) {
setSilent();
}
return result;
}
private boolean parseKeywords(String[] args, int i) throws Exception {
boolean result = false;
if (checkPair(args, NEW_SESSION, i)) {
result = true;
} else if (checkPair(args, SESSION, i)) {
result = true;
} else if (checkPair(args, DIR, i)) {
Constant.setZapHome(keywords.get(DIR));
result = true;
} else if (checkPair(args, LOG_LEVEL, i)) {
logLevel = Level.toLevel(keywords.get(LOG_LEVEL), null);
if (logLevel == null) {
throw new Exception("Invalid log level: \"" + keywords.get(LOG_LEVEL) + "\"");
}
result = true;
} else if (checkPair(args, INSTALL_DIR, i)) {
Constant.setZapInstall(keywords.get(INSTALL_DIR));
result = true;
} else if (checkPair(args, SBOM_ZIP, i)) {
String zipName = keywords.get(SBOM_ZIP);
this.saveSbomZip = new File(zipName);
setDaemon(false);
setGUI(false);
result = true;
} else if (checkPair(args, CONFIG, i)) {
String pair = keywords.get(CONFIG);
if (pair != null && pair.indexOf("=") > 0) {
int eqIndex = pair.indexOf("=");
this.configs.put(pair.substring(0, eqIndex), pair.substring(eqIndex + 1));
result = true;
}
} else if (checkPair(args, CONFIG_FILE, i)) {
String conf = keywords.get(CONFIG_FILE);
File confFile = new File(conf);
if (!confFile.isFile()) {
// We cant use i18n here as the messages wont have been loaded
throw new Exception("No such file: " + confFile.getAbsolutePath());
} else if (!confFile.canRead()) {
// We cant use i18n here as the messages wont have been loaded
throw new Exception("File not readable: " + confFile.getAbsolutePath());
}
Properties prop =
new Properties() {
// Override methods to ensure keys returned in order
List<Object> orderedKeys = new ArrayList<>();
private static final long serialVersionUID = 1L;
@Override
public synchronized Object put(Object key, Object value) {
orderedKeys.add(key);
return super.put(key, value);
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(orderedKeys);
}
};
try (FileInputStream inStream = new FileInputStream(confFile)) {
prop.load(inStream);
}
Enumeration<Object> keyEnum = prop.keys();
while (keyEnum.hasMoreElements()) {
String key = (String) keyEnum.nextElement();
this.configs.put(key, prop.getProperty(key));
}
}
return result;
}
/**
* Tells whether or not ZAP was started with GUI.
*
* @return {@code true} if ZAP was started with GUI, {@code false} otherwise
*/
public boolean isGUI() {
return GUI;
}
/**
* Sets whether or not ZAP was started with GUI.
*
* @param GUI {@code true} if ZAP was started with GUI, {@code false} otherwise
*/
public void setGUI(boolean GUI) {
this.GUI = GUI;
}
public boolean isDaemon() {
return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
public boolean isLowMem() {
return lowMem;
}
public void setLowMem(boolean lowMem) {
this.lowMem = lowMem;
}
public boolean isExperimentalDb() {
return experimentalDb;
}
public void setExperimentalDb(boolean experimentalDb) {
this.experimentalDb = experimentalDb;
}
public boolean isReportVersion() {
return this.reportVersion;
}
public boolean isDisplaySupportInfo() {
return this.displaySupportInfo;
}
public File getSaveSbomZip() {
return this.saveSbomZip;
}
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated
public int getPort() {
return -1;
}
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated
public String getHost() {
return null;
}
/**
* Gets the {@code config} command line arguments, in the order they were specified.
*
* @return the {@code config} command line arguments.
* @since 2.6.0
*/
public Map<String, String> getOrderedConfigs() {
return configs;
}
public String getArgument(String keyword) {
return keywords.get(keyword);
}
public String getHelp() {
return CommandLine.getHelp(commandList);
}
/**
* Tells whether or not the default logging through standard output should be disabled.
*
* @return {@code true} if the default logging through standard output should be disabled,
* {@code false} otherwise.
* @since 2.6.0
*/
public boolean isNoStdOutLog() {
return noStdOutLog;
}
/**
* Returns the specified log level argument.
*
* @since 2.15.0
*/
public Level getLogLevel() {
return logLevel;
}
/**
* Returns true if ZAP should not make any unsolicited requests, e.g. check-for-updates, etc.
*
* @since 2.8.0
*/
public boolean isSilent() {
return silent;
}
/**
* Tells whether or not the "dev mode" should be enabled.
*
* @return {@code true} if the "dev mode" should be enabled, {@code false} otherwise.
* @since 2.8.0
* @see #DEV_MODE
*/
public boolean isDevMode() {
return devMode;
}
public static String getHelp(List<CommandLineArgument[]> cmdList) {
String zap;
if (Constant.isWindows()) {
zap = "zap.bat";
} else {
zap = "zap.sh";
}
StringBuilder sb = new StringBuilder();
sb.append(Constant.messages.getString("cmdline.help", zap));
if (cmdList != null) {
for (CommandLineArgument[] extArgs : cmdList) {
for (CommandLineArgument extArg : extArgs) {
sb.append("\t");
sb.append(extArg.getHelpMessage()).append("\n");
}
}
}
return sb.toString();
}
public boolean isEnabled(String keyword) {
Object obj = keywords.get(keyword);
return (obj != null) && (obj instanceof String);
}
/**
* Reset the arguments so that they can be parsed again (e.g. after an add-on is installed)
*
* @since 2.12.0
*/
public void resetArgs() {
System.arraycopy(argsBackup, 0, args, 0, argsBackup.length);
}
/**
* A method for reporting informational messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stdout as appropriate.
*
* @param str the informational message
*/
public static void info(String str) {
switch (ZAP.getProcessType()) {
case cmdline:
System.out.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.info(str);
}
/**
* A method for reporting error messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stderr as appropriate.
*
* @param str the error message
*/
public static void error(String str) {
switch (ZAP.getProcessType()) {
case cmdline:
System.err.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.error(str);
}
/**
* A method for reporting error messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stderr as appropriate.
*
* @param str the error message
* @param e the cause of the error
*/
public static void error(String str, Throwable e) {
switch (ZAP.getProcessType()) {
case cmdline:
System.err.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.error(str, e);
}
}
| zaproxy/zaproxy | zap/src/main/java/org/parosproxy/paros/CommandLine.java | 6,974 | // ZAP: 2017/08/31 Use helper method I18N.getString(String, Object...). | line_comment | nl | /*
*
* Paros and its related class files.
*
* Paros is an HTTP/HTTPS proxy for assessing web application security.
* Copyright (C) 2003-2004 Chinotec Technologies Company
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the Clarified Artistic License
* as published by the Free Software Foundation.
*
* This program 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
* Clarified Artistic License for more details.
*
* You should have received a copy of the Clarified Artistic License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// ZAP: 2011/04/16 Support for running ZAP as a daemon
// ZAP: 2012/03/15 Removed unnecessary castings from methods parse, getArgument and getHelp.
// Changed to use the class StringBuilder instead of the class StringBuffer in the method
// getHelp.
// ZAP: 2012/10/15 Issue 397: Support weekly builds
// ZAP: 2013/03/03 Issue 546: Remove all template Javadoc comments
// ZAP: 2013/03/20 Issue 568: Allow extensions to run from the command line
// ZAP: 2013/08/30 Issue 775: Allow host to be set via the command line
// ZAP: 2013/12/03 Issue 933: Automatically determine install dir
// ZAP: 2013/12/03 Issue 934: Handle files on the command line via extension
// ZAP: 2014/01/17 Issue 987: Allow arbitrary config file values to be set via the command line
// ZAP: 2014/05/20 Issue 1191: Cmdline session params have no effect
// ZAP: 2015/04/02 Issue 321: Support multiple databases and Issue 1582: Low memory option
// ZAP: 2015/10/06 Issue 1962: Install and update add-ons from the command line
// ZAP: 2016/08/19 Issue 2782: Support -configfile
// ZAP: 2016/09/22 JavaDoc tweaks
// ZAP: 2016/11/07 Allow to disable default standard output logging
// ZAP: 2017/03/26 Allow to obtain configs in the order specified
// ZAP: 2017/05/12 Issue 3460: Support -suppinfo
// ZAP: 2017/05/31 Handle null args and include a message in all exceptions.
// ZAP: 2017/08/31<SUF>
// ZAP: 2017/11/21 Validate that -cmd and -daemon are not set at the same time (they are mutually
// exclusive).
// ZAP: 2017/12/26 Remove unused command line arg SP.
// ZAP: 2018/06/29 Add command line to run ZAP in dev mode.
// ZAP: 2019/06/01 Normalise line endings.
// ZAP: 2019/06/05 Normalise format/style.
// ZAP: 2019/10/09 Issue 5619: Ensure -configfile maintains key order
// ZAP: 2020/11/26 Use Log4j 2 classes for logging.
// ZAP: 2021/05/14 Remove redundant type arguments.
// ZAP: 2022/02/09 No longer parse host/port and deprecate related code.
// ZAP: 2022/02/28 Remove code deprecated in 2.6.0
// ZAP: 2022/04/11 Remove -nouseragent option.
// ZAP: 2022/08/18 Support parameters supplied to newly installed or updated add-ons.
// ZAP: 2023/01/10 Tidy up logger.
// ZAP: 2023/03/23 Read ZAP_SILENT env var.
// ZAP: 2023/10/10 Add -sbomzip option.
// ZAP: 2024/01/13 Add -loglevel option.
package org.parosproxy.paros;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.function.UnaryOperator;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.parosproxy.paros.extension.CommandLineArgument;
import org.parosproxy.paros.extension.CommandLineListener;
import org.zaproxy.zap.ZAP;
import org.zaproxy.zap.extension.autoupdate.ExtensionAutoUpdate;
public class CommandLine {
private static final Logger LOGGER = LogManager.getLogger(CommandLine.class);
// ZAP: Made public
public static final String SESSION = "-session";
public static final String NEW_SESSION = "-newsession";
public static final String DAEMON = "-daemon";
public static final String HELP = "-help";
public static final String HELP2 = "-h";
public static final String DIR = "-dir";
public static final String VERSION = "-version";
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated public static final String PORT = "-port";
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated public static final String HOST = "-host";
public static final String CMD = "-cmd";
public static final String INSTALL_DIR = "-installdir";
public static final String CONFIG = "-config";
public static final String CONFIG_FILE = "-configfile";
public static final String LOG_LEVEL = "-loglevel";
public static final String LOWMEM = "-lowmem";
public static final String EXPERIMENTALDB = "-experimentaldb";
public static final String SUPPORT_INFO = "-suppinfo";
public static final String SBOM_ZIP = "-sbomzip";
public static final String SILENT = "-silent";
static final String SILENT_ENV_VAR = "ZAP_SILENT";
/**
* Command line option to disable the default logging through standard output.
*
* @see #isNoStdOutLog()
* @since 2.6.0
*/
public static final String NOSTDOUT = "-nostdout";
/**
* Command line option to enable "dev mode".
*
* <p>With this option development related utilities/functionalities are enabled. For example,
* it's shown an error counter in the footer tool bar and license is implicitly accepted (thus
* not requiring to show/accept the license each time a new home is used).
*
* <p><strong>Note:</strong> this mode is always enabled when running ZAP directly from source
* (i.e. not packaged in a JAR) or using a dev build.
*
* @see #isDevMode()
* @since 2.8.0
*/
public static final String DEV_MODE = "-dev";
private boolean GUI = true;
private boolean daemon = false;
private boolean reportVersion = false;
private boolean displaySupportInfo = false;
private boolean lowMem = false;
private boolean experimentalDb = false;
private boolean silent = false;
private File saveSbomZip;
private String[] args;
private String[] argsBackup;
private final Map<String, String> configs = new LinkedHashMap<>();
private final Hashtable<String, String> keywords = new Hashtable<>();
private List<CommandLineArgument[]> commandList = null;
/**
* Flag that indicates whether or not the default logging through standard output should be
* disabled.
*/
private boolean noStdOutLog;
/** Flag that indicates whether or not the "dev mode" is enabled. */
private boolean devMode;
private Level logLevel;
public CommandLine(String[] args) throws Exception {
this(args, System::getenv);
}
CommandLine(String[] args, UnaryOperator<String> env) throws Exception {
this.args = args == null ? new String[0] : args;
this.argsBackup = new String[this.args.length];
System.arraycopy(this.args, 0, argsBackup, 0, this.args.length);
parseFirst(this.args);
readEnv(env);
if (isEnabled(CommandLine.CMD) && isEnabled(CommandLine.DAEMON)) {
throw new IllegalArgumentException(
"Command line arguments "
+ CommandLine.CMD
+ " and "
+ CommandLine.DAEMON
+ " cannot be used at the same time.");
}
}
private void readEnv(UnaryOperator<String> env) {
if (env.apply(SILENT_ENV_VAR) != null) {
setSilent();
}
}
private void setSilent() {
silent = true;
Constant.setSilent(true);
}
private boolean checkPair(String[] args, String paramName, int i) throws Exception {
String key = args[i];
String value = null;
if (key == null) {
return false;
}
if (key.equalsIgnoreCase(paramName)) {
value = args[i + 1];
if (value == null) {
throw new Exception("Missing parameter for keyword '" + paramName + "'.");
}
keywords.put(paramName, value);
args[i] = null;
args[i + 1] = null;
return true;
}
return false;
}
private boolean checkSwitch(String[] args, String paramName, int i) throws Exception {
String key = args[i];
if (key == null) {
return false;
}
if (key.equalsIgnoreCase(paramName)) {
keywords.put(paramName, "");
args[i] = null;
return true;
}
return false;
}
private void parseFirst(String[] args) throws Exception {
for (int i = 0; i < args.length; i++) {
if (parseSwitchs(args, i)) {
continue;
}
if (parseKeywords(args, i)) {
continue;
}
}
}
public void parse(
List<CommandLineArgument[]> commandList, Map<String, CommandLineListener> extMap)
throws Exception {
this.parse(commandList, extMap, true);
}
/**
* Parse the command line arguments
*
* @param commandList the list of commands
* @param extMap a map of the extensions which support command line args
* @param reportUnsupported if true will report unsupported args
* @throws Exception
* @since 2.12.0
*/
public void parse(
List<CommandLineArgument[]> commandList,
Map<String, CommandLineListener> extMap,
boolean reportUnsupported)
throws Exception {
this.commandList = commandList;
CommandLineArgument lastArg = null;
boolean found = false;
int remainingValueCount = 0;
boolean installingAddons = false;
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
found = false;
for (int j = 0; j < commandList.size() && !found; j++) {
CommandLineArgument[] extArg = commandList.get(j);
for (int k = 0; k < extArg.length && !found; k++) {
if (args[i].compareToIgnoreCase(extArg[k].getName()) == 0) {
// check if previous keyword satisfied its required no. of parameters
if (remainingValueCount > 0) {
throw new Exception(
"Missing parameters for keyword '" + lastArg.getName() + "'.");
}
// process this keyword
lastArg = extArg[k];
lastArg.setEnabled(true);
found = true;
if (ExtensionAutoUpdate.ADDON_INSTALL.equals(args[i])
|| ExtensionAutoUpdate.ADDON_INSTALL_ALL.equals(args[i])) {
installingAddons = true;
}
args[i] = null;
remainingValueCount = lastArg.getNumOfArguments();
}
}
}
// check if current string is a keyword preceded by '-'
if (args[i] != null && args[i].startsWith("-")) {
continue;
}
// check if there is no more expected param value
if (lastArg != null && remainingValueCount == 0) {
continue;
}
// check if consume remaining for last matched keywords
if (!found && lastArg != null) {
if (lastArg.getPattern() == null || lastArg.getPattern().matcher(args[i]).find()) {
lastArg.getArguments().add(args[i]);
if (remainingValueCount > 0) {
remainingValueCount--;
}
args[i] = null;
} else {
throw new Exception(lastArg.getErrorMessage());
}
}
}
// check if the last keyword satisfied its no. of parameters.
if (lastArg != null && remainingValueCount > 0) {
throw new Exception("Missing parameters for keyword '" + lastArg.getName() + "'.");
}
// check for supported extensions
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
int dotIndex = args[i].lastIndexOf(".");
if (dotIndex < 0) {
// Only support files with extensions
continue;
}
File file = new File(args[i]);
if (!file.exists() || !file.canRead()) {
// Not there or cant read .. move on
continue;
}
String ext = args[i].substring(dotIndex + 1);
CommandLineListener cll = extMap.get(ext);
if (cll != null) {
if (cll.handleFile(file)) {
found = true;
args[i] = null;
}
}
}
if (reportUnsupported && !installingAddons) {
// check if there is some unknown keywords or parameters
for (String arg : args) {
if (arg != null) {
if (arg.startsWith("-")) {
throw new Exception(
Constant.messages.getString("start.cmdline.badparam", arg));
} else {
// Assume they were trying to specify a file
File f = new File(arg);
if (!f.exists()) {
throw new Exception(
Constant.messages.getString("start.cmdline.nofile", arg));
} else if (!f.canRead()) {
throw new Exception(
Constant.messages.getString("start.cmdline.noread", arg));
} else {
// We probably dont handle this sort of file
throw new Exception(
Constant.messages.getString("start.cmdline.badfile", arg));
}
}
}
}
}
}
private boolean parseSwitchs(String[] args, int i) throws Exception {
boolean result = false;
if (checkSwitch(args, CMD, i)) {
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, DAEMON, i)) {
setDaemon(true);
setGUI(false);
} else if (checkSwitch(args, LOWMEM, i)) {
setLowMem(true);
} else if (checkSwitch(args, EXPERIMENTALDB, i)) {
setExperimentalDb(true);
} else if (checkSwitch(args, HELP, i)) {
result = true;
setGUI(false);
} else if (checkSwitch(args, HELP2, i)) {
result = true;
setGUI(false);
} else if (checkSwitch(args, VERSION, i)) {
reportVersion = true;
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, NOSTDOUT, i)) {
noStdOutLog = true;
} else if (checkSwitch(args, SUPPORT_INFO, i)) {
displaySupportInfo = true;
setDaemon(false);
setGUI(false);
} else if (checkSwitch(args, DEV_MODE, i)) {
devMode = true;
Constant.setDevMode(true);
} else if (checkSwitch(args, SILENT, i)) {
setSilent();
}
return result;
}
private boolean parseKeywords(String[] args, int i) throws Exception {
boolean result = false;
if (checkPair(args, NEW_SESSION, i)) {
result = true;
} else if (checkPair(args, SESSION, i)) {
result = true;
} else if (checkPair(args, DIR, i)) {
Constant.setZapHome(keywords.get(DIR));
result = true;
} else if (checkPair(args, LOG_LEVEL, i)) {
logLevel = Level.toLevel(keywords.get(LOG_LEVEL), null);
if (logLevel == null) {
throw new Exception("Invalid log level: \"" + keywords.get(LOG_LEVEL) + "\"");
}
result = true;
} else if (checkPair(args, INSTALL_DIR, i)) {
Constant.setZapInstall(keywords.get(INSTALL_DIR));
result = true;
} else if (checkPair(args, SBOM_ZIP, i)) {
String zipName = keywords.get(SBOM_ZIP);
this.saveSbomZip = new File(zipName);
setDaemon(false);
setGUI(false);
result = true;
} else if (checkPair(args, CONFIG, i)) {
String pair = keywords.get(CONFIG);
if (pair != null && pair.indexOf("=") > 0) {
int eqIndex = pair.indexOf("=");
this.configs.put(pair.substring(0, eqIndex), pair.substring(eqIndex + 1));
result = true;
}
} else if (checkPair(args, CONFIG_FILE, i)) {
String conf = keywords.get(CONFIG_FILE);
File confFile = new File(conf);
if (!confFile.isFile()) {
// We cant use i18n here as the messages wont have been loaded
throw new Exception("No such file: " + confFile.getAbsolutePath());
} else if (!confFile.canRead()) {
// We cant use i18n here as the messages wont have been loaded
throw new Exception("File not readable: " + confFile.getAbsolutePath());
}
Properties prop =
new Properties() {
// Override methods to ensure keys returned in order
List<Object> orderedKeys = new ArrayList<>();
private static final long serialVersionUID = 1L;
@Override
public synchronized Object put(Object key, Object value) {
orderedKeys.add(key);
return super.put(key, value);
}
@Override
public synchronized Enumeration<Object> keys() {
return Collections.enumeration(orderedKeys);
}
};
try (FileInputStream inStream = new FileInputStream(confFile)) {
prop.load(inStream);
}
Enumeration<Object> keyEnum = prop.keys();
while (keyEnum.hasMoreElements()) {
String key = (String) keyEnum.nextElement();
this.configs.put(key, prop.getProperty(key));
}
}
return result;
}
/**
* Tells whether or not ZAP was started with GUI.
*
* @return {@code true} if ZAP was started with GUI, {@code false} otherwise
*/
public boolean isGUI() {
return GUI;
}
/**
* Sets whether or not ZAP was started with GUI.
*
* @param GUI {@code true} if ZAP was started with GUI, {@code false} otherwise
*/
public void setGUI(boolean GUI) {
this.GUI = GUI;
}
public boolean isDaemon() {
return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
public boolean isLowMem() {
return lowMem;
}
public void setLowMem(boolean lowMem) {
this.lowMem = lowMem;
}
public boolean isExperimentalDb() {
return experimentalDb;
}
public void setExperimentalDb(boolean experimentalDb) {
this.experimentalDb = experimentalDb;
}
public boolean isReportVersion() {
return this.reportVersion;
}
public boolean isDisplaySupportInfo() {
return this.displaySupportInfo;
}
public File getSaveSbomZip() {
return this.saveSbomZip;
}
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated
public int getPort() {
return -1;
}
/**
* @deprecated (2.12.0) No longer used/needed. It will be removed in a future release.
*/
@Deprecated
public String getHost() {
return null;
}
/**
* Gets the {@code config} command line arguments, in the order they were specified.
*
* @return the {@code config} command line arguments.
* @since 2.6.0
*/
public Map<String, String> getOrderedConfigs() {
return configs;
}
public String getArgument(String keyword) {
return keywords.get(keyword);
}
public String getHelp() {
return CommandLine.getHelp(commandList);
}
/**
* Tells whether or not the default logging through standard output should be disabled.
*
* @return {@code true} if the default logging through standard output should be disabled,
* {@code false} otherwise.
* @since 2.6.0
*/
public boolean isNoStdOutLog() {
return noStdOutLog;
}
/**
* Returns the specified log level argument.
*
* @since 2.15.0
*/
public Level getLogLevel() {
return logLevel;
}
/**
* Returns true if ZAP should not make any unsolicited requests, e.g. check-for-updates, etc.
*
* @since 2.8.0
*/
public boolean isSilent() {
return silent;
}
/**
* Tells whether or not the "dev mode" should be enabled.
*
* @return {@code true} if the "dev mode" should be enabled, {@code false} otherwise.
* @since 2.8.0
* @see #DEV_MODE
*/
public boolean isDevMode() {
return devMode;
}
public static String getHelp(List<CommandLineArgument[]> cmdList) {
String zap;
if (Constant.isWindows()) {
zap = "zap.bat";
} else {
zap = "zap.sh";
}
StringBuilder sb = new StringBuilder();
sb.append(Constant.messages.getString("cmdline.help", zap));
if (cmdList != null) {
for (CommandLineArgument[] extArgs : cmdList) {
for (CommandLineArgument extArg : extArgs) {
sb.append("\t");
sb.append(extArg.getHelpMessage()).append("\n");
}
}
}
return sb.toString();
}
public boolean isEnabled(String keyword) {
Object obj = keywords.get(keyword);
return (obj != null) && (obj instanceof String);
}
/**
* Reset the arguments so that they can be parsed again (e.g. after an add-on is installed)
*
* @since 2.12.0
*/
public void resetArgs() {
System.arraycopy(argsBackup, 0, args, 0, argsBackup.length);
}
/**
* A method for reporting informational messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stdout as appropriate.
*
* @param str the informational message
*/
public static void info(String str) {
switch (ZAP.getProcessType()) {
case cmdline:
System.out.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.info(str);
}
/**
* A method for reporting error messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stderr as appropriate.
*
* @param str the error message
*/
public static void error(String str) {
switch (ZAP.getProcessType()) {
case cmdline:
System.err.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.error(str);
}
/**
* A method for reporting error messages in {@link
* CommandLineListener#execute(CommandLineArgument[])} implementations. It ensures that messages
* are written to the log file and/or written to stderr as appropriate.
*
* @param str the error message
* @param e the cause of the error
*/
public static void error(String str, Throwable e) {
switch (ZAP.getProcessType()) {
case cmdline:
System.err.println(str);
break;
default: // Ignore
}
// Always write to the log
LOGGER.error(str, e);
}
}
| False |
2,114 | 58011_1 | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor alle waarden van type
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| apollo-mapping/geotools | modules/unsupported/dxf/src/main/java/org/geotools/data/dxf/entities/DXFLwPolyline.java | 3,599 | // geldt voor alle waarden van type | line_comment | nl | /*
* [ 1719398 ] First shot at LWPOLYLINE
* Peter Hopfgartner - hopfgartner
*
*/
package org.geotools.data.dxf.entities;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LinearRing;
import java.io.EOFException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geotools.data.GeometryType;
import org.geotools.data.dxf.header.DXFLayer;
import org.geotools.data.dxf.header.DXFLineType;
import org.geotools.data.dxf.header.DXFTables;
import org.geotools.data.dxf.parser.DXFCodeValuePair;
import org.geotools.data.dxf.parser.DXFGroupCode;
import org.geotools.data.dxf.parser.DXFLineNumberReader;
import org.geotools.data.dxf.parser.DXFParseException;
import org.geotools.data.dxf.parser.DXFUnivers;
/** @source $URL$ */
public class DXFLwPolyline extends DXFEntity {
private static final Log log = LogFactory.getLog(DXFLwPolyline.class);
public String _id = "DXFLwPolyline";
public int _flag = 0;
public Vector<DXFLwVertex> theVertices = new Vector<DXFLwVertex>();
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
}
public DXFLwPolyline(
String name,
int flag,
int c,
DXFLayer l,
Vector<DXFLwVertex> v,
int visibility,
DXFLineType lineType,
double thickness,
DXFExtendedData extData) {
super(c, l, visibility, lineType, thickness);
_id = name;
Vector<DXFLwVertex> newV = new Vector<DXFLwVertex>();
for (int i = 0; i < v.size(); i++) {
DXFLwVertex entity = (DXFLwVertex) v.get(i).clone();
newV.add(entity);
}
theVertices = newV;
_flag = flag;
setName("DXFLwPolyline");
_extendedData = extData;
}
public DXFLwPolyline(DXFLayer l) {
super(-1, l, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline() {
super(-1, null, 0, null, DXFTables.defaultThickness);
setName("DXFLwPolyline");
}
public DXFLwPolyline(DXFLwPolyline orig) {
super(orig.getColor(), orig.getRefLayer(), 0, orig.getLineType(), orig.getThickness());
_id = orig._id;
for (int i = 0; i < orig.theVertices.size(); i++) {
theVertices.add((DXFLwVertex) orig.theVertices.elementAt(i).clone());
}
_flag = orig._flag;
setType(orig.getType());
setStartingLineNumber(orig.getStartingLineNumber());
setUnivers(orig.getUnivers());
setName("DXFLwPolyline");
}
public static DXFLwPolyline read(DXFLineNumberReader br, DXFUnivers univers)
throws IOException {
String name = "";
int visibility = 0, flag = 0, c = -1;
DXFLineType lineType = null;
Vector<DXFLwVertex> lv = new Vector<DXFLwVertex>();
DXFLayer l = null;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
DXFExtendedData _extData = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
String type = cvp.getStringValue(); // SEQEND ???
// geldt voor<SUF>
br.reset();
doLoop = false;
break;
case X_1: // "10"
br.reset();
readLwVertices(br, lv);
break;
case NAME: // "2"
name = cvp.getStringValue();
break;
case LAYER_NAME: // "8"
l = univers.findLayer(cvp.getStringValue());
break;
case LINETYPE_NAME: // "6"
lineType = univers.findLType(cvp.getStringValue());
break;
case COLOR: // "62"
c = cvp.getShortValue();
break;
case INT_1: // "70"
flag = cvp.getShortValue();
break;
case VISIBILITY: // "60"
visibility = cvp.getShortValue();
break;
case XDATA_APPLICATION_NAME:
String appName = cvp.getStringValue();
_extData = DXFExtendedData.getExtendedData(br);
_extData.setAppName(appName);
break;
default:
break;
}
}
DXFLwPolyline e =
new DXFLwPolyline(
name,
flag,
c,
l,
lv,
visibility,
lineType,
DXFTables.defaultThickness,
_extData);
if ((flag & 1) == 1) {
e.setType(GeometryType.POLYGON);
} else {
e.setType(GeometryType.LINE);
}
e.setStartingLineNumber(sln);
e.setUnivers(univers);
log.debug(e.toString(name, flag, lv.size(), c, visibility, DXFTables.defaultThickness));
log.debug(">>Exit at line: " + br.getLineNumber());
return e;
}
public static void readLwVertices(DXFLineNumberReader br, Vector<DXFLwVertex> theVertices)
throws IOException {
double x = 0, y = 0, b = 0;
boolean xFound = false, yFound = false;
int sln = br.getLineNumber();
log.debug(">>Enter at line: " + sln);
DXFCodeValuePair cvp = null;
DXFGroupCode gc = null;
boolean doLoop = true;
while (doLoop) {
cvp = new DXFCodeValuePair();
try {
gc = cvp.read(br);
} catch (DXFParseException ex) {
throw new IOException("DXF parse error" + ex.getLocalizedMessage());
} catch (EOFException e) {
doLoop = false;
break;
}
switch (gc) {
case TYPE:
case X_1: // "10"
// check of vorig vertex opgeslagen kan worden
if (xFound && yFound) {
DXFLwVertex e = new DXFLwVertex(x, y, b);
log.debug(e.toString(b, x, y));
theVertices.add(e);
xFound = false;
yFound = false;
x = 0;
y = 0;
b = 0;
}
// TODO klopt dit???
if (gc == DXFGroupCode.TYPE) {
br.reset();
doLoop = false;
break;
}
x = cvp.getDoubleValue();
xFound = true;
break;
case Y_1: // "20"
y = cvp.getDoubleValue();
yFound = true;
break;
case DOUBLE_3: // "42"
b = cvp.getDoubleValue();
break;
default:
break;
}
}
log.debug(">Exit at line: " + br.getLineNumber());
}
@Override
public Geometry getGeometry() {
if (geometry == null) {
updateGeometry();
}
return super.getGeometry();
}
@Override
public void updateGeometry() {
Coordinate[] ca = toCoordinateArray();
if (ca != null && ca.length > 1) {
if (getType() == GeometryType.POLYGON) {
LinearRing lr = getUnivers().getGeometryFactory().createLinearRing(ca);
geometry = getUnivers().getGeometryFactory().createPolygon(lr, null);
} else {
geometry = getUnivers().getGeometryFactory().createLineString(ca);
}
} else {
addError("coordinate array faulty, size: " + (ca == null ? 0 : ca.length));
}
}
public Coordinate[] toCoordinateArray() {
if (theVertices == null) {
addError("coordinate array can not be created.");
return null;
}
Iterator it = theVertices.iterator();
List<Coordinate> lc = new ArrayList<Coordinate>();
Coordinate firstc = null;
Coordinate lastc = null;
while (it.hasNext()) {
DXFLwVertex v = (DXFLwVertex) it.next();
lastc = v.toCoordinate();
if (firstc == null) {
firstc = lastc;
}
lc.add(lastc);
}
// If only 2 points found, make Line
if (lc.size() == 2) {
setType(GeometryType.LINE);
}
// Forced closing polygon
if (getType() == GeometryType.POLYGON) {
if (!firstc.equals2D(lastc)) {
lc.add(firstc);
}
}
/* TODO uitzoeken of lijn zichzelf snijdt, zo ja nodding
* zie jts union:
* Collection lineStrings = . . .
* Geometry nodedLineStrings = (LineString) lineStrings.get(0);
* for (int i = 1; i < lineStrings.size(); i++) {
* nodedLineStrings = nodedLineStrings.union((LineString)lineStrings.get(i));
* */
return rotateAndPlace(lc.toArray(new Coordinate[] {}));
}
public String toString(
String name, int flag, int numVert, int c, int visibility, double thickness) {
StringBuffer s = new StringBuffer();
s.append("DXFPolyline [");
s.append("name: ");
s.append(name + ", ");
s.append("flag: ");
s.append(flag + ", ");
s.append("numVert: ");
s.append(numVert + ", ");
s.append("color: ");
s.append(c + ", ");
s.append("visibility: ");
s.append(visibility + ", ");
s.append("thickness: ");
s.append(thickness);
s.append("]");
return s.toString();
}
@Override
public String toString() {
return toString(
getName(),
_flag,
theVertices.size(),
getColor(),
(isVisible() ? 0 : 1),
getThickness());
}
@Override
public DXFEntity translate(double x, double y) {
// Move all vertices
Iterator iter = theVertices.iterator();
while (iter.hasNext()) {
DXFLwVertex vertex = (DXFLwVertex) iter.next();
vertex._point.x += x;
vertex._point.y += y;
}
return this;
}
@Override
public DXFEntity clone() {
return new DXFLwPolyline(this);
}
}
| True |
1,802 | 17171_2 | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | UcllJavaEnterprise/first-servlet | src/main/java/be/ucll/java/ent/InschrijvingServlet.java | 1,157 | /*
// Create a cookie. Een 'cookie' kan zeer weinig info bevatten en de inhoud die je wil opslaan hou je best onder de 4000 bytes.
String encodedStr = URLEncoder.encode(stud_name, StandardCharsets.UTF_8.toString());
Cookie cookie = new Cookie(COOKIE_STUDENT, encodedStr);
cookie.setMaxAge(60 * 60 * 24 * 7); // Seconds, 60 * 60 * 24 * 7 = 1 week
response.addCookie(cookie);
this.getServletContext().log("Added cookie with name: " + COOKIE_STUDENT + ", value: " + encodedStr);
*/ | block_comment | nl | package be.ucll.java.ent;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@WebServlet("/inschrijving")
public class InschrijvingServlet extends HttpServlet {
// private static final String COOKIE_STUDENT = "StudentInfo";
private String stud_name = "";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie: cookies){
if (cookie != null && cookie.getName() != null && cookie.getName().trim().equalsIgnoreCase(COOKIE_STUDENT)) {
String tmp = cookie.getValue();
if (tmp != null && tmp.trim().length() > 0) {
stud_name = URLDecoder.decode(tmp.trim(), StandardCharsets.UTF_8.toString());
}
}
}
} else {
this.getServletContext().log("No cookies found");
}
*/
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println("<title>Inschrijving</title>");
pw.println("</head>");
pw.println("<body>");
pw.println(" <p><h3>Schrijf u in voor het opleidingsonderdeel 'Java Enterprise'.</h3>");
pw.println(" <form action='" + request.getContextPath() + request.getServletPath() + "' method='post'>");
pw.println(" Student naam: <input type='text' name='stud_name' size='50' maxlength='50' value='" + stud_name + "' /><br/><br/> ");
pw.println(" <input type='submit' value='Inschrijven'/>");
pw.println(" </form></p>");
pw.println("</body>");
pw.println("</html>");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
stud_name = request.getParameter("stud_name");
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
pw.println("<html>");
pw.println("<head>");
pw.println(" <title>Hello Servlets</title>");
pw.println("</head>");
pw.println("<body>");
if (stud_name != null && stud_name.trim().length() > 0) {
pw.println(" <p><h3>Bedankt " + stud_name + ". U bent ingeschreven</h3>");
/*
// Create a cookie.<SUF>*/
} else {
pw.println(" <p><h3>De naam ontbreekt. U bent niet ingeschreven</h3>");
}
pw.println(" <br/><a href='." + request.getServletPath() + "'>Keer terug naar inschrijving</a>");
pw.println(" <br/><br/>Session Id: " + request.getSession().getId());
pw.println("</body>");
pw.println("</html>");
}
}
} | True |
636 | 43016_2 | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
| Guusje2/FTCUnits-SkyStone | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/CraterSide.java | 3,502 | //TODO: meten startwaarde, gemiddelde pakken vnan een aantal metingen | line_comment | nl | /* Copyright (c) 2018 FIRST. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted (subject to the limitations in the disclaimer below) provided that
* the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* Neither the name of FIRST nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS
* LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.firstinspires.ftc.teamcode;
import com.qualcomm.hardware.bosch.BNO055IMU;
import com.qualcomm.hardware.bosch.JustLoggingAccelerationIntegrator;
import com.qualcomm.hardware.rev.Rev2mDistanceSensor;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.Acceleration;
import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit;
import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder;
import org.firstinspires.ftc.robotcore.external.navigation.AxesReference;
import org.firstinspires.ftc.robotcore.external.navigation.DistanceUnit;
import org.firstinspires.ftc.robotcore.external.navigation.Orientation;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.tfod.Recognition;
import org.firstinspires.ftc.robotcore.external.tfod.TFObjectDetector;
import java.util.List;
/**
* This 2018-2019 OpMode illustrates the basics of using the TensorFlow Object Detection API to
* determine the position of the gold and silver minerals.
*
* Use Android Studio to Copy this Class, and Paste it into your team's code folder with a new name.
* Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list.
*
* IMPORTANT: In order to use this OpMode, you need to obtain your own Vuforia license key as
* is explained below.
*/
@Disabled
@Autonomous(name = "Crater Side", group = "Concept")
public class CraterSide extends LinearOpMode {
private enum mineralPosEnum {none,left,center,right};
private mineralPosEnum mineralPos;
public int Runstate = 0;
private static final String TFOD_MODEL_ASSET = "RoverRuckus.tflite";
private static final String LABEL_GOLD_MINERAL = "Gold Mineral";
private static final String LABEL_SILVER_MINERAL = "Silver Mineral";
private DcMotor MotorFrontLeft;
private DcMotor MotorBackLeft;
private DcMotor MotorFrontRight;
private DcMotor MotorBackRight;
private DcMotor HijsMotor;
private Servo BlockBoxServo;
private Rev2mDistanceSensor frontDistance;
private Rev2mDistanceSensor bottomDistance;
private float LandedDistance = 15.5f; //TODO: meten<SUF>
private float heading;
private BNO055IMU imu;
Acceleration gravity;
//private DcMotor HijsMotor;
float startHeading;
float relativeHeading;
/*
* IMPORTANT: You need to obtain your own license key to use Vuforia. The string below with which
* 'parameters.vuforiaLicenseKey' is initialized is for illustration only, and will not function.
* A Vuforia 'Development' license key, can be obtained free of charge from the Vuforia developer
* web site at https://developer.vuforia.com/license-manager.
*
* Vuforia license keys are always 380 characters long, and look as if they contain mostly
* random data. As an example, here is a example of a fragment of a valid key:
* ... yIgIzTqZ4mWjk9wd3cZO9T1axEqzuhxoGlfOOI2dRzKS4T0hQ8kT ...
* Once you've obtained a license key, copy the string from the Vuforia web site
* and paste it in to your code on the next line, between the double quotes.
*/
private static final String VUFORIA_KEY = "AfjFORf/////AAABmdp8TdE6Nkuqs+jlHLz05V0LetUXImgc6W92YLIchdsfSuMAtrfYRSeeVYC0dBEgnqdEg16/6KMZcJ8yA55f9h+m01rF5tmJZIe+A//Wv2CcrjRBZ4IbSDFNwzUi23aMJTETtEJ7bpbOul6O1qyhCMVC8T0FLZc7HJJUjkMhZxaCm46Kfpzw2z9yfaU+cbRAO6AIe83UJh5km2Gom3d562hIZekNhaZsbDz3InjVx80/mOhqKOp0FyoZ8SiwBTRftydNo1tkaZhrOpGtgbIURMW+hhyu7TXnM75gOMHBuG5idIUIqZCWZxfSEITmadeGvkWwW7kONeD/VXYLdHh+Dt9zuMnzmGkG1gPhNeQ/JvD+";
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
private VuforiaLocalizer vuforia;
/**
* {@link #tfod} is the variable we will use to store our instance of the Tensor Flow Object
* Detection engine.
*/
private TFObjectDetector tfod;
@Override
public void runOpMode() {
//IMU parameter setup
BNO055IMU.Parameters parameters = new BNO055IMU.Parameters();
parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES;
parameters.accelUnit = BNO055IMU.AccelUnit.METERS_PERSEC_PERSEC;
parameters.calibrationDataFile = "BNO055IMUCalibration.json"; // see the calibration sample opmode
parameters.loggingEnabled = true;
parameters.loggingTag = "IMU";
parameters.accelerationIntegrationAlgorithm = new JustLoggingAccelerationIntegrator();
double StartTimeDetection = 0;
//IMU start
imu = hardwareMap.get(BNO055IMU.class, "imu");
imu.initialize(parameters);
startHeading = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.addData("IMU status",imu.isGyroCalibrated());
//starting logging
try {
logUtils.StartLogging(3);
} catch (Exception e){
}
// The TFObjectDetector uses the camera frames from the VuforiaLocalizer, so we create that
// first.
Orientation a = imu.getAngularOrientation();
telemetry.addData("StartHeading", startHeading);
MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft");
MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight");
MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft");
MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight");
BlockBoxServo = hardwareMap.servo.get("BlockBoxServo");
Runstate = 0;
HijsMotor = hardwareMap.dcMotor.get("LiftMotor");
HijsMotor.setPower(-.5);
frontDistance = hardwareMap.get(Rev2mDistanceSensor.class, "front");
bottomDistance = hardwareMap.get(Rev2mDistanceSensor.class, "bottom");
/** Wait for the game to begin */
telemetry.addData(">", "Press Play to start tracking");
telemetry.update();
waitForStart();
if (opModeIsActive()) {
while (opModeIsActive()) {
logUtils.Log(logUtils.logType.normal,String.valueOf( Runstate), 3);
relativeHeading = startHeading + imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES).firstAngle;
telemetry.update();
switch (Runstate){
case 0:
telemetry.addData("Status", "Hanging");
HijsMotor.setPower(0);
if(bottomDistance.getDistance(DistanceUnit.CM) > 17){
sleep(50);
continue;
}
Runstate = 10;
break;
case 10:
telemetry.addData("Status", "Dropping");
sleep(200);
MoveSideWays(-1);
sleep(150);
MoveSideWays(0);
HijsMotor.setPower(-1);
sleep(600);
HijsMotor.setPower(0);
MoveSideWays(1);
sleep(150);
MoveSideWays(0);
Runstate = 15;
break;
case 15:
MoveForward(1f);
sleep(5000);
MoveForward(0);
logUtils.StopLogging(3);
stop();
}
}
}
}
/**
* Initialize the Vuforia localization engine.
*/
/**
* for driving sideways, also called strafing
* @param direction 1=right, -1=left
*/
public void MoveSideWays(int direction) {
MotorBackLeft.setPower(direction);
MotorFrontLeft.setPower(-direction);
MotorBackRight.setPower(-direction);
MotorFrontRight.setPower(direction);
}
/**
* For moving the robot forwards/backwards
* @param speed the robots speed, on a scale from -1 to 1 (negative for backwards, positive for forwards
*/
public void MoveForward(float speed){
MotorFrontRight.setPower(-speed*.5);
MotorBackRight.setPower(-speed*.5 );
MotorFrontLeft.setPower(speed*.5 );
MotorBackLeft.setPower(speed*.5 );
}
/**
* For turning the robot whilst staying in place
* @param speed the speed the robot turns, 1 for clockwise
*/
public void Turn(float speed) {
MotorFrontRight.setPower(speed * .5);
MotorBackRight.setPower(speed * .5);
MotorFrontLeft.setPower(speed * .5);
MotorBackLeft.setPower(speed * .5);
}
/**
* used for checking the camera view with Tensorflow
*/
}
| False |
1,752 | 10815_0 | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO zie oefening 3
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| TomEversdijk/Bomen_en_grafen_oefeningen | week05_Heap/src/domain/BinaryMinHeap.java | 498 | //TO DO zie oefening 3 | line_comment | nl | package domain;
import java.util.ArrayList;
public class BinaryMinHeap<E extends Comparable<E>> {
private ArrayList<E> values;
private boolean isEmpty() {
return values == null || values.size() == 0;
}
public void print() {
if (this.isEmpty())
System.out.println("De heap is leeg");
else
System.out.println(values);
}
public E getMin() {
if (this.isEmpty())
throw new IllegalStateException("Kan niet zoeken in een lege heap");
//TO DO<SUF>
return null;
}
public boolean addValue(E value) {
// geen null toevoegen aan de heap
if (value == null) throw new IllegalArgumentException();
// indien de heap leeg is: eerst initialiseren
if (this.isEmpty())
values = new ArrayList<E>();
values.add(value);//achteraan toevoegen
this.bubbleUp();//bubbleUp vanaf de laatste zie slides theorie
return true;
}
private void bubbleUp() {
//TO DO : oefening 4
}
public E removeSmallest() {
if (this.isEmpty())
throw new IllegalStateException("Kan niets verwijderen uit een lege boom");
E res = this.getMin();// res bevat de kleinste = eerste element van de lijst
this.values.set(0, this.values.get(this.values.size() - 1));// verwissel eerste met de laatste
this.values.remove(this.values.size() - 1); // verwijder de laatste
this.bubbleDown(); // bubble down van eerste naar beneden zie theorie
return res;
}
private void bubbleDown() {
// TODO zie oefening 5
}
public ArrayList<E> getPath(E value) {
// TODO zie oefening 6;
return null;
}
}
| True |
1,596 | 41419_0 | package simonjang.androidmeting;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements Introduction.OnFragmentInteractionListener {
SharedPreferences prefs = null;
@BindView(R.id.collapsingToolbar)
CollapsingToolbarLayout toolbarLayout;
@BindView(R.id.appBar)
AppBarLayout appBar;
android.support.v4.app.FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("simonjang.androidmeting", MODE_PRIVATE);
if(prefs.getBoolean("dataInserted", true)) {
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fm = getSupportFragmentManager();
setupWelcome();
}
else {
startOverview();
}
}
private void setupWelcome() {
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
toolbarLayout.setTitle("Meting Applicatie");
toolbarLayout.setCollapsedTitleTextColor(Color.BLACK);
isShow = true;
} else if(isShow) {
toolbarLayout.setTitle("");
isShow = false;
}
}
});
}
private void startOverview() {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
@Override
public void onFragmentInteraction(Uri uri) {
// Moet deze methode implementeren zodat Fragments kunnen gebruikt worden
// Je kan een Activty ook laten ervan van FragmentActivity
}
/*
XML-methode voor fragment toe te voegen werkt hier beter
Fragment in deze activity was eerder een probeersel
private void startIntroduction() {
android.support.v4.app.FragmentTransaction fmt = fm.beginTransaction();
fmt.add(R.id.intro_container, new Introduction());
fmt.commit();
}
*/
}
| SimonJang/MetingAndroid | app/src/main/java/simonjang/androidmeting/MainActivity.java | 781 | // Moet deze methode implementeren zodat Fragments kunnen gebruikt worden | line_comment | nl | package simonjang.androidmeting;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MainActivity extends AppCompatActivity implements Introduction.OnFragmentInteractionListener {
SharedPreferences prefs = null;
@BindView(R.id.collapsingToolbar)
CollapsingToolbarLayout toolbarLayout;
@BindView(R.id.appBar)
AppBarLayout appBar;
android.support.v4.app.FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
prefs = getSharedPreferences("simonjang.androidmeting", MODE_PRIVATE);
if(prefs.getBoolean("dataInserted", true)) {
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
fm = getSupportFragmentManager();
setupWelcome();
}
else {
startOverview();
}
}
private void setupWelcome() {
appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
boolean isShow = false;
int scrollRange = -1;
@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
if (scrollRange == -1) {
scrollRange = appBarLayout.getTotalScrollRange();
}
if (scrollRange + verticalOffset == 0) {
toolbarLayout.setTitle("Meting Applicatie");
toolbarLayout.setCollapsedTitleTextColor(Color.BLACK);
isShow = true;
} else if(isShow) {
toolbarLayout.setTitle("");
isShow = false;
}
}
});
}
private void startOverview() {
Intent intent = new Intent(this, MainMenu.class);
startActivity(intent);
}
@Override
public void onFragmentInteraction(Uri uri) {
// Moet deze<SUF>
// Je kan een Activty ook laten ervan van FragmentActivity
}
/*
XML-methode voor fragment toe te voegen werkt hier beter
Fragment in deze activity was eerder een probeersel
private void startIntroduction() {
android.support.v4.app.FragmentTransaction fmt = fm.beginTransaction();
fmt.add(R.id.intro_container, new Introduction());
fmt.commit();
}
*/
}
| False |
3,905 | 80502_13 | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.api.db;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.openmrs.Concept;
import org.openmrs.ConceptAnswer;
import org.openmrs.ConceptAttribute;
import org.openmrs.ConceptAttributeType;
import org.openmrs.ConceptClass;
import org.openmrs.ConceptComplex;
import org.openmrs.ConceptDatatype;
import org.openmrs.ConceptDescription;
import org.openmrs.ConceptMap;
import org.openmrs.ConceptMapType;
import org.openmrs.ConceptName;
import org.openmrs.ConceptNameTag;
import org.openmrs.ConceptNumeric;
import org.openmrs.ConceptProposal;
import org.openmrs.ConceptReferenceTerm;
import org.openmrs.ConceptReferenceTermMap;
import org.openmrs.ConceptSearchResult;
import org.openmrs.ConceptSet;
import org.openmrs.ConceptSource;
import org.openmrs.ConceptStopWord;
import org.openmrs.Drug;
import org.openmrs.DrugIngredient;
import org.openmrs.api.APIException;
import org.openmrs.api.ConceptService;
/**
* Concept-related database functions
*
* @see ConceptService
*/
public interface ConceptDAO {
/**
* @see org.openmrs.api.ConceptService#saveConcept(org.openmrs.Concept)
*/
public Concept saveConcept(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConcept(org.openmrs.Concept)
* <strong>Should</strong> purge concept
*/
public void purgeConcept(Concept concept) throws DAOException;
/**
* Get a ConceptComplex. The Concept.getDatatype() is "Complex" and the Concept.getHandler() is
* the class name for the ComplexObsHandler key associated with this ConceptComplex.
*
* @param conceptId
* @return the ConceptComplex
*/
public ConceptComplex getConceptComplex(Integer conceptId);
/**
* @see org.openmrs.api.ConceptService#purgeDrug(org.openmrs.Drug)
*/
public void purgeDrug(Drug drug) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveDrug(org.openmrs.Drug)
*/
public Drug saveDrug(Drug drug) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConcept(java.lang.Integer)
*/
public Concept getConcept(Integer conceptId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptName(java.lang.Integer)
* @param conceptNameId
* @return The ConceptName matching the specified conceptNameId
*/
public ConceptName getConceptName(Integer conceptNameId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConcepts(java.lang.String, boolean, boolean)
*/
public List<Concept> getAllConcepts(String sortBy, boolean asc, boolean includeRetired) throws DAOException;
/**
* Returns a list of concepts based on the search criteria
*
* @param name
* @param loc
* @param searchOnPhrase This puts wildcard characters around the concept name search criteria
* @return List<Concept>
* @throws DAOException
* <strong>Should</strong> not return concepts with matching names that are voided
*/
public List<Concept> getConcepts(String name, Locale loc, boolean searchOnPhrase, List<ConceptClass> classes,
List<ConceptDatatype> datatypes) throws DAOException;
/**
* @see ConceptService#getConcepts(String, List, boolean, List, List, List, List, Concept,
* Integer, Integer)
* @throws DAOException
* <strong>Should</strong> return correct results for concept with names that contains words with more weight
* <strong>Should</strong> return correct results if a concept name contains same word more than once
*/
public List<ConceptSearchResult> getConcepts(String phrase, List<Locale> locales, boolean includeRetired,
List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes,
List<ConceptDatatype> excludeDatatypes, Concept answersToConcept, Integer start, Integer size)
throws DAOException;
public Integer getCountOfConcepts(String phrase, List<Locale> locales, boolean includeRetired,
List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes,
List<ConceptDatatype> excludeDatatypes, Concept answersToConcept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptAnswer(java.lang.Integer)
*/
public ConceptAnswer getConceptAnswer(Integer conceptAnswerId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer)
*/
public Drug getDrug(Integer drugId) throws DAOException;
/**
* DAO for retrieving a list of drugs based on the following criteria
*
* @param drugName
* @param concept
* @param includeRetired
* @return List<Drug>
* @throws DAOException
*/
public List<Drug> getDrugs(String drugName, Concept concept, boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrugs(java.lang.String)
*/
public List<Drug> getDrugs(String phrase) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptClass(java.lang.Integer)
*/
public ConceptClass getConceptClass(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptClassByName(java.lang.String)
*/
public List<ConceptClass> getConceptClasses(String name) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptClasses(boolean)
*/
public List<ConceptClass> getAllConceptClasses(boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptClass(org.openmrs.ConceptClass)
*/
public ConceptClass saveConceptClass(ConceptClass cc) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptClass(org.openmrs.ConceptClass)
*/
public void purgeConceptClass(ConceptClass cc) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptNameTag(org.openmrs.ConceptNameTag)
*/
public void deleteConceptNameTag(ConceptNameTag cnt) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptDatatypes(boolean)
*/
public List<ConceptDatatype> getAllConceptDatatypes(boolean includeRetired) throws DAOException;
/**
* @param name
* @return the {@link ConceptDatatype} that matches <em>name</em> exactly or null if one does
* not exist.
* @throws DAOException
*/
public ConceptDatatype getConceptDatatypeByName(String name) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptDatatype(java.lang.Integer)
*/
public ConceptDatatype getConceptDatatype(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptDatatype(org.openmrs.ConceptDatatype)
*/
public ConceptDatatype saveConceptDatatype(ConceptDatatype cd) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptDatatype(org.openmrs.ConceptDatatype)
*/
public void purgeConceptDatatype(ConceptDatatype cd) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSetsByConcept(org.openmrs.Concept)
*/
public List<ConceptSet> getConceptSetsByConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getSetsContainingConcept(org.openmrs.Concept)
*/
public List<ConceptSet> getSetsContainingConcept(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptNumeric(java.lang.Integer)
*/
public ConceptNumeric getConceptNumeric(Integer conceptId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptsByAnswer(org.openmrs.Concept)
* <strong>Should</strong> return concepts for the given answer concept
*/
public List<Concept> getConceptsByAnswer(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getPrevConcept(org.openmrs.Concept)
*/
public Concept getPrevConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getNextConcept(org.openmrs.Concept)
*/
public Concept getNextConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptProposals(boolean)
*/
public List<ConceptProposal> getAllConceptProposals(boolean includeComplete) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptProposal(java.lang.Integer)
*/
public ConceptProposal getConceptProposal(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptProposals(java.lang.String)
*/
public List<ConceptProposal> getConceptProposals(String text) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getProposedConcepts(java.lang.String)
*/
public List<Concept> getProposedConcepts(String text) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptProposal(org.openmrs.ConceptProposal)
*/
public ConceptProposal saveConceptProposal(ConceptProposal cp) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptProposal(org.openmrs.ConceptProposal)
*/
public void purgeConceptProposal(ConceptProposal cp) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptsWithDrugsInFormulary()
*/
public List<Concept> getConceptsWithDrugsInFormulary() throws DAOException;
public ConceptNameTag saveConceptNameTag(ConceptNameTag nameTag);
public ConceptNameTag getConceptNameTag(Integer i);
public ConceptNameTag getConceptNameTagByName(String name);
/**
* @see org.openmrs.api.ConceptService#getAllConceptNameTags()
*/
public List<ConceptNameTag> getAllConceptNameTags();
/**
* @see org.openmrs.api.ConceptService#getConceptSource(java.lang.Integer)
*/
public ConceptSource getConceptSource(Integer conceptSourceId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptSources(boolean)
*/
public List<ConceptSource> getAllConceptSources(boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptSource(org.openmrs.ConceptSource)
*/
public ConceptSource saveConceptSource(ConceptSource conceptSource) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptSource(org.openmrs.ConceptSource)
*/
public ConceptSource deleteConceptSource(ConceptSource cs) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getLocalesOfConceptNames()
*/
public Set<Locale> getLocalesOfConceptNames();
/**
* @see ConceptService#getMaxConceptId()
*/
public Integer getMaxConceptId();
/**
* @see org.openmrs.api.ConceptService#conceptIterator()
*/
public Iterator<Concept> conceptIterator();
/**
* @see org.openmrs.api.ConceptService#getConceptsByMapping(java.lang.String, java.lang.String)
*
* @deprecated As of 2.5.0, this method has been deprecated in favor of {@link #getConceptIdsByMapping(String, String, boolean)}
*/
@Deprecated
public List<Concept> getConceptsByMapping(String code, String sourceName, boolean includeRetired);
/**
* @see org.openmrs.api.ConceptService#getConceptIdsByMapping(String, String, boolean)
*/
public List<Integer> getConceptIdsByMapping(String code, String sourceName, boolean includeRetired);
/**
* @param uuid
* @return concept or null
*/
public Concept getConceptByUuid(String uuid);
/**
* @param uuid
* @return concept class or null
*/
public ConceptClass getConceptClassByUuid(String uuid);
public ConceptAnswer getConceptAnswerByUuid(String uuid);
public ConceptName getConceptNameByUuid(String uuid);
public ConceptSet getConceptSetByUuid(String uuid);
public ConceptSource getConceptSourceByUuid(String uuid);
/**
* @param uuid
* @return concept data type or null
*/
public ConceptDatatype getConceptDatatypeByUuid(String uuid);
/**
* @param uuid
* @return concept numeric or null
*/
public ConceptNumeric getConceptNumericByUuid(String uuid);
/**
* @param uuid
* @return concept proposal or null
*/
public ConceptProposal getConceptProposalByUuid(String uuid);
/**
* @param uuid
* @return drug or null
*/
public Drug getDrugByUuid(String uuid);
public DrugIngredient getDrugIngredientByUuid(String uuid);
public Map<Integer, String> getConceptUuids();
public ConceptDescription getConceptDescriptionByUuid(String uuid);
public ConceptNameTag getConceptNameTagByUuid(String uuid);
/**
* @see ConceptService#getConceptMappingsToSource(ConceptSource)
*/
public List<ConceptMap> getConceptMapsBySource(ConceptSource conceptSource) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByName(java.lang.String)
*/
public ConceptSource getConceptSourceByName(String conceptSourceName) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByUniqueId(java.lang.String)
*/
public ConceptSource getConceptSourceByUniqueId(String uniqueId);
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByHL7Code(java.lang.String)
*/
public ConceptSource getConceptSourceByHL7Code(String hl7Code);
/**
* Gets the value of conceptDatatype currently saved in the database for the given concept,
* bypassing any caches. This is used prior to saving an concept so that we can change the obs
* if need be
*
* @param concept for which the conceptDatatype should be fetched
* @return the conceptDatatype currently in the database for this concept
* <strong>Should</strong> get saved conceptDatatype from database
*/
public ConceptDatatype getSavedConceptDatatype(Concept concept);
/**
* Gets the persisted copy of the conceptName currently saved in the database for the given
* conceptName, bypassing any caches. This is used prior to saving an concept so that we can
* change the obs if need be or avoid breaking any obs referencing it.
*
* @param conceptName ConceptName to fetch from the database
* @return the persisted copy of the conceptName currently saved in the database for this
* conceptName
*/
public ConceptName getSavedConceptName(ConceptName conceptName);
/**
* @see org.openmrs.api.ConceptService#saveConceptStopWord(org.openmrs.ConceptStopWord)
*/
public ConceptStopWord saveConceptStopWord(ConceptStopWord conceptStopWord) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#deleteConceptStopWord(Integer)
*/
public void deleteConceptStopWord(Integer conceptStopWordId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptStopWords(java.util.Locale)
*/
public List<String> getConceptStopWords(Locale locale) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptStopWords()
*/
public List<ConceptStopWord> getAllConceptStopWords();
/**
* @see ConceptService#getCountOfDrugs(String, Concept, boolean, boolean, boolean)
*/
public Long getCountOfDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames,
boolean includeRetired) throws DAOException;
/**
* @see ConceptService#getDrugs(String, Concept, boolean, boolean, boolean, Integer, Integer)
*/
public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames,
boolean includeRetired, Integer start, Integer length) throws DAOException;
/**
* @see ConceptService#getDrugsByIngredient(Concept)
*/
public List<Drug> getDrugsByIngredient(Concept ingredient);
/**
* @see ConceptService#getConceptMapTypes(boolean, boolean)
*/
public List<ConceptMapType> getConceptMapTypes(boolean includeRetired, boolean includeHidden) throws DAOException;
/**
* @see ConceptService#getConceptMapType(Integer)
*/
public ConceptMapType getConceptMapType(Integer conceptMapTypeId) throws DAOException;
/**
* @see ConceptService#getConceptMapTypeByUuid(String)
*/
public ConceptMapType getConceptMapTypeByUuid(String uuid) throws DAOException;
/**
* @see ConceptService#getConceptMapTypeByName(String)
*/
public ConceptMapType getConceptMapTypeByName(String name) throws DAOException;
/**
* @see ConceptService#saveConceptMapType(ConceptMapType)
*/
public ConceptMapType saveConceptMapType(ConceptMapType conceptMapType) throws DAOException;
/**
* @see ConceptService#purgeConceptMapType(ConceptMapType)
*/
public void deleteConceptMapType(ConceptMapType conceptMapType) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerms(boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTerms(boolean includeRetired) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerm(Integer)
*/
public ConceptReferenceTerm getConceptReferenceTerm(Integer conceptReferenceTermId) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByUuid(String)
*/
public ConceptReferenceTerm getConceptReferenceTermByUuid(String uuid) throws DAOException;
public List<ConceptReferenceTerm> getConceptReferenceTermsBySource(ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByName(String, ConceptSource)
*/
public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource)
*/
public ConceptReferenceTerm getConceptReferenceTermByCode(String code, ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource, boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTermByCode(String code, ConceptSource conceptSource, boolean includeRetired) throws DAOException;
/**
* @see ConceptService#saveConceptReferenceTerm(ConceptReferenceTerm)
*/
public ConceptReferenceTerm saveConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException;
/**
* @see ConceptService#purgeConceptReferenceTerm(ConceptReferenceTerm)
*/
public void deleteConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException;
/**
* @see ConceptService#getCountOfConceptReferenceTerms(String, ConceptSource, boolean)
*/
public Long getCountOfConceptReferenceTerms(String query, ConceptSource conceptSource, boolean includeRetired)
throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerms(String, ConceptSource, Integer, Integer,
* boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTerms(String query, ConceptSource conceptSource, Integer start,
Integer length, boolean includeRetired) throws APIException;
/**
* @see ConceptService#getReferenceTermMappingsTo(ConceptReferenceTerm)
*/
public List<ConceptReferenceTermMap> getReferenceTermMappingsTo(ConceptReferenceTerm term) throws DAOException;
/**
* Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the
* specified term
*
* @param term
* @return true if term is in use
* @throws DAOException
* <strong>Should</strong> return true if a term has a conceptMap or more using it
* <strong>Should</strong> return true if a term has a conceptReferenceTermMap or more using it
* <strong>Should</strong> return false if a term has no maps using it
*/
public boolean isConceptReferenceTermInUse(ConceptReferenceTerm term) throws DAOException;
/**
* Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the
* specified mapType
*
* @param mapType
* @return true if map type is in use
* @throws DAOException
* <strong>Should</strong> return true if a mapType has a conceptMap or more using it
* <strong>Should</strong> return true if a mapType has a conceptReferenceTermMap or more using it
* <strong>Should</strong> return false if a mapType has no maps using it
*/
public boolean isConceptMapTypeInUse(ConceptMapType mapType) throws DAOException;
/**
* @see ConceptService#getConceptsByName(String, Locale, Boolean)
*/
public List<Concept> getConceptsByName(String name, Locale locale, Boolean exactLocal);
/**
* @see ConceptService#getConceptByName(String)
*/
public Concept getConceptByName(String name);
/**
* It is in the DAO, because it must be done in the MANUAL flush mode to prevent premature
* flushes in {@link ConceptService#saveConcept(Concept)}. It will be removed in 1.10 when we
* have a better way to manage flush modes.
*
* @see ConceptService#getDefaultConceptMapType()
*/
public ConceptMapType getDefaultConceptMapType() throws DAOException;
/**
* @see ConceptService#isConceptNameDuplicate(ConceptName)
*/
public boolean isConceptNameDuplicate(ConceptName name);
/**
* @see ConceptService#getDrugs(String, java.util.Locale, boolean, boolean)
*/
public List<Drug> getDrugs(String searchPhrase, Locale locale, boolean exactLocale, boolean includeRetired);
/**
* @see org.openmrs.api.ConceptService#getDrugsByMapping(String, ConceptSource, Collection,
* boolean)
*/
public List<Drug> getDrugsByMapping(String code, ConceptSource conceptSource,
Collection<ConceptMapType> withAnyOfTheseTypes, boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrugByMapping(String, org.openmrs.ConceptSource, java.util.Collection)
*/
Drug getDrugByMapping(String code, ConceptSource conceptSource,
Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference) throws DAOException;
/**
* @see ConceptService#getAllConceptAttributeTypes()
*/
List<ConceptAttributeType> getAllConceptAttributeTypes();
/**
* @see ConceptService#saveConceptAttributeType(ConceptAttributeType)
*/
ConceptAttributeType saveConceptAttributeType(ConceptAttributeType conceptAttributeType);
/**
* @see ConceptService#getConceptAttributeType(Integer)
*/
ConceptAttributeType getConceptAttributeType(Integer id);
/**
* @see ConceptService#getConceptAttributeTypeByUuid(String)
*/
ConceptAttributeType getConceptAttributeTypeByUuid(String uuid);
/**
* @see ConceptService#purgeConceptAttributeType(ConceptAttributeType)
*/
public void deleteConceptAttributeType(ConceptAttributeType conceptAttributeType);
/**
* @see ConceptService#getConceptAttributeTypes(String)
*/
public List<ConceptAttributeType> getConceptAttributeTypes(String name);
/**
* @see ConceptService#getConceptAttributeTypeByName(String)
*/
public ConceptAttributeType getConceptAttributeTypeByName(String exactName);
/**
* @see ConceptService#getConceptAttributeByUuid(String)
*/
public ConceptAttribute getConceptAttributeByUuid(String uuid);
/**
* @see ConceptService#hasAnyConceptAttribute(ConceptAttributeType)
*/
public long getConceptAttributeCount(ConceptAttributeType conceptAttributeType);
List<Concept> getConceptsByClass(ConceptClass conceptClass);
}
| openmrs/openmrs-core | api/src/main/java/org/openmrs/api/db/ConceptDAO.java | 7,503 | /**
* @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer)
*/ | block_comment | nl | /**
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under
* the terms of the Healthcare Disclaimer located at http://openmrs.org/license.
*
* Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS
* graphic logo is a trademark of OpenMRS Inc.
*/
package org.openmrs.api.db;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.openmrs.Concept;
import org.openmrs.ConceptAnswer;
import org.openmrs.ConceptAttribute;
import org.openmrs.ConceptAttributeType;
import org.openmrs.ConceptClass;
import org.openmrs.ConceptComplex;
import org.openmrs.ConceptDatatype;
import org.openmrs.ConceptDescription;
import org.openmrs.ConceptMap;
import org.openmrs.ConceptMapType;
import org.openmrs.ConceptName;
import org.openmrs.ConceptNameTag;
import org.openmrs.ConceptNumeric;
import org.openmrs.ConceptProposal;
import org.openmrs.ConceptReferenceTerm;
import org.openmrs.ConceptReferenceTermMap;
import org.openmrs.ConceptSearchResult;
import org.openmrs.ConceptSet;
import org.openmrs.ConceptSource;
import org.openmrs.ConceptStopWord;
import org.openmrs.Drug;
import org.openmrs.DrugIngredient;
import org.openmrs.api.APIException;
import org.openmrs.api.ConceptService;
/**
* Concept-related database functions
*
* @see ConceptService
*/
public interface ConceptDAO {
/**
* @see org.openmrs.api.ConceptService#saveConcept(org.openmrs.Concept)
*/
public Concept saveConcept(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConcept(org.openmrs.Concept)
* <strong>Should</strong> purge concept
*/
public void purgeConcept(Concept concept) throws DAOException;
/**
* Get a ConceptComplex. The Concept.getDatatype() is "Complex" and the Concept.getHandler() is
* the class name for the ComplexObsHandler key associated with this ConceptComplex.
*
* @param conceptId
* @return the ConceptComplex
*/
public ConceptComplex getConceptComplex(Integer conceptId);
/**
* @see org.openmrs.api.ConceptService#purgeDrug(org.openmrs.Drug)
*/
public void purgeDrug(Drug drug) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveDrug(org.openmrs.Drug)
*/
public Drug saveDrug(Drug drug) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConcept(java.lang.Integer)
*/
public Concept getConcept(Integer conceptId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptName(java.lang.Integer)
* @param conceptNameId
* @return The ConceptName matching the specified conceptNameId
*/
public ConceptName getConceptName(Integer conceptNameId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConcepts(java.lang.String, boolean, boolean)
*/
public List<Concept> getAllConcepts(String sortBy, boolean asc, boolean includeRetired) throws DAOException;
/**
* Returns a list of concepts based on the search criteria
*
* @param name
* @param loc
* @param searchOnPhrase This puts wildcard characters around the concept name search criteria
* @return List<Concept>
* @throws DAOException
* <strong>Should</strong> not return concepts with matching names that are voided
*/
public List<Concept> getConcepts(String name, Locale loc, boolean searchOnPhrase, List<ConceptClass> classes,
List<ConceptDatatype> datatypes) throws DAOException;
/**
* @see ConceptService#getConcepts(String, List, boolean, List, List, List, List, Concept,
* Integer, Integer)
* @throws DAOException
* <strong>Should</strong> return correct results for concept with names that contains words with more weight
* <strong>Should</strong> return correct results if a concept name contains same word more than once
*/
public List<ConceptSearchResult> getConcepts(String phrase, List<Locale> locales, boolean includeRetired,
List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes,
List<ConceptDatatype> excludeDatatypes, Concept answersToConcept, Integer start, Integer size)
throws DAOException;
public Integer getCountOfConcepts(String phrase, List<Locale> locales, boolean includeRetired,
List<ConceptClass> requireClasses, List<ConceptClass> excludeClasses, List<ConceptDatatype> requireDatatypes,
List<ConceptDatatype> excludeDatatypes, Concept answersToConcept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptAnswer(java.lang.Integer)
*/
public ConceptAnswer getConceptAnswer(Integer conceptAnswerId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrug(java.lang.Integer)
<SUF>*/
public Drug getDrug(Integer drugId) throws DAOException;
/**
* DAO for retrieving a list of drugs based on the following criteria
*
* @param drugName
* @param concept
* @param includeRetired
* @return List<Drug>
* @throws DAOException
*/
public List<Drug> getDrugs(String drugName, Concept concept, boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrugs(java.lang.String)
*/
public List<Drug> getDrugs(String phrase) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptClass(java.lang.Integer)
*/
public ConceptClass getConceptClass(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptClassByName(java.lang.String)
*/
public List<ConceptClass> getConceptClasses(String name) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptClasses(boolean)
*/
public List<ConceptClass> getAllConceptClasses(boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptClass(org.openmrs.ConceptClass)
*/
public ConceptClass saveConceptClass(ConceptClass cc) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptClass(org.openmrs.ConceptClass)
*/
public void purgeConceptClass(ConceptClass cc) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptNameTag(org.openmrs.ConceptNameTag)
*/
public void deleteConceptNameTag(ConceptNameTag cnt) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptDatatypes(boolean)
*/
public List<ConceptDatatype> getAllConceptDatatypes(boolean includeRetired) throws DAOException;
/**
* @param name
* @return the {@link ConceptDatatype} that matches <em>name</em> exactly or null if one does
* not exist.
* @throws DAOException
*/
public ConceptDatatype getConceptDatatypeByName(String name) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptDatatype(java.lang.Integer)
*/
public ConceptDatatype getConceptDatatype(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptDatatype(org.openmrs.ConceptDatatype)
*/
public ConceptDatatype saveConceptDatatype(ConceptDatatype cd) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptDatatype(org.openmrs.ConceptDatatype)
*/
public void purgeConceptDatatype(ConceptDatatype cd) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSetsByConcept(org.openmrs.Concept)
*/
public List<ConceptSet> getConceptSetsByConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getSetsContainingConcept(org.openmrs.Concept)
*/
public List<ConceptSet> getSetsContainingConcept(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptNumeric(java.lang.Integer)
*/
public ConceptNumeric getConceptNumeric(Integer conceptId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptsByAnswer(org.openmrs.Concept)
* <strong>Should</strong> return concepts for the given answer concept
*/
public List<Concept> getConceptsByAnswer(Concept concept) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getPrevConcept(org.openmrs.Concept)
*/
public Concept getPrevConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getNextConcept(org.openmrs.Concept)
*/
public Concept getNextConcept(Concept c) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptProposals(boolean)
*/
public List<ConceptProposal> getAllConceptProposals(boolean includeComplete) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptProposal(java.lang.Integer)
*/
public ConceptProposal getConceptProposal(Integer i) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptProposals(java.lang.String)
*/
public List<ConceptProposal> getConceptProposals(String text) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getProposedConcepts(java.lang.String)
*/
public List<Concept> getProposedConcepts(String text) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptProposal(org.openmrs.ConceptProposal)
*/
public ConceptProposal saveConceptProposal(ConceptProposal cp) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptProposal(org.openmrs.ConceptProposal)
*/
public void purgeConceptProposal(ConceptProposal cp) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptsWithDrugsInFormulary()
*/
public List<Concept> getConceptsWithDrugsInFormulary() throws DAOException;
public ConceptNameTag saveConceptNameTag(ConceptNameTag nameTag);
public ConceptNameTag getConceptNameTag(Integer i);
public ConceptNameTag getConceptNameTagByName(String name);
/**
* @see org.openmrs.api.ConceptService#getAllConceptNameTags()
*/
public List<ConceptNameTag> getAllConceptNameTags();
/**
* @see org.openmrs.api.ConceptService#getConceptSource(java.lang.Integer)
*/
public ConceptSource getConceptSource(Integer conceptSourceId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptSources(boolean)
*/
public List<ConceptSource> getAllConceptSources(boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#saveConceptSource(org.openmrs.ConceptSource)
*/
public ConceptSource saveConceptSource(ConceptSource conceptSource) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#purgeConceptSource(org.openmrs.ConceptSource)
*/
public ConceptSource deleteConceptSource(ConceptSource cs) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getLocalesOfConceptNames()
*/
public Set<Locale> getLocalesOfConceptNames();
/**
* @see ConceptService#getMaxConceptId()
*/
public Integer getMaxConceptId();
/**
* @see org.openmrs.api.ConceptService#conceptIterator()
*/
public Iterator<Concept> conceptIterator();
/**
* @see org.openmrs.api.ConceptService#getConceptsByMapping(java.lang.String, java.lang.String)
*
* @deprecated As of 2.5.0, this method has been deprecated in favor of {@link #getConceptIdsByMapping(String, String, boolean)}
*/
@Deprecated
public List<Concept> getConceptsByMapping(String code, String sourceName, boolean includeRetired);
/**
* @see org.openmrs.api.ConceptService#getConceptIdsByMapping(String, String, boolean)
*/
public List<Integer> getConceptIdsByMapping(String code, String sourceName, boolean includeRetired);
/**
* @param uuid
* @return concept or null
*/
public Concept getConceptByUuid(String uuid);
/**
* @param uuid
* @return concept class or null
*/
public ConceptClass getConceptClassByUuid(String uuid);
public ConceptAnswer getConceptAnswerByUuid(String uuid);
public ConceptName getConceptNameByUuid(String uuid);
public ConceptSet getConceptSetByUuid(String uuid);
public ConceptSource getConceptSourceByUuid(String uuid);
/**
* @param uuid
* @return concept data type or null
*/
public ConceptDatatype getConceptDatatypeByUuid(String uuid);
/**
* @param uuid
* @return concept numeric or null
*/
public ConceptNumeric getConceptNumericByUuid(String uuid);
/**
* @param uuid
* @return concept proposal or null
*/
public ConceptProposal getConceptProposalByUuid(String uuid);
/**
* @param uuid
* @return drug or null
*/
public Drug getDrugByUuid(String uuid);
public DrugIngredient getDrugIngredientByUuid(String uuid);
public Map<Integer, String> getConceptUuids();
public ConceptDescription getConceptDescriptionByUuid(String uuid);
public ConceptNameTag getConceptNameTagByUuid(String uuid);
/**
* @see ConceptService#getConceptMappingsToSource(ConceptSource)
*/
public List<ConceptMap> getConceptMapsBySource(ConceptSource conceptSource) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByName(java.lang.String)
*/
public ConceptSource getConceptSourceByName(String conceptSourceName) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByUniqueId(java.lang.String)
*/
public ConceptSource getConceptSourceByUniqueId(String uniqueId);
/**
* @see org.openmrs.api.ConceptService#getConceptSourceByHL7Code(java.lang.String)
*/
public ConceptSource getConceptSourceByHL7Code(String hl7Code);
/**
* Gets the value of conceptDatatype currently saved in the database for the given concept,
* bypassing any caches. This is used prior to saving an concept so that we can change the obs
* if need be
*
* @param concept for which the conceptDatatype should be fetched
* @return the conceptDatatype currently in the database for this concept
* <strong>Should</strong> get saved conceptDatatype from database
*/
public ConceptDatatype getSavedConceptDatatype(Concept concept);
/**
* Gets the persisted copy of the conceptName currently saved in the database for the given
* conceptName, bypassing any caches. This is used prior to saving an concept so that we can
* change the obs if need be or avoid breaking any obs referencing it.
*
* @param conceptName ConceptName to fetch from the database
* @return the persisted copy of the conceptName currently saved in the database for this
* conceptName
*/
public ConceptName getSavedConceptName(ConceptName conceptName);
/**
* @see org.openmrs.api.ConceptService#saveConceptStopWord(org.openmrs.ConceptStopWord)
*/
public ConceptStopWord saveConceptStopWord(ConceptStopWord conceptStopWord) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#deleteConceptStopWord(Integer)
*/
public void deleteConceptStopWord(Integer conceptStopWordId) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getConceptStopWords(java.util.Locale)
*/
public List<String> getConceptStopWords(Locale locale) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getAllConceptStopWords()
*/
public List<ConceptStopWord> getAllConceptStopWords();
/**
* @see ConceptService#getCountOfDrugs(String, Concept, boolean, boolean, boolean)
*/
public Long getCountOfDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames,
boolean includeRetired) throws DAOException;
/**
* @see ConceptService#getDrugs(String, Concept, boolean, boolean, boolean, Integer, Integer)
*/
public List<Drug> getDrugs(String drugName, Concept concept, boolean searchOnPhrase, boolean searchDrugConceptNames,
boolean includeRetired, Integer start, Integer length) throws DAOException;
/**
* @see ConceptService#getDrugsByIngredient(Concept)
*/
public List<Drug> getDrugsByIngredient(Concept ingredient);
/**
* @see ConceptService#getConceptMapTypes(boolean, boolean)
*/
public List<ConceptMapType> getConceptMapTypes(boolean includeRetired, boolean includeHidden) throws DAOException;
/**
* @see ConceptService#getConceptMapType(Integer)
*/
public ConceptMapType getConceptMapType(Integer conceptMapTypeId) throws DAOException;
/**
* @see ConceptService#getConceptMapTypeByUuid(String)
*/
public ConceptMapType getConceptMapTypeByUuid(String uuid) throws DAOException;
/**
* @see ConceptService#getConceptMapTypeByName(String)
*/
public ConceptMapType getConceptMapTypeByName(String name) throws DAOException;
/**
* @see ConceptService#saveConceptMapType(ConceptMapType)
*/
public ConceptMapType saveConceptMapType(ConceptMapType conceptMapType) throws DAOException;
/**
* @see ConceptService#purgeConceptMapType(ConceptMapType)
*/
public void deleteConceptMapType(ConceptMapType conceptMapType) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerms(boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTerms(boolean includeRetired) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerm(Integer)
*/
public ConceptReferenceTerm getConceptReferenceTerm(Integer conceptReferenceTermId) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByUuid(String)
*/
public ConceptReferenceTerm getConceptReferenceTermByUuid(String uuid) throws DAOException;
public List<ConceptReferenceTerm> getConceptReferenceTermsBySource(ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByName(String, ConceptSource)
*/
public ConceptReferenceTerm getConceptReferenceTermByName(String name, ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource)
*/
public ConceptReferenceTerm getConceptReferenceTermByCode(String code, ConceptSource conceptSource) throws DAOException;
/**
* @see ConceptService#getConceptReferenceTermByCode(String, ConceptSource, boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTermByCode(String code, ConceptSource conceptSource, boolean includeRetired) throws DAOException;
/**
* @see ConceptService#saveConceptReferenceTerm(ConceptReferenceTerm)
*/
public ConceptReferenceTerm saveConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException;
/**
* @see ConceptService#purgeConceptReferenceTerm(ConceptReferenceTerm)
*/
public void deleteConceptReferenceTerm(ConceptReferenceTerm conceptReferenceTerm) throws DAOException;
/**
* @see ConceptService#getCountOfConceptReferenceTerms(String, ConceptSource, boolean)
*/
public Long getCountOfConceptReferenceTerms(String query, ConceptSource conceptSource, boolean includeRetired)
throws DAOException;
/**
* @see ConceptService#getConceptReferenceTerms(String, ConceptSource, Integer, Integer,
* boolean)
*/
public List<ConceptReferenceTerm> getConceptReferenceTerms(String query, ConceptSource conceptSource, Integer start,
Integer length, boolean includeRetired) throws APIException;
/**
* @see ConceptService#getReferenceTermMappingsTo(ConceptReferenceTerm)
*/
public List<ConceptReferenceTermMap> getReferenceTermMappingsTo(ConceptReferenceTerm term) throws DAOException;
/**
* Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the
* specified term
*
* @param term
* @return true if term is in use
* @throws DAOException
* <strong>Should</strong> return true if a term has a conceptMap or more using it
* <strong>Should</strong> return true if a term has a conceptReferenceTermMap or more using it
* <strong>Should</strong> return false if a term has no maps using it
*/
public boolean isConceptReferenceTermInUse(ConceptReferenceTerm term) throws DAOException;
/**
* Checks if there are any {@link ConceptReferenceTermMap}s or {@link ConceptMap}s using the
* specified mapType
*
* @param mapType
* @return true if map type is in use
* @throws DAOException
* <strong>Should</strong> return true if a mapType has a conceptMap or more using it
* <strong>Should</strong> return true if a mapType has a conceptReferenceTermMap or more using it
* <strong>Should</strong> return false if a mapType has no maps using it
*/
public boolean isConceptMapTypeInUse(ConceptMapType mapType) throws DAOException;
/**
* @see ConceptService#getConceptsByName(String, Locale, Boolean)
*/
public List<Concept> getConceptsByName(String name, Locale locale, Boolean exactLocal);
/**
* @see ConceptService#getConceptByName(String)
*/
public Concept getConceptByName(String name);
/**
* It is in the DAO, because it must be done in the MANUAL flush mode to prevent premature
* flushes in {@link ConceptService#saveConcept(Concept)}. It will be removed in 1.10 when we
* have a better way to manage flush modes.
*
* @see ConceptService#getDefaultConceptMapType()
*/
public ConceptMapType getDefaultConceptMapType() throws DAOException;
/**
* @see ConceptService#isConceptNameDuplicate(ConceptName)
*/
public boolean isConceptNameDuplicate(ConceptName name);
/**
* @see ConceptService#getDrugs(String, java.util.Locale, boolean, boolean)
*/
public List<Drug> getDrugs(String searchPhrase, Locale locale, boolean exactLocale, boolean includeRetired);
/**
* @see org.openmrs.api.ConceptService#getDrugsByMapping(String, ConceptSource, Collection,
* boolean)
*/
public List<Drug> getDrugsByMapping(String code, ConceptSource conceptSource,
Collection<ConceptMapType> withAnyOfTheseTypes, boolean includeRetired) throws DAOException;
/**
* @see org.openmrs.api.ConceptService#getDrugByMapping(String, org.openmrs.ConceptSource, java.util.Collection)
*/
Drug getDrugByMapping(String code, ConceptSource conceptSource,
Collection<ConceptMapType> withAnyOfTheseTypesOrOrderOfPreference) throws DAOException;
/**
* @see ConceptService#getAllConceptAttributeTypes()
*/
List<ConceptAttributeType> getAllConceptAttributeTypes();
/**
* @see ConceptService#saveConceptAttributeType(ConceptAttributeType)
*/
ConceptAttributeType saveConceptAttributeType(ConceptAttributeType conceptAttributeType);
/**
* @see ConceptService#getConceptAttributeType(Integer)
*/
ConceptAttributeType getConceptAttributeType(Integer id);
/**
* @see ConceptService#getConceptAttributeTypeByUuid(String)
*/
ConceptAttributeType getConceptAttributeTypeByUuid(String uuid);
/**
* @see ConceptService#purgeConceptAttributeType(ConceptAttributeType)
*/
public void deleteConceptAttributeType(ConceptAttributeType conceptAttributeType);
/**
* @see ConceptService#getConceptAttributeTypes(String)
*/
public List<ConceptAttributeType> getConceptAttributeTypes(String name);
/**
* @see ConceptService#getConceptAttributeTypeByName(String)
*/
public ConceptAttributeType getConceptAttributeTypeByName(String exactName);
/**
* @see ConceptService#getConceptAttributeByUuid(String)
*/
public ConceptAttribute getConceptAttributeByUuid(String uuid);
/**
* @see ConceptService#hasAnyConceptAttribute(ConceptAttributeType)
*/
public long getConceptAttributeCount(ConceptAttributeType conceptAttributeType);
List<Concept> getConceptsByClass(ConceptClass conceptClass);
}
| False |
1,680 | 8380_0 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| TOMP-WG/TOMP-REF | tomp_meta/src/main/java/io/swagger/client/ApiCallback.java | 580 | /*
* CBM interface
* Dit document beschrijft de interface van CBM die ten behoeve van Melvin beschikbaar wordt gesteld. . </br></br> De API moet worden uitgevraagd met een token. De token kan met een gebruikersnaam en wachtwoord verkregen worden. De token is tijdelijk geldig, daarna kan een nieuwe token opgevraagd worden. </br></br> De Geo-inputparameters moeten matchen op de door CBM gebruikte OSM-versie.
*
* OpenAPI spec version: 0.1.0
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/ | block_comment | nl | /*
* CBM interface
<SUF>*/
package io.swagger.client;
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API downlond processing.
*
* @param bytesRead bytes Read
* @param contentLength content lenngth of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}
| True |
4,689 | 22086_6 | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays van knoppen, 1 voor iedere panel.
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | wennhao/project3-4 | guiold_OUTDATED/gui.java | 765 | //Drie arrays van knoppen, 1 voor iedere panel. | line_comment | nl | import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String[] args) {
//Initialiseer een nieuwe JFrame en configureer de basics,
//dus size en de ON_CLOSE operation.
JFrame frame = new JFrame("Workshop frame");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Aanmaak van drie JPanels
JPanel flowLayoutPanel = new JPanel();
JPanel boxLayoutPanel = new JPanel();
JPanel gridLayoutPanel = new JPanel();
//Zet voor iedere panel een aparte layout manager;
//FlowLayout voor links naar rechts, BoxLayout voor x-as of y-as, GridLayout voor raster.
//Let op dat sommige layout managers dus parameters mee moeten krijgen in hun constructors.
flowLayoutPanel.setLayout(new FlowLayout());
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
gridLayoutPanel.setLayout(new GridLayout(3, 2));
//Drie arrays<SUF>
JButton[] buttons1 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons2 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
JButton[] buttons3 = {
new JButton("Button1"),
new JButton("Button2"),
new JButton("Button3"),
new JButton("Button4"),
new JButton("Button5"),
new JButton("Button6")
};
//Knoppen toevoegen aan de panels.
for (JButton b : buttons1){
flowLayoutPanel.add(b);
}
for (JButton b : buttons2){
boxLayoutPanel.add(b);
}
for (JButton b : buttons3){
gridLayoutPanel.add(b);
}
//Maak een main panel aan om alle andere panels in onder te brengen, inclusief layout manager.
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
//Voeg de layout panels toe aan de main panel. Let op, volgorde maakt uit.
mainPanel.add(flowLayoutPanel);
mainPanel.add(boxLayoutPanel);
mainPanel.add(gridLayoutPanel);
//Voeg mainpanel toe aan de JFrame en maak de JFrame visible.
frame.add(mainPanel);
frame.setVisible(true);
}
} | True |
4,666 | 5587_4 | /*
* This file is part of Waarp Project (named also Waarp or GG).
*
* Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
* tags. See the COPYRIGHT.txt in the distribution for a full listing of
* individual contributors.
*
* All Waarp Project is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* Waarp . If not, see <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.context.task;
import org.waarp.common.command.exception.CommandAbstractException;
import org.waarp.common.logging.WaarpLogger;
import org.waarp.common.logging.WaarpLoggerFactory;
import org.waarp.common.utility.WaarpStringUtils;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.filesystem.R66Dir;
import org.waarp.openr66.context.filesystem.R66File;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException;
import org.waarp.openr66.protocol.utils.R66Future;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Abstract implementation of task
*/
public abstract class AbstractTask implements Runnable {
/**
* Internal Logger
*/
private static final WaarpLogger logger =
WaarpLoggerFactory.getLogger(AbstractTask.class);
protected static final Pattern BLANK = Pattern.compile(" ");
/**
* Current full path of current FILENAME
*/
public static final String TRUEFULLPATH = "#TRUEFULLPATH#";
/**
* Current FILENAME (basename) (change in retrieval part)
*/
public static final String TRUEFILENAME = "#TRUEFILENAME#";
/**
* Current full path of Original FILENAME (as transmitted) (before changing
* in
* retrieval part)
*/
public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#";
/**
* Original FILENAME (basename) (before changing in retrieval part)
*/
public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#";
/**
* Size of the current FILE
*/
public static final String FILESIZE = "#FILESIZE#";
/**
* Current full path of current RULE
*/
public static final String RULE = "#RULE#";
/**
* Date in yyyyMMdd format
*/
public static final String DATE = "#DATE#";
/**
* Hour in HHmmss format
*/
public static final String HOUR = "#HOUR#";
/**
* Remote host id (if not the initiator of the call)
*/
public static final String REMOTEHOST = "#REMOTEHOST#";
/**
* Remote host address
*/
public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#";
/**
* Local host id
*/
public static final String LOCALHOST = "#LOCALHOST#";
/**
* Local host address
*/
public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#";
/**
* Transfer id
*/
public static final String TRANSFERID = "#TRANSFERID#";
/**
* Requester Host
*/
public static final String REQUESTERHOST = "#REQUESTERHOST#";
/**
* Requested Host
*/
public static final String REQUESTEDHOST = "#REQUESTEDHOST#";
/**
* Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST)
*/
public static final String FULLTRANSFERID = "#FULLTRANSFERID#";
/**
* Current or final RANK of block
*/
public static final String RANKTRANSFER = "#RANKTRANSFER#";
/**
* Block size used
*/
public static final String BLOCKSIZE = "#BLOCKSIZE#";
/**
* IN Path used
*/
public static final String INPATH = "#INPATH#";
/**
* OUT Path used
*/
public static final String OUTPATH = "#OUTPATH#";
/**
* WORK Path used
*/
public static final String WORKPATH = "#WORKPATH#";
/**
* ARCH Path used
*/
public static final String ARCHPATH = "#ARCHPATH#";
/**
* HOME Path used
*/
public static final String HOMEPATH = "#HOMEPATH#";
/**
* Last Current Error Message
*/
public static final String ERRORMSG = "#ERRORMSG#";
/**
* Last Current Error Code
*/
public static final String ERRORCODE = "#ERRORCODE#";
/**
* Last Current Error Code in Full String
*/
public static final String ERRORSTRCODE = "#ERRORSTRCODE#";
/**
* If specified, no Wait for Task Validation (default is wait)
*/
public static final String NOWAIT = "#NOWAIT#";
/**
* If specified, use the LocalExec Daemon specified in the global
* configuration (default no usage of
* LocalExec)
*/
public static final String LOCALEXEC = "#LOCALEXEC#";
/**
* Type of operation
*/
final TaskType type;
/**
* Argument from Rule
*/
final String argRule;
/**
* Delay from Rule (if applicable)
*/
final int delay;
/**
* Argument from Transfer
*/
final String argTransfer;
/**
* Current session
*/
final R66Session session;
/**
* R66Future of completion
*/
final R66Future futureCompletion;
/**
* Do we wait for a validation of the task ? Default = True
*/
boolean waitForValidation = true;
/**
* Do we need to use LocalExec for an Exec Task ? Default = False
*/
boolean useLocalExec;
/**
* Constructor
*
* @param type
* @param delay
* @param argRule
* @param argTransfer
* @param session
*/
AbstractTask(TaskType type, int delay, String argRule, String argTransfer,
R66Session session) {
this.type = type;
this.delay = delay;
this.argRule = argRule;
this.argTransfer = argTransfer;
this.session = session;
futureCompletion = new R66Future(true);
}
/**
* @return the TaskType of this AbstractTask
*/
public TaskType getType() {
return type;
}
/**
* This is the only interface to execute an operator.
*/
@Override
public abstract void run();
/**
* @return True if the operation is in success status
*/
public boolean isSuccess() {
futureCompletion.awaitOrInterruptible();
return futureCompletion.isSuccess();
}
/**
* @return the R66Future of completion
*/
public R66Future getFutureCompletion() {
return futureCompletion;
}
/**
* @param arg as the Format string where FIXED items will be
* replaced by
* context values and next using
* argFormat as format second argument; this arg comes from the
* rule
* itself
* @param argFormat as format second argument; this argFormat comes
* from
* the transfer Information itself
*
* @return The string with replaced values from context and second argument
*/
protected String getReplacedValue(String arg, Object[] argFormat) {
final StringBuilder builder = new StringBuilder(arg);
// check NOWAIT and LOCALEXEC
if (arg.contains(NOWAIT)) {
waitForValidation = false;
WaarpStringUtils.replaceAll(builder, NOWAIT, "");
}
if (arg.contains(LOCALEXEC)) {
useLocalExec = true;
WaarpStringUtils.replaceAll(builder, LOCALEXEC, "");
}
File trueFile = null;
if (session.getFile() != null) {
trueFile = session.getFile().getTrueFile();
}
if (trueFile != null) {
WaarpStringUtils
.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath());
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir
.getFinalUniqueFilename(session.getFile()));
WaarpStringUtils
.replaceAll(builder, FILESIZE, Long.toString(trueFile.length()));
} else {
WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile");
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile");
WaarpStringUtils.replaceAll(builder, FILESIZE, "0");
}
final DbTaskRunner runner = session.getRunner();
if (runner != null) {
WaarpStringUtils
.replaceAll(builder, ORIGINALFULLPATH, runner.getOriginalFilename());
WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, R66File
.getBasename(runner.getOriginalFilename()));
WaarpStringUtils.replaceAll(builder, RULE, runner.getRuleId());
}
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final Date date = new Date();
WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date));
dateFormat = new SimpleDateFormat("HHmmss");
WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date));
if (session.getAuth() != null) {
WaarpStringUtils
.replaceAll(builder, REMOTEHOST, session.getAuth().getUser());
try {
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration
.getHostId(session.getAuth().isSsl()));
} catch (final OpenR66ProtocolNoSslException e) {
// replace by standard name
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration.getHostId());
}
}
if (session.getRemoteAddress() != null) {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR,
session.getRemoteAddress().toString());
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR,
session.getLocalAddress().toString());
} else {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown");
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown");
}
if (runner != null) {
WaarpStringUtils.replaceAll(builder, TRANSFERID,
Long.toString(runner.getSpecialId()));
final String requester = runner.getRequester();
WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester);
final String requested = runner.getRequested();
WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested);
WaarpStringUtils.replaceAll(builder, FULLTRANSFERID,
runner.getSpecialId() + "_" + requester +
'_' + requested);
WaarpStringUtils.replaceAll(builder, RANKTRANSFER,
Integer.toString(runner.getRank()));
}
WaarpStringUtils.replaceAll(builder, BLOCKSIZE,
Integer.toString(session.getBlockSize()));
R66Dir dir = new R66Dir(session);
if (runner != null) {
if (runner.isRecvThrough() || runner.isSendThrough()) {
try {
dir.changeDirectoryNotChecked(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
} else {
try {
dir.changeDirectory(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
} else {
try {
dir.changeDirectory(Configuration.configuration.getInPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getOutPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getWorkingPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
WaarpStringUtils.replaceAll(builder, HOMEPATH,
Configuration.configuration.getBaseDirectory());
if (session.getLocalChannelReference() == null) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
} else {
try {
WaarpStringUtils.replaceAll(builder, ERRORMSG,
session.getLocalChannelReference()
.getErrorMessage());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORCODE,
session.getLocalChannelReference()
.getCurrentCode().getCode());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORSTRCODE,
session.getLocalChannelReference()
.getCurrentCode().name());
} catch (final NullPointerException e) {
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
}
}
// finalname
if (argFormat != null && argFormat.length > 0) {
try {
return String.format(builder.toString(), argFormat);
} catch (final Exception e) {
// ignored error since bad argument in static rule info
logger.error("Bad format in Rule: {" + builder + "} " + e.getMessage());
}
}
return builder.toString();
}
}
| waarp/Waarp-All | WaarpR66/src/main/java/org/waarp/openr66/context/task/AbstractTask.java | 4,743 | /**
* Current FILENAME (basename) (change in retrieval part)
*/ | block_comment | nl | /*
* This file is part of Waarp Project (named also Waarp or GG).
*
* Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
* tags. See the COPYRIGHT.txt in the distribution for a full listing of
* individual contributors.
*
* All Waarp Project is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* Waarp . If not, see <http://www.gnu.org/licenses/>.
*/
package org.waarp.openr66.context.task;
import org.waarp.common.command.exception.CommandAbstractException;
import org.waarp.common.logging.WaarpLogger;
import org.waarp.common.logging.WaarpLoggerFactory;
import org.waarp.common.utility.WaarpStringUtils;
import org.waarp.openr66.context.ErrorCode;
import org.waarp.openr66.context.R66Session;
import org.waarp.openr66.context.filesystem.R66Dir;
import org.waarp.openr66.context.filesystem.R66File;
import org.waarp.openr66.database.data.DbTaskRunner;
import org.waarp.openr66.protocol.configuration.Configuration;
import org.waarp.openr66.protocol.exception.OpenR66ProtocolNoSslException;
import org.waarp.openr66.protocol.utils.R66Future;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;
/**
* Abstract implementation of task
*/
public abstract class AbstractTask implements Runnable {
/**
* Internal Logger
*/
private static final WaarpLogger logger =
WaarpLoggerFactory.getLogger(AbstractTask.class);
protected static final Pattern BLANK = Pattern.compile(" ");
/**
* Current full path of current FILENAME
*/
public static final String TRUEFULLPATH = "#TRUEFULLPATH#";
/**
* Current FILENAME (basename)<SUF>*/
public static final String TRUEFILENAME = "#TRUEFILENAME#";
/**
* Current full path of Original FILENAME (as transmitted) (before changing
* in
* retrieval part)
*/
public static final String ORIGINALFULLPATH = "#ORIGINALFULLPATH#";
/**
* Original FILENAME (basename) (before changing in retrieval part)
*/
public static final String ORIGINALFILENAME = "#ORIGINALFILENAME#";
/**
* Size of the current FILE
*/
public static final String FILESIZE = "#FILESIZE#";
/**
* Current full path of current RULE
*/
public static final String RULE = "#RULE#";
/**
* Date in yyyyMMdd format
*/
public static final String DATE = "#DATE#";
/**
* Hour in HHmmss format
*/
public static final String HOUR = "#HOUR#";
/**
* Remote host id (if not the initiator of the call)
*/
public static final String REMOTEHOST = "#REMOTEHOST#";
/**
* Remote host address
*/
public static final String REMOTEHOSTADDR = "#REMOTEHOSTADDR#";
/**
* Local host id
*/
public static final String LOCALHOST = "#LOCALHOST#";
/**
* Local host address
*/
public static final String LOCALHOSTADDR = "#LOCALHOSTADDR#";
/**
* Transfer id
*/
public static final String TRANSFERID = "#TRANSFERID#";
/**
* Requester Host
*/
public static final String REQUESTERHOST = "#REQUESTERHOST#";
/**
* Requested Host
*/
public static final String REQUESTEDHOST = "#REQUESTEDHOST#";
/**
* Full Transfer id (TRANSFERID_REQUESTERHOST_REQUESTEDHOST)
*/
public static final String FULLTRANSFERID = "#FULLTRANSFERID#";
/**
* Current or final RANK of block
*/
public static final String RANKTRANSFER = "#RANKTRANSFER#";
/**
* Block size used
*/
public static final String BLOCKSIZE = "#BLOCKSIZE#";
/**
* IN Path used
*/
public static final String INPATH = "#INPATH#";
/**
* OUT Path used
*/
public static final String OUTPATH = "#OUTPATH#";
/**
* WORK Path used
*/
public static final String WORKPATH = "#WORKPATH#";
/**
* ARCH Path used
*/
public static final String ARCHPATH = "#ARCHPATH#";
/**
* HOME Path used
*/
public static final String HOMEPATH = "#HOMEPATH#";
/**
* Last Current Error Message
*/
public static final String ERRORMSG = "#ERRORMSG#";
/**
* Last Current Error Code
*/
public static final String ERRORCODE = "#ERRORCODE#";
/**
* Last Current Error Code in Full String
*/
public static final String ERRORSTRCODE = "#ERRORSTRCODE#";
/**
* If specified, no Wait for Task Validation (default is wait)
*/
public static final String NOWAIT = "#NOWAIT#";
/**
* If specified, use the LocalExec Daemon specified in the global
* configuration (default no usage of
* LocalExec)
*/
public static final String LOCALEXEC = "#LOCALEXEC#";
/**
* Type of operation
*/
final TaskType type;
/**
* Argument from Rule
*/
final String argRule;
/**
* Delay from Rule (if applicable)
*/
final int delay;
/**
* Argument from Transfer
*/
final String argTransfer;
/**
* Current session
*/
final R66Session session;
/**
* R66Future of completion
*/
final R66Future futureCompletion;
/**
* Do we wait for a validation of the task ? Default = True
*/
boolean waitForValidation = true;
/**
* Do we need to use LocalExec for an Exec Task ? Default = False
*/
boolean useLocalExec;
/**
* Constructor
*
* @param type
* @param delay
* @param argRule
* @param argTransfer
* @param session
*/
AbstractTask(TaskType type, int delay, String argRule, String argTransfer,
R66Session session) {
this.type = type;
this.delay = delay;
this.argRule = argRule;
this.argTransfer = argTransfer;
this.session = session;
futureCompletion = new R66Future(true);
}
/**
* @return the TaskType of this AbstractTask
*/
public TaskType getType() {
return type;
}
/**
* This is the only interface to execute an operator.
*/
@Override
public abstract void run();
/**
* @return True if the operation is in success status
*/
public boolean isSuccess() {
futureCompletion.awaitOrInterruptible();
return futureCompletion.isSuccess();
}
/**
* @return the R66Future of completion
*/
public R66Future getFutureCompletion() {
return futureCompletion;
}
/**
* @param arg as the Format string where FIXED items will be
* replaced by
* context values and next using
* argFormat as format second argument; this arg comes from the
* rule
* itself
* @param argFormat as format second argument; this argFormat comes
* from
* the transfer Information itself
*
* @return The string with replaced values from context and second argument
*/
protected String getReplacedValue(String arg, Object[] argFormat) {
final StringBuilder builder = new StringBuilder(arg);
// check NOWAIT and LOCALEXEC
if (arg.contains(NOWAIT)) {
waitForValidation = false;
WaarpStringUtils.replaceAll(builder, NOWAIT, "");
}
if (arg.contains(LOCALEXEC)) {
useLocalExec = true;
WaarpStringUtils.replaceAll(builder, LOCALEXEC, "");
}
File trueFile = null;
if (session.getFile() != null) {
trueFile = session.getFile().getTrueFile();
}
if (trueFile != null) {
WaarpStringUtils
.replaceAll(builder, TRUEFULLPATH, trueFile.getAbsolutePath());
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, R66Dir
.getFinalUniqueFilename(session.getFile()));
WaarpStringUtils
.replaceAll(builder, FILESIZE, Long.toString(trueFile.length()));
} else {
WaarpStringUtils.replaceAll(builder, TRUEFULLPATH, "nofile");
WaarpStringUtils.replaceAll(builder, TRUEFILENAME, "nofile");
WaarpStringUtils.replaceAll(builder, FILESIZE, "0");
}
final DbTaskRunner runner = session.getRunner();
if (runner != null) {
WaarpStringUtils
.replaceAll(builder, ORIGINALFULLPATH, runner.getOriginalFilename());
WaarpStringUtils.replaceAll(builder, ORIGINALFILENAME, R66File
.getBasename(runner.getOriginalFilename()));
WaarpStringUtils.replaceAll(builder, RULE, runner.getRuleId());
}
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
final Date date = new Date();
WaarpStringUtils.replaceAll(builder, DATE, dateFormat.format(date));
dateFormat = new SimpleDateFormat("HHmmss");
WaarpStringUtils.replaceAll(builder, HOUR, dateFormat.format(date));
if (session.getAuth() != null) {
WaarpStringUtils
.replaceAll(builder, REMOTEHOST, session.getAuth().getUser());
try {
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration
.getHostId(session.getAuth().isSsl()));
} catch (final OpenR66ProtocolNoSslException e) {
// replace by standard name
WaarpStringUtils.replaceAll(builder, LOCALHOST,
Configuration.configuration.getHostId());
}
}
if (session.getRemoteAddress() != null) {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR,
session.getRemoteAddress().toString());
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR,
session.getLocalAddress().toString());
} else {
WaarpStringUtils.replaceAll(builder, REMOTEHOSTADDR, "unknown");
WaarpStringUtils.replaceAll(builder, LOCALHOSTADDR, "unknown");
}
if (runner != null) {
WaarpStringUtils.replaceAll(builder, TRANSFERID,
Long.toString(runner.getSpecialId()));
final String requester = runner.getRequester();
WaarpStringUtils.replaceAll(builder, REQUESTERHOST, requester);
final String requested = runner.getRequested();
WaarpStringUtils.replaceAll(builder, REQUESTEDHOST, requested);
WaarpStringUtils.replaceAll(builder, FULLTRANSFERID,
runner.getSpecialId() + "_" + requester +
'_' + requested);
WaarpStringUtils.replaceAll(builder, RANKTRANSFER,
Integer.toString(runner.getRank()));
}
WaarpStringUtils.replaceAll(builder, BLOCKSIZE,
Integer.toString(session.getBlockSize()));
R66Dir dir = new R66Dir(session);
if (runner != null) {
if (runner.isRecvThrough() || runner.isSendThrough()) {
try {
dir.changeDirectoryNotChecked(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectoryNotChecked(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
} else {
try {
dir.changeDirectory(runner.getRule().getRecvPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getSendPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getWorkPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(runner.getRule().getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
} else {
try {
dir.changeDirectory(Configuration.configuration.getInPath());
WaarpStringUtils.replaceAll(builder, INPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getOutPath());
WaarpStringUtils.replaceAll(builder, OUTPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getWorkingPath());
WaarpStringUtils.replaceAll(builder, WORKPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
dir = new R66Dir(session);
try {
dir.changeDirectory(Configuration.configuration.getArchivePath());
WaarpStringUtils.replaceAll(builder, ARCHPATH, dir.getFullPath());
} catch (final CommandAbstractException ignored) {
// nothing
}
}
WaarpStringUtils.replaceAll(builder, HOMEPATH,
Configuration.configuration.getBaseDirectory());
if (session.getLocalChannelReference() == null) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
} else {
try {
WaarpStringUtils.replaceAll(builder, ERRORMSG,
session.getLocalChannelReference()
.getErrorMessage());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORMSG, "NoError");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORCODE,
session.getLocalChannelReference()
.getCurrentCode().getCode());
} catch (final NullPointerException e) {
WaarpStringUtils.replaceAll(builder, ERRORCODE, "-");
}
try {
WaarpStringUtils.replaceAll(builder, ERRORSTRCODE,
session.getLocalChannelReference()
.getCurrentCode().name());
} catch (final NullPointerException e) {
WaarpStringUtils
.replaceAll(builder, ERRORSTRCODE, ErrorCode.Unknown.name());
}
}
// finalname
if (argFormat != null && argFormat.length > 0) {
try {
return String.format(builder.toString(), argFormat);
} catch (final Exception e) {
// ignored error since bad argument in static rule info
logger.error("Bad format in Rule: {" + builder + "} " + e.getMessage());
}
}
return builder.toString();
}
}
| False |
1,426 | 128601_0 | public class main{
public static void main(String[] args) {
String halo;
main hewan = new main();
System.out.println(simpel());
hewan.kucing();
halo = "ciko";
hewan.anjing(halo);
}
//method dengan void
//itu maksudnya sebuah method yang bernilai hampa
//dalam pengembaliannya tidak betuh return
void kucing(){
String nama, makanan;
nama = "cerberus";
makanan = "whiskas";
System.out.println("Nama kucing saya "+nama);
System.out.println("Makanan kucing saya adalah "+makanan);
}
void anjing(String name){
System.out.println("Nama anjing saya adalah "+name);
}
//method biasa dengan return
static float simpel(){
return 10.0f;
}
} | RaenaldP/New-Java | Void method/main.java | 271 | //method dengan void | line_comment | nl | public class main{
public static void main(String[] args) {
String halo;
main hewan = new main();
System.out.println(simpel());
hewan.kucing();
halo = "ciko";
hewan.anjing(halo);
}
//method dengan<SUF>
//itu maksudnya sebuah method yang bernilai hampa
//dalam pengembaliannya tidak betuh return
void kucing(){
String nama, makanan;
nama = "cerberus";
makanan = "whiskas";
System.out.println("Nama kucing saya "+nama);
System.out.println("Makanan kucing saya adalah "+makanan);
}
void anjing(String name){
System.out.println("Nama anjing saya adalah "+name);
}
//method biasa dengan return
static float simpel(){
return 10.0f;
}
} | False |
3,485 | 179629_6 | /*
* Copyright (c) 2018 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.filedownloader.util;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.liulishuo.filedownloader.DownloadTaskAdapter;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.Util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The utils for FileDownloader.
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public class FileDownloadUtils {
private static String defaultSaveRootPath;
private static final String TAG = "FileDownloadUtils";
private static final String FILEDOWNLOADER_PREFIX = "FileDownloader";
// note on https://tools.ietf.org/html/rfc5987
private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\*\\s*=\\s*\"*([^\"]*)'\\S*'([^\"]*)\"*");
// note on http://www.ietf.org/rfc/rfc1806.txt
private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\s*=\\s*\"*([^\"\\n]*)\"*");
public static String getDefaultSaveRootPath() {
if (!TextUtils.isEmpty(defaultSaveRootPath)) {
return defaultSaveRootPath;
}
if (FileDownloadHelper.getAppContext().getExternalCacheDir() == null) {
return Environment.getDownloadCacheDirectory().getAbsolutePath();
} else {
//noinspection ConstantConditions
return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();
}
}
/**
* The path is used as the default directory in the case of the task without set path.
*
* @param path default root path for save download file.
* @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)
*/
public static void setDefaultSaveRootPath(final String path) {
defaultSaveRootPath = path;
}
public static String getDefaultSaveFilePath(final String url) {
return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));
}
public static String generateFileName(final String url) {
return md5(url);
}
public static String generateFilePath(String directory, String filename) {
if (filename == null) {
throw new IllegalStateException("can't generate real path, the file name is null");
}
if (directory == null) {
throw new IllegalStateException("can't generate real path, the directory is null");
}
return String.format("%s%s%s", directory, File.separator, filename);
}
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append(0);
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
@Nullable
public static DownloadTaskAdapter findDownloadTaskAdapter(DownloadTask downloadTask) {
if (downloadTask == null) {
Util.w(TAG, "download task is null when find DownloadTaskAdapter");
return null;
}
final Object o = downloadTask.getTag(DownloadTaskAdapter.KEY_TASK_ADAPTER);
if (o == null) {
Util.w(TAG, "no tag with DownloadTaskAdapter.KEY_TASK_ADAPTER");
return null;
}
if (o instanceof DownloadTaskAdapter) {
return (DownloadTaskAdapter) o;
}
Util.w(TAG, "download task's tag is not DownloadTaskAdapter");
return null;
}
public static byte convertDownloadStatus(final StatusUtil.Status status) {
switch (status) {
case COMPLETED:
return FileDownloadStatus.completed;
case IDLE:
return FileDownloadStatus.paused;
case PENDING:
return FileDownloadStatus.pending;
case RUNNING:
return FileDownloadStatus.progress;
default:
return FileDownloadStatus.INVALID_STATUS;
}
}
/**
* Temp file pattern is deprecated in OkDownload.
*/
@Deprecated
public static String getTempPath(final String targetPath) {
return String.format(Locale.ENGLISH, "%s.temp", targetPath);
}
@Deprecated
public static String getThreadPoolName(String name) {
return FILEDOWNLOADER_PREFIX + "-" + name;
}
@Deprecated
public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static int getMinProgressStep() {
return 0;
}
@Deprecated
public static long getMinProgressTime() {
return 0;
}
@Deprecated
public static boolean isFilenameValid(String filename) {
return true;
}
@Deprecated
public static int generateId(final String url, final String path) {
return new DownloadTask.Builder(url, new File(path)).build().getId();
}
@Deprecated
public static int generateId(final String url, final String path,
final boolean pathAsDirectory) {
if (pathAsDirectory) {
return new DownloadTask.Builder(url, path, null).build().getId();
}
return generateId(url, path);
}
public static String getStack() {
return getStack(true);
}
public static String getStack(final boolean printLine) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
return getStack(stackTrace, printLine);
}
public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {
if ((stackTrace == null) || (stackTrace.length < 4)) {
return "";
}
StringBuilder t = new StringBuilder();
for (int i = 3; i < stackTrace.length; i++) {
if (!stackTrace[i].getClassName().contains("com.liulishuo.filedownloader")) {
continue;
}
t.append('[');
t.append(stackTrace[i].getClassName()
.substring("com.liulishuo.filedownloader".length()));
t.append(':');
t.append(stackTrace[i].getMethodName());
if (printLine) {
t.append('(').append(stackTrace[i].getLineNumber()).append(")]");
} else {
t.append(']');
}
}
return t.toString();
}
@Deprecated
public static boolean isDownloaderProcess(final Context context) {
return false;
}
public static String[] convertHeaderString(final String nameAndValuesString) {
final String[] lineString = nameAndValuesString.split("\n");
final String[] namesAndValues = new String[lineString.length * 2];
for (int i = 0; i < lineString.length; i++) {
final String[] nameAndValue = lineString[i].split(": ");
/**
* @see Headers#toString()
* @see Headers#name(int)
* @see Headers#value(int)
*/
namesAndValues[i * 2] = nameAndValue[0];
namesAndValues[i * 2 + 1] = nameAndValue[1];
}
return namesAndValues;
}
public static long getFreeSpaceBytes(final String path) {
long freeSpaceBytes;
final StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
freeSpaceBytes = statFs.getAvailableBytes();
} else {
//noinspection deprecation
freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
return freeSpaceBytes;
}
public static String formatString(final String msg, Object... args) {
return String.format(Locale.ENGLISH, msg, args);
}
@Deprecated
public static long parseContentRangeFoInstanceLength(String contentRange) {
return -1;
}
/**
* The same to com.android.providers.downloads.Helpers#parseContentDisposition.
* </p>
* Parse the Content-Disposition HTTP Header. The format of the header
* is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
* This header provides a filename for content that is going to be
* downloaded to the file system. We only support the attachment type.
*/
public static String parseContentDisposition(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
try {
Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
String charset = m.group(1);
String encodeFileName = m.group(2);
return URLDecoder.decode(encodeFileName, charset);
}
m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
return m.group(1);
}
} catch (IllegalStateException | UnsupportedEncodingException ignore) {
// This function is defined as returning null when it can't parse the header
}
return null;
}
/**
* @param path If {@code pathAsDirectory} is true, the {@code path} would be the
* absolute directory to settle down the file;
* If {@code pathAsDirectory} is false, the {@code path} would be the
* absolute file path.
* @param pathAsDirectory whether the {@code path} is a directory.
* @param filename the file's name.
* @return the absolute path of the file. If can't find by params, will return {@code null}.
*/
public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {
if (path == null) {
return null;
}
if (pathAsDirectory) {
if (filename == null) {
return null;
}
return FileDownloadUtils.generateFilePath(path, filename);
} else {
return path;
}
}
/**
* The same to {@link File#getParent()}, for non-creating a file object.
*
* @return this file's parent pathname or {@code null}.
*/
public static String getParent(final String path) {
int length = path.length(), firstInPath = 0;
if (File.separatorChar == '\\' && length > 2 && path.charAt(1) == ':') {
firstInPath = 2;
}
int index = path.lastIndexOf(File.separatorChar);
if (index == -1 && firstInPath > 0) {
index = 2;
}
if (index == -1 || path.charAt(length - 1) == File.separatorChar) {
return null;
}
if (path.indexOf(File.separatorChar) == index
&& path.charAt(firstInPath) == File.separatorChar) {
return path.substring(0, index + 1);
}
return path.substring(0, index);
}
@Deprecated
public static boolean isNetworkNotOnWifiType() {
return false;
}
public static boolean checkPermission(String permission) {
final int perm = FileDownloadHelper.getAppContext()
.checkCallingOrSelfPermission(permission);
return perm == PackageManager.PERMISSION_GRANTED;
}
public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {
deleteTempFile(tempFilePath);
deleteTargetFile(targetFilepath);
}
public static void deleteTempFile(String tempFilePath) {
if (tempFilePath != null) {
final File tempFile = new File(tempFilePath);
if (tempFile.exists()) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
}
public static void deleteTargetFile(String targetFilePath) {
if (targetFilePath != null) {
final File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
//noinspection ResultOfMethodCallIgnored
targetFile.delete();
}
}
}
} | lingochamp/okdownload | okdownload-filedownloader/src/main/java/com/liulishuo/filedownloader/util/FileDownloadUtils.java | 3,798 | /**
* @see Headers#toString()
* @see Headers#name(int)
* @see Headers#value(int)
*/ | block_comment | nl | /*
* Copyright (c) 2018 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.filedownloader.util;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import com.liulishuo.filedownloader.DownloadTaskAdapter;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.core.Util;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The utils for FileDownloader.
*/
@SuppressWarnings({"SameParameterValue", "WeakerAccess"})
public class FileDownloadUtils {
private static String defaultSaveRootPath;
private static final String TAG = "FileDownloadUtils";
private static final String FILEDOWNLOADER_PREFIX = "FileDownloader";
// note on https://tools.ietf.org/html/rfc5987
private static final Pattern CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\*\\s*=\\s*\"*([^\"]*)'\\S*'([^\"]*)\"*");
// note on http://www.ietf.org/rfc/rfc1806.txt
private static final Pattern CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN =
Pattern.compile("attachment;\\s*filename\\s*=\\s*\"*([^\"\\n]*)\"*");
public static String getDefaultSaveRootPath() {
if (!TextUtils.isEmpty(defaultSaveRootPath)) {
return defaultSaveRootPath;
}
if (FileDownloadHelper.getAppContext().getExternalCacheDir() == null) {
return Environment.getDownloadCacheDirectory().getAbsolutePath();
} else {
//noinspection ConstantConditions
return FileDownloadHelper.getAppContext().getExternalCacheDir().getAbsolutePath();
}
}
/**
* The path is used as the default directory in the case of the task without set path.
*
* @param path default root path for save download file.
* @see com.liulishuo.filedownloader.BaseDownloadTask#setPath(String, boolean)
*/
public static void setDefaultSaveRootPath(final String path) {
defaultSaveRootPath = path;
}
public static String getDefaultSaveFilePath(final String url) {
return generateFilePath(getDefaultSaveRootPath(), generateFileName(url));
}
public static String generateFileName(final String url) {
return md5(url);
}
public static String generateFilePath(String directory, String filename) {
if (filename == null) {
throw new IllegalStateException("can't generate real path, the file name is null");
}
if (directory == null) {
throw new IllegalStateException("can't generate real path, the directory is null");
}
return String.format("%s%s%s", directory, File.separator, filename);
}
public static String md5(String string) {
byte[] hash;
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Huh, MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Huh, UTF-8 should be supported?", e);
}
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append(0);
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
}
@Nullable
public static DownloadTaskAdapter findDownloadTaskAdapter(DownloadTask downloadTask) {
if (downloadTask == null) {
Util.w(TAG, "download task is null when find DownloadTaskAdapter");
return null;
}
final Object o = downloadTask.getTag(DownloadTaskAdapter.KEY_TASK_ADAPTER);
if (o == null) {
Util.w(TAG, "no tag with DownloadTaskAdapter.KEY_TASK_ADAPTER");
return null;
}
if (o instanceof DownloadTaskAdapter) {
return (DownloadTaskAdapter) o;
}
Util.w(TAG, "download task's tag is not DownloadTaskAdapter");
return null;
}
public static byte convertDownloadStatus(final StatusUtil.Status status) {
switch (status) {
case COMPLETED:
return FileDownloadStatus.completed;
case IDLE:
return FileDownloadStatus.paused;
case PENDING:
return FileDownloadStatus.pending;
case RUNNING:
return FileDownloadStatus.progress;
default:
return FileDownloadStatus.INVALID_STATUS;
}
}
/**
* Temp file pattern is deprecated in OkDownload.
*/
@Deprecated
public static String getTempPath(final String targetPath) {
return String.format(Locale.ENGLISH, "%s.temp", targetPath);
}
@Deprecated
public static String getThreadPoolName(String name) {
return FILEDOWNLOADER_PREFIX + "-" + name;
}
@Deprecated
public static void setMinProgressStep(int minProgressStep) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static void setMinProgressTime(long minProgressTime) throws IllegalAccessException {
// do nothing
}
@Deprecated
public static int getMinProgressStep() {
return 0;
}
@Deprecated
public static long getMinProgressTime() {
return 0;
}
@Deprecated
public static boolean isFilenameValid(String filename) {
return true;
}
@Deprecated
public static int generateId(final String url, final String path) {
return new DownloadTask.Builder(url, new File(path)).build().getId();
}
@Deprecated
public static int generateId(final String url, final String path,
final boolean pathAsDirectory) {
if (pathAsDirectory) {
return new DownloadTask.Builder(url, path, null).build().getId();
}
return generateId(url, path);
}
public static String getStack() {
return getStack(true);
}
public static String getStack(final boolean printLine) {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
return getStack(stackTrace, printLine);
}
public static String getStack(final StackTraceElement[] stackTrace, final boolean printLine) {
if ((stackTrace == null) || (stackTrace.length < 4)) {
return "";
}
StringBuilder t = new StringBuilder();
for (int i = 3; i < stackTrace.length; i++) {
if (!stackTrace[i].getClassName().contains("com.liulishuo.filedownloader")) {
continue;
}
t.append('[');
t.append(stackTrace[i].getClassName()
.substring("com.liulishuo.filedownloader".length()));
t.append(':');
t.append(stackTrace[i].getMethodName());
if (printLine) {
t.append('(').append(stackTrace[i].getLineNumber()).append(")]");
} else {
t.append(']');
}
}
return t.toString();
}
@Deprecated
public static boolean isDownloaderProcess(final Context context) {
return false;
}
public static String[] convertHeaderString(final String nameAndValuesString) {
final String[] lineString = nameAndValuesString.split("\n");
final String[] namesAndValues = new String[lineString.length * 2];
for (int i = 0; i < lineString.length; i++) {
final String[] nameAndValue = lineString[i].split(": ");
/**
* @see Headers#toString()
<SUF>*/
namesAndValues[i * 2] = nameAndValue[0];
namesAndValues[i * 2 + 1] = nameAndValue[1];
}
return namesAndValues;
}
public static long getFreeSpaceBytes(final String path) {
long freeSpaceBytes;
final StatFs statFs = new StatFs(path);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
freeSpaceBytes = statFs.getAvailableBytes();
} else {
//noinspection deprecation
freeSpaceBytes = statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
return freeSpaceBytes;
}
public static String formatString(final String msg, Object... args) {
return String.format(Locale.ENGLISH, msg, args);
}
@Deprecated
public static long parseContentRangeFoInstanceLength(String contentRange) {
return -1;
}
/**
* The same to com.android.providers.downloads.Helpers#parseContentDisposition.
* </p>
* Parse the Content-Disposition HTTP Header. The format of the header
* is defined here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html
* This header provides a filename for content that is going to be
* downloaded to the file system. We only support the attachment type.
*/
public static String parseContentDisposition(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
try {
Matcher m = CONTENT_DISPOSITION_WITH_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
String charset = m.group(1);
String encodeFileName = m.group(2);
return URLDecoder.decode(encodeFileName, charset);
}
m = CONTENT_DISPOSITION_WITHOUT_ASTERISK_PATTERN.matcher(contentDisposition);
if (m.find()) {
return m.group(1);
}
} catch (IllegalStateException | UnsupportedEncodingException ignore) {
// This function is defined as returning null when it can't parse the header
}
return null;
}
/**
* @param path If {@code pathAsDirectory} is true, the {@code path} would be the
* absolute directory to settle down the file;
* If {@code pathAsDirectory} is false, the {@code path} would be the
* absolute file path.
* @param pathAsDirectory whether the {@code path} is a directory.
* @param filename the file's name.
* @return the absolute path of the file. If can't find by params, will return {@code null}.
*/
public static String getTargetFilePath(String path, boolean pathAsDirectory, String filename) {
if (path == null) {
return null;
}
if (pathAsDirectory) {
if (filename == null) {
return null;
}
return FileDownloadUtils.generateFilePath(path, filename);
} else {
return path;
}
}
/**
* The same to {@link File#getParent()}, for non-creating a file object.
*
* @return this file's parent pathname or {@code null}.
*/
public static String getParent(final String path) {
int length = path.length(), firstInPath = 0;
if (File.separatorChar == '\\' && length > 2 && path.charAt(1) == ':') {
firstInPath = 2;
}
int index = path.lastIndexOf(File.separatorChar);
if (index == -1 && firstInPath > 0) {
index = 2;
}
if (index == -1 || path.charAt(length - 1) == File.separatorChar) {
return null;
}
if (path.indexOf(File.separatorChar) == index
&& path.charAt(firstInPath) == File.separatorChar) {
return path.substring(0, index + 1);
}
return path.substring(0, index);
}
@Deprecated
public static boolean isNetworkNotOnWifiType() {
return false;
}
public static boolean checkPermission(String permission) {
final int perm = FileDownloadHelper.getAppContext()
.checkCallingOrSelfPermission(permission);
return perm == PackageManager.PERMISSION_GRANTED;
}
public static void deleteTaskFiles(String targetFilepath, String tempFilePath) {
deleteTempFile(tempFilePath);
deleteTargetFile(targetFilepath);
}
public static void deleteTempFile(String tempFilePath) {
if (tempFilePath != null) {
final File tempFile = new File(tempFilePath);
if (tempFile.exists()) {
//noinspection ResultOfMethodCallIgnored
tempFile.delete();
}
}
}
public static void deleteTargetFile(String targetFilePath) {
if (targetFilePath != null) {
final File targetFile = new File(targetFilePath);
if (targetFile.exists()) {
//noinspection ResultOfMethodCallIgnored
targetFile.delete();
}
}
}
} | False |
3,535 | 13182_16 | package mage.game;
import mage.MageItem;
import mage.MageObject;
import mage.MageObjectReference;
import mage.abilities.Ability;
import mage.abilities.ActivatedAbility;
import mage.abilities.DelayedTriggeredAbility;
import mage.abilities.TriggeredAbility;
import mage.abilities.common.delayed.ReflexiveTriggeredAbility;
import mage.abilities.effects.ContinuousEffect;
import mage.abilities.effects.ContinuousEffects;
import mage.abilities.effects.PreventionEffectData;
import mage.actions.impl.MageAction;
import mage.cards.Card;
import mage.cards.Cards;
import mage.cards.MeldCard;
import mage.cards.decks.Deck;
import mage.choices.Choice;
import mage.constants.*;
import mage.counters.Counters;
import mage.game.combat.Combat;
import mage.game.command.*;
import mage.game.events.GameEvent;
import mage.game.events.Listener;
import mage.game.events.PlayerQueryEvent;
import mage.game.events.TableEvent;
import mage.game.match.MatchType;
import mage.game.mulligan.Mulligan;
import mage.game.permanent.Battlefield;
import mage.game.permanent.Permanent;
import mage.game.permanent.PermanentCard;
import mage.game.stack.Spell;
import mage.game.stack.SpellStack;
import mage.game.turn.Phase;
import mage.game.turn.Step;
import mage.game.turn.Turn;
import mage.players.Player;
import mage.players.PlayerList;
import mage.players.Players;
import mage.util.Copyable;
import mage.util.MessageToClient;
import mage.util.MultiAmountMessage;
import mage.util.functions.CopyApplier;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
public interface Game extends MageItem, Serializable, Copyable<Game> {
MatchType getGameType();
int getNumPlayers();
int getStartingLife();
RangeOfInfluence getRangeOfInfluence();
MultiplayerAttackOption getAttackOption();
//game data methods
void loadCards(Set<Card> cards, UUID ownerId);
Collection<Card> getCards();
MeldCard getMeldCard(UUID meldId);
void addMeldCard(UUID meldId, MeldCard meldCard);
Object getCustomData();
void setCustomData(Object data);
GameOptions getOptions();
/**
* Return object or LKI from battlefield
*
* @param objectId
* @return
*/
MageObject getObject(UUID objectId);
MageObject getObject(Ability source);
MageObject getBaseObject(UUID objectId);
MageObject getEmblem(UUID objectId);
Dungeon getDungeon(UUID objectId);
Dungeon getPlayerDungeon(UUID objectId);
UUID getControllerId(UUID objectId);
UUID getOwnerId(UUID objectId);
UUID getOwnerId(MageObject object);
Spell getSpell(UUID spellId);
Spell getSpellOrLKIStack(UUID spellId);
/**
* Find permanent on the battlefield by id. If you works with cards and want to check it on battlefield then
* use game.getState().getZone() instead. Card's id and permanent's id can be different (example: mdf card
* puts half card to battlefield, not the main card).
*
* @param permanentId
* @return
*/
Permanent getPermanent(UUID permanentId);
/**
* Given the UUID of a permanent, this method returns the permanent. If the current game state does not contain
* a permanent with the given UUID, this method checks the last known information on the battlefield to look for it.
* <br>
* Warning: if the permanent has left the battlefield and then returned, this information might be wrong.
* Prefer usage of a MageObjectReference instead of only the UUID.
*
* @param permanentId - The UUID of the permanent
* @return permanent or permanent's LKI
*/
Permanent getPermanentOrLKIBattlefield(UUID permanentId);
/**
* Given a MageObjectReference to a permanent, this method returns the permanent. If the current game state does not
* contain that permanent, this method checks the last known information on the battlefield.
*
* @param permanentRef - A MOR to the permanent
* @return permanent or permanent's LKI
*/
Permanent getPermanentOrLKIBattlefield(MageObjectReference permanentRef);
Permanent getPermanentEntering(UUID permanentId);
Map<UUID, Permanent> getPermanentsEntering();
Map<Zone, Map<UUID, MageObject>> getLKI();
Map<MageObjectReference, Map<String, Object>> getPermanentCostsTags();
/**
* Take the source's Costs Tags and store it for later access through the MOR.
*/
void storePermanentCostsTags(MageObjectReference permanentMOR, Ability source);
// Result must be checked for null. Possible errors search pattern: (\S*) = game.getCard.+\n(?!.+\1 != null)
Card getCard(UUID cardId);
Optional<Ability> getAbility(UUID abilityId, UUID sourceId);
void setZone(UUID objectId, Zone zone);
void addPlayer(Player player, Deck deck);
// Result must be checked for null. Possible errors search pattern: (\S*) = game.getPlayer.+\n(?!.+\1 != null)
Player getPlayer(UUID playerId);
Player getPlayerOrPlaneswalkerController(UUID playerId);
Players getPlayers();
PlayerList getPlayerList();
default Set<UUID> getOpponents(UUID playerId) {
return getOpponents(playerId, false);
}
/**
* Returns a Set of opponents in range for the given playerId
*
* @param playerId
* @param excludeDeadPlayers Determines if players who have lost are excluded from the list
* @return
*/
default Set<UUID> getOpponents(UUID playerId, boolean excludeDeadPlayers) {
Player player = getPlayer(playerId);
if (player == null) {
return new HashSet<>();
}
return player.getInRange().stream()
.filter(opponentId -> !opponentId.equals(playerId))
.filter(opponentId -> !excludeDeadPlayers || !getPlayer(opponentId).hasLost())
.collect(Collectors.toSet());
}
default boolean isActivePlayer(UUID playerId) {
return getActivePlayerId() != null && getActivePlayerId().equals(playerId);
}
/**
* Checks if the given playerToCheckId is an opponent of player As long as
* no team formats are implemented, this method returns always true for each
* playerId not equal to the player it is checked for. Also if this player
* is out of range. This method can't handle that only players in range are
* processed because it can only return TRUE or FALSE.
*
* @param player
* @param playerToCheckId
* @return
*/
default boolean isOpponent(Player player, UUID playerToCheckId) {
return !player.getId().equals(playerToCheckId);
}
Turn getTurn();
/**
* @return can return null in non started games
*/
PhaseStep getTurnStepType();
/**
* @return can return null in non started games
*/
TurnPhase getTurnPhaseType();
/**
* @return can return null in non started games
*/
Phase getPhase();
Step getStep();
int getTurnNum();
boolean isMainPhase();
boolean canPlaySorcery(UUID playerId);
/**
* Id of the player the current turn it is.
*
* Player can be under control of another player, so search a real GUI's controller by Player->getTurnControlledBy
*
* @return
*/
UUID getActivePlayerId();
UUID getPriorityPlayerId();
boolean checkIfGameIsOver();
boolean hasEnded();
Battlefield getBattlefield();
SpellStack getStack();
Exile getExile();
Combat getCombat();
GameState getState();
String getWinner();
void setDraw(UUID playerId);
boolean isADraw();
ContinuousEffects getContinuousEffects();
GameStates getGameStates();
void loadGameStates(GameStates states);
boolean isSimulation();
/**
* Prepare game for any simulations like AI or effects calc
*/
Game createSimulationForAI();
/**
* Prepare game for any playable calc (available mana/abilities)
*/
Game createSimulationForPlayableCalc();
boolean inCheckPlayableState();
MageObject getLastKnownInformation(UUID objectId, Zone zone);
CardState getLastKnownInformationCard(UUID objectId, Zone zone);
MageObject getLastKnownInformation(UUID objectId, Zone zone, int zoneChangeCounter);
boolean getShortLivingLKI(UUID objectId, Zone zone);
void rememberLKI(UUID objectId, Zone zone, MageObject object);
void resetLKI();
void resetShortLivingLKI();
void setLosingPlayer(Player player);
Player getLosingPlayer();
int getTotalErrorsCount();
//client event methods
void addTableEventListener(Listener<TableEvent> listener);
void addPlayerQueryEventListener(Listener<PlayerQueryEvent> listener);
void fireAskPlayerEvent(UUID playerId, MessageToClient message, Ability source);
void fireAskPlayerEvent(UUID playerId, MessageToClient message, Ability source, Map<String, Serializable> options);
void fireChooseChoiceEvent(UUID playerId, Choice choice);
void fireSelectTargetEvent(UUID playerId, MessageToClient message, Set<UUID> targets, boolean required, Map<String, Serializable> options);
void fireSelectTargetEvent(UUID playerId, MessageToClient message, Cards cards, boolean required, Map<String, Serializable> options);
void fireSelectTargetTriggeredAbilityEvent(UUID playerId, String message, List<TriggeredAbility> abilities);
void fireSelectTargetEvent(UUID playerId, String message, List<Permanent> perms, boolean required);
void fireSelectEvent(UUID playerId, String message);
void fireSelectEvent(UUID playerId, String message, Map<String, Serializable> options);
void firePriorityEvent(UUID playerId);
void firePlayManaEvent(UUID playerId, String message, Map<String, Serializable> options);
void firePlayXManaEvent(UUID playerId, String message);
void fireGetChoiceEvent(UUID playerId, String message, MageObject object, List<? extends ActivatedAbility> choices);
void fireGetModeEvent(UUID playerId, String message, Map<UUID, String> modes);
void fireGetAmountEvent(UUID playerId, String message, int min, int max);
void fireGetMultiAmountEvent(UUID playerId, List<MultiAmountMessage> messages, int min, int max, Map<String, Serializable> options);
void fireChoosePileEvent(UUID playerId, String message, List<? extends Card> pile1, List<? extends Card> pile2);
void fireInformEvent(String message);
void fireStatusEvent(String message, boolean withTime, boolean withTurnInfo);
void fireUpdatePlayersEvent();
void informPlayers(String message);
void informPlayer(Player player, String message);
void debugMessage(String message);
void fireErrorEvent(String message, Exception ex);
void fireGameEndInfo();
//game event methods
void fireEvent(GameEvent event);
/**
* The events are stored until the resolution of the current effect ends and
* fired then all together (e.g. X lands enter the battlefield from
* Scapeshift)
*
* @param event
*/
void addSimultaneousEvent(GameEvent event);
boolean replaceEvent(GameEvent event);
boolean replaceEvent(GameEvent event, Ability targetAbility);
/**
* Creates and fires a damage prevention event
*
* @param damageEvent damage event that will be replaced (instanceof
* check will be done)
* @param source ability that's the source of the prevention effect
* @param game
* @param amountToPrevent max preventable amount
* @return true prevention was successful / false prevention was replaced
*/
PreventionEffectData preventDamage(GameEvent damageEvent, Ability source, Game game, int amountToPrevent);
void start(UUID choosingPlayerId);
void resume();
void pause();
boolean isPaused();
void end();
void cleanUp();
/*
* Gives back the number of cards the player has after the next mulligan
*/
int mulliganDownTo(UUID playerId);
void mulligan(UUID playerId);
void endMulligan(UUID playerId);
// void quit(UUID playerId);
void timerTimeout(UUID playerId);
void idleTimeout(UUID playerId);
void concede(UUID playerId);
void setConcedingPlayer(UUID playerId);
void setManaPaymentMode(UUID playerId, boolean autoPayment);
void setManaPaymentModeRestricted(UUID playerId, boolean autoPaymentRestricted);
void setUseFirstManaAbility(UUID playerId, boolean useFirstManaAbility);
void undo(UUID playerId);
/**
* Empty mana pool with mana burn and life lose checks
*
* @param source must be null for default game events
*/
void emptyManaPools(Ability source);
void addEffect(ContinuousEffect continuousEffect, Ability source);
void addEmblem(Emblem emblem, MageObject sourceObject, Ability source);
void addEmblem(Emblem emblem, MageObject sourceObject, UUID toPlayerId);
boolean addPlane(Plane plane, UUID toPlayerId);
void addCommander(Commander commander);
Dungeon addDungeon(Dungeon dungeon, UUID playerId);
void ventureIntoDungeon(UUID playerId, boolean undercity);
void temptWithTheRing(UUID playerId);
/**
* Tells whether the current game has day or night, defaults to false
*/
boolean hasDayNight();
/**
* Sets game to day or night, sets hasDayNight to true
*
* @param daytime day is true, night is false
*/
void setDaytime(boolean daytime);
/**
* Returns true if hasDayNight is true and parameter matches current day/night value
* Returns false if hasDayNight is false
*
* @param daytime day is true, night is false
*/
boolean checkDayNight(boolean daytime);
/**
* Adds a permanent to the battlefield
*
* @param permanent
* @param createOrder upcounting number from state about the create order of
* all permanents. Can equal for multiple permanents, if
* they go to battlefield at the same time. If the value
* is set to 0, a next number will be set automatically.
*/
void addPermanent(Permanent permanent, int createOrder);
// priority method
void sendPlayerAction(PlayerAction playerAction, UUID playerId, Object data);
/**
* This version supports copying of copies of any depth.
*
* @param copyFromPermanent
* @param copyToPermanentId
* @param source
* @param applier
* @return
*/
Permanent copyPermanent(Permanent copyFromPermanent, UUID copyToPermanentId, Ability source, CopyApplier applier);
Permanent copyPermanent(Duration duration, Permanent copyFromPermanent, UUID copyToPermanentId, Ability source, CopyApplier applier);
Card copyCard(Card cardToCopy, Ability source, UUID newController);
void addTriggeredAbility(TriggeredAbility ability, GameEvent triggeringEvent);
UUID addDelayedTriggeredAbility(DelayedTriggeredAbility delayedAbility, Ability source);
UUID fireReflexiveTriggeredAbility(ReflexiveTriggeredAbility reflexiveAbility, Ability source);
/**
* Inner game engine call to reset game objects to actual versions
* (reset all objects and apply all effects due layer system)
* <p>
* Warning, if you need to process object moves in the middle of the effect/ability
* then call game.getState().processAction(game) instead
*/
void applyEffects();
@Deprecated // TODO: must research usage and remove it from all non engine code (example: Bestow ability, ProcessActions must be used instead)
boolean checkStateAndTriggered();
void playPriority(UUID activePlayerId, boolean resuming);
void resetControlAfterSpellResolve(UUID topId);
boolean endTurn(Ability source);
int doAction(Ability source, MageAction action);
//game transaction methods
void saveState(boolean bookmark);
/**
* Save current game state and return bookmark to it
*
* @return
*/
int bookmarkState();
GameState restoreState(int bookmark, String context);
/**
* Remove selected bookmark and all newer bookmarks and game states
* Part of restore/rollback lifecycle
*
* @param bookmark
*/
void removeBookmark(int bookmark);
/**
* TODO: remove logic changed, must research each usage of removeBookmark and replace it with new code
* @param bookmark
*/
void removeBookmark_v2(int bookmark);
int getSavedStateSize();
boolean isSaveGame();
void setSaveGame(boolean saveGame);
// game options
void setGameOptions(GameOptions options);
// game times
Date getStartTime();
Date getEndTime();
// game cheats (for tests only)
void cheat(UUID ownerId, Map<Zone, String> commands);
void cheat(UUID ownerId, List<Card> library, List<Card> hand, List<PutToBattlefieldInfo> battlefield, List<Card> graveyard, List<Card> command, List<Card> exiled);
// controlling the behaviour of replacement effects while permanents entering the battlefield
void setScopeRelevant(boolean scopeRelevant);
boolean getScopeRelevant();
// players' timers
void initTimer(UUID playerId);
void resumeTimer(UUID playerId);
void pauseTimer(UUID playerId);
int getPriorityTime();
void setPriorityTime(int priorityTime);
int getBufferTime();
void setBufferTime(int bufferTime);
UUID getStartingPlayerId();
void setStartingPlayerId(UUID startingPlayerId);
void saveRollBackGameState();
boolean canRollbackTurns(int turnsToRollback);
void rollbackTurns(int turnsToRollback);
boolean executingRollback();
/**
* Add counters to permanent before ETB. Use it before put real permanent to battlefield.
*/
void setEnterWithCounters(UUID sourceId, Counters counters);
Counters getEnterWithCounters(UUID sourceId);
/**
* Get the UUID of the current player who is the Monarch, or null if nobody has it.
*
* @return UUID of the Monarch (null if nobody has it).
*/
UUID getMonarchId();
void setMonarchId(Ability source, UUID monarchId);
/**
* Get the UUID of the current player who has the initiative, or null if nobody has it.
*
* @return UUID of the player who currently has the Initiative (null if nobody has it).
*/
UUID getInitiativeId();
/**
* Function to call for a player to take the initiative.
*
* @param source The ability granting initiative.
* @param initiativeId UUID of the player taking the initiative
*/
void takeInitiative(Ability source, UUID initiativeId);
int damagePlayerOrPermanent(UUID playerOrPermanent, int damage, UUID attackerId, Ability source, Game game, boolean combatDamage, boolean preventable);
int damagePlayerOrPermanent(UUID playerOrPermanent, int damage, UUID attackerId, Ability source, Game game, boolean combatDamage, boolean preventable, List<UUID> appliedEffects);
Mulligan getMulligan();
Set<UUID> getCommandersIds(Player player, CommanderCardType commanderCardType, boolean returnAllCardParts);
/**
* Return not played commander cards from command zone
* Read comments for CommanderCardType for more info on commanderCardType usage
*
* @param player
* @return
*/
default Set<Card> getCommanderCardsFromCommandZone(Player player, CommanderCardType commanderCardType) {
// commanders in command zone aren't cards so you must call getCard instead getObject
return getCommandersIds(player, commanderCardType, false).stream()
.map(this::getCard)
.filter(Objects::nonNull)
.filter(card -> Zone.COMMAND.equals(this.getState().getZone(card.getId())))
.collect(Collectors.toSet());
}
/**
* Return commander cards from any zones (main card from command and permanent card from battlefield)
* Read comments for CommanderCardType for more info on commanderCardType usage
*
* @param player
* @param commanderCardType commander or signature spell
* @return
*/
default Set<Card> getCommanderCardsFromAnyZones(Player player, CommanderCardType commanderCardType, Zone... searchZones) {
Set<Zone> needZones = Arrays.stream(searchZones).collect(Collectors.toSet());
if (needZones.isEmpty()) {
throw new IllegalArgumentException("Empty zones list in searching commanders");
}
Set<UUID> needCommandersIds = this.getCommandersIds(player, commanderCardType, true);
Set<Card> needCommandersCards = needCommandersIds.stream()
.map(this::getCard)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<Card> res = new HashSet<>();
// hand
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.HAND)) {
needCommandersCards.stream()
.filter(card -> Zone.HAND.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// graveyard
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.GRAVEYARD)) {
needCommandersCards.stream()
.filter(card -> Zone.GRAVEYARD.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// library
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.LIBRARY)) {
needCommandersCards.stream()
.filter(card -> Zone.LIBRARY.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// battlefield (need permanent card)
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.BATTLEFIELD)) {
needCommandersIds.stream()
.map(this::getPermanent)
.filter(Objects::nonNull)
.forEach(res::add);
}
// stack
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.STACK)) {
needCommandersCards.stream()
.filter(card -> Zone.STACK.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// exiled
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.EXILED)) {
needCommandersCards.stream()
.filter(card -> Zone.EXILED.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// command
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.COMMAND)) {
res.addAll(getCommanderCardsFromCommandZone(player, commanderCardType));
}
// outside must be ignored (example: second side of MDFC commander after cast)
if (needZones.contains(Zone.OUTSIDE)) {
throw new IllegalArgumentException("Outside zone doesn't supported in searching commanders");
}
return res;
}
/**
* Finds is it a commander card/object (use it in conditional and other things)
*
* @param player
* @param object
* @return
*/
default boolean isCommanderObject(Player player, MageObject object) {
UUID idToCheck = null;
if (object instanceof Spell) {
idToCheck = ((Spell) object).getCard().getId();
}
if (object instanceof CommandObject) {
idToCheck = object.getId();
}
if (object instanceof Card) {
idToCheck = ((Card) object).getMainCard().getId();
}
return idToCheck != null && this.getCommandersIds(player, CommanderCardType.COMMANDER_OR_OATHBREAKER, false).contains(idToCheck);
}
void setGameStopped(boolean gameStopped);
boolean isGameStopped();
boolean isTurnOrderReversed();
}
| magefree/mage | Mage/src/main/java/mage/game/Game.java | 6,655 | //client event methods | line_comment | nl | package mage.game;
import mage.MageItem;
import mage.MageObject;
import mage.MageObjectReference;
import mage.abilities.Ability;
import mage.abilities.ActivatedAbility;
import mage.abilities.DelayedTriggeredAbility;
import mage.abilities.TriggeredAbility;
import mage.abilities.common.delayed.ReflexiveTriggeredAbility;
import mage.abilities.effects.ContinuousEffect;
import mage.abilities.effects.ContinuousEffects;
import mage.abilities.effects.PreventionEffectData;
import mage.actions.impl.MageAction;
import mage.cards.Card;
import mage.cards.Cards;
import mage.cards.MeldCard;
import mage.cards.decks.Deck;
import mage.choices.Choice;
import mage.constants.*;
import mage.counters.Counters;
import mage.game.combat.Combat;
import mage.game.command.*;
import mage.game.events.GameEvent;
import mage.game.events.Listener;
import mage.game.events.PlayerQueryEvent;
import mage.game.events.TableEvent;
import mage.game.match.MatchType;
import mage.game.mulligan.Mulligan;
import mage.game.permanent.Battlefield;
import mage.game.permanent.Permanent;
import mage.game.permanent.PermanentCard;
import mage.game.stack.Spell;
import mage.game.stack.SpellStack;
import mage.game.turn.Phase;
import mage.game.turn.Step;
import mage.game.turn.Turn;
import mage.players.Player;
import mage.players.PlayerList;
import mage.players.Players;
import mage.util.Copyable;
import mage.util.MessageToClient;
import mage.util.MultiAmountMessage;
import mage.util.functions.CopyApplier;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
public interface Game extends MageItem, Serializable, Copyable<Game> {
MatchType getGameType();
int getNumPlayers();
int getStartingLife();
RangeOfInfluence getRangeOfInfluence();
MultiplayerAttackOption getAttackOption();
//game data methods
void loadCards(Set<Card> cards, UUID ownerId);
Collection<Card> getCards();
MeldCard getMeldCard(UUID meldId);
void addMeldCard(UUID meldId, MeldCard meldCard);
Object getCustomData();
void setCustomData(Object data);
GameOptions getOptions();
/**
* Return object or LKI from battlefield
*
* @param objectId
* @return
*/
MageObject getObject(UUID objectId);
MageObject getObject(Ability source);
MageObject getBaseObject(UUID objectId);
MageObject getEmblem(UUID objectId);
Dungeon getDungeon(UUID objectId);
Dungeon getPlayerDungeon(UUID objectId);
UUID getControllerId(UUID objectId);
UUID getOwnerId(UUID objectId);
UUID getOwnerId(MageObject object);
Spell getSpell(UUID spellId);
Spell getSpellOrLKIStack(UUID spellId);
/**
* Find permanent on the battlefield by id. If you works with cards and want to check it on battlefield then
* use game.getState().getZone() instead. Card's id and permanent's id can be different (example: mdf card
* puts half card to battlefield, not the main card).
*
* @param permanentId
* @return
*/
Permanent getPermanent(UUID permanentId);
/**
* Given the UUID of a permanent, this method returns the permanent. If the current game state does not contain
* a permanent with the given UUID, this method checks the last known information on the battlefield to look for it.
* <br>
* Warning: if the permanent has left the battlefield and then returned, this information might be wrong.
* Prefer usage of a MageObjectReference instead of only the UUID.
*
* @param permanentId - The UUID of the permanent
* @return permanent or permanent's LKI
*/
Permanent getPermanentOrLKIBattlefield(UUID permanentId);
/**
* Given a MageObjectReference to a permanent, this method returns the permanent. If the current game state does not
* contain that permanent, this method checks the last known information on the battlefield.
*
* @param permanentRef - A MOR to the permanent
* @return permanent or permanent's LKI
*/
Permanent getPermanentOrLKIBattlefield(MageObjectReference permanentRef);
Permanent getPermanentEntering(UUID permanentId);
Map<UUID, Permanent> getPermanentsEntering();
Map<Zone, Map<UUID, MageObject>> getLKI();
Map<MageObjectReference, Map<String, Object>> getPermanentCostsTags();
/**
* Take the source's Costs Tags and store it for later access through the MOR.
*/
void storePermanentCostsTags(MageObjectReference permanentMOR, Ability source);
// Result must be checked for null. Possible errors search pattern: (\S*) = game.getCard.+\n(?!.+\1 != null)
Card getCard(UUID cardId);
Optional<Ability> getAbility(UUID abilityId, UUID sourceId);
void setZone(UUID objectId, Zone zone);
void addPlayer(Player player, Deck deck);
// Result must be checked for null. Possible errors search pattern: (\S*) = game.getPlayer.+\n(?!.+\1 != null)
Player getPlayer(UUID playerId);
Player getPlayerOrPlaneswalkerController(UUID playerId);
Players getPlayers();
PlayerList getPlayerList();
default Set<UUID> getOpponents(UUID playerId) {
return getOpponents(playerId, false);
}
/**
* Returns a Set of opponents in range for the given playerId
*
* @param playerId
* @param excludeDeadPlayers Determines if players who have lost are excluded from the list
* @return
*/
default Set<UUID> getOpponents(UUID playerId, boolean excludeDeadPlayers) {
Player player = getPlayer(playerId);
if (player == null) {
return new HashSet<>();
}
return player.getInRange().stream()
.filter(opponentId -> !opponentId.equals(playerId))
.filter(opponentId -> !excludeDeadPlayers || !getPlayer(opponentId).hasLost())
.collect(Collectors.toSet());
}
default boolean isActivePlayer(UUID playerId) {
return getActivePlayerId() != null && getActivePlayerId().equals(playerId);
}
/**
* Checks if the given playerToCheckId is an opponent of player As long as
* no team formats are implemented, this method returns always true for each
* playerId not equal to the player it is checked for. Also if this player
* is out of range. This method can't handle that only players in range are
* processed because it can only return TRUE or FALSE.
*
* @param player
* @param playerToCheckId
* @return
*/
default boolean isOpponent(Player player, UUID playerToCheckId) {
return !player.getId().equals(playerToCheckId);
}
Turn getTurn();
/**
* @return can return null in non started games
*/
PhaseStep getTurnStepType();
/**
* @return can return null in non started games
*/
TurnPhase getTurnPhaseType();
/**
* @return can return null in non started games
*/
Phase getPhase();
Step getStep();
int getTurnNum();
boolean isMainPhase();
boolean canPlaySorcery(UUID playerId);
/**
* Id of the player the current turn it is.
*
* Player can be under control of another player, so search a real GUI's controller by Player->getTurnControlledBy
*
* @return
*/
UUID getActivePlayerId();
UUID getPriorityPlayerId();
boolean checkIfGameIsOver();
boolean hasEnded();
Battlefield getBattlefield();
SpellStack getStack();
Exile getExile();
Combat getCombat();
GameState getState();
String getWinner();
void setDraw(UUID playerId);
boolean isADraw();
ContinuousEffects getContinuousEffects();
GameStates getGameStates();
void loadGameStates(GameStates states);
boolean isSimulation();
/**
* Prepare game for any simulations like AI or effects calc
*/
Game createSimulationForAI();
/**
* Prepare game for any playable calc (available mana/abilities)
*/
Game createSimulationForPlayableCalc();
boolean inCheckPlayableState();
MageObject getLastKnownInformation(UUID objectId, Zone zone);
CardState getLastKnownInformationCard(UUID objectId, Zone zone);
MageObject getLastKnownInformation(UUID objectId, Zone zone, int zoneChangeCounter);
boolean getShortLivingLKI(UUID objectId, Zone zone);
void rememberLKI(UUID objectId, Zone zone, MageObject object);
void resetLKI();
void resetShortLivingLKI();
void setLosingPlayer(Player player);
Player getLosingPlayer();
int getTotalErrorsCount();
//client event<SUF>
void addTableEventListener(Listener<TableEvent> listener);
void addPlayerQueryEventListener(Listener<PlayerQueryEvent> listener);
void fireAskPlayerEvent(UUID playerId, MessageToClient message, Ability source);
void fireAskPlayerEvent(UUID playerId, MessageToClient message, Ability source, Map<String, Serializable> options);
void fireChooseChoiceEvent(UUID playerId, Choice choice);
void fireSelectTargetEvent(UUID playerId, MessageToClient message, Set<UUID> targets, boolean required, Map<String, Serializable> options);
void fireSelectTargetEvent(UUID playerId, MessageToClient message, Cards cards, boolean required, Map<String, Serializable> options);
void fireSelectTargetTriggeredAbilityEvent(UUID playerId, String message, List<TriggeredAbility> abilities);
void fireSelectTargetEvent(UUID playerId, String message, List<Permanent> perms, boolean required);
void fireSelectEvent(UUID playerId, String message);
void fireSelectEvent(UUID playerId, String message, Map<String, Serializable> options);
void firePriorityEvent(UUID playerId);
void firePlayManaEvent(UUID playerId, String message, Map<String, Serializable> options);
void firePlayXManaEvent(UUID playerId, String message);
void fireGetChoiceEvent(UUID playerId, String message, MageObject object, List<? extends ActivatedAbility> choices);
void fireGetModeEvent(UUID playerId, String message, Map<UUID, String> modes);
void fireGetAmountEvent(UUID playerId, String message, int min, int max);
void fireGetMultiAmountEvent(UUID playerId, List<MultiAmountMessage> messages, int min, int max, Map<String, Serializable> options);
void fireChoosePileEvent(UUID playerId, String message, List<? extends Card> pile1, List<? extends Card> pile2);
void fireInformEvent(String message);
void fireStatusEvent(String message, boolean withTime, boolean withTurnInfo);
void fireUpdatePlayersEvent();
void informPlayers(String message);
void informPlayer(Player player, String message);
void debugMessage(String message);
void fireErrorEvent(String message, Exception ex);
void fireGameEndInfo();
//game event methods
void fireEvent(GameEvent event);
/**
* The events are stored until the resolution of the current effect ends and
* fired then all together (e.g. X lands enter the battlefield from
* Scapeshift)
*
* @param event
*/
void addSimultaneousEvent(GameEvent event);
boolean replaceEvent(GameEvent event);
boolean replaceEvent(GameEvent event, Ability targetAbility);
/**
* Creates and fires a damage prevention event
*
* @param damageEvent damage event that will be replaced (instanceof
* check will be done)
* @param source ability that's the source of the prevention effect
* @param game
* @param amountToPrevent max preventable amount
* @return true prevention was successful / false prevention was replaced
*/
PreventionEffectData preventDamage(GameEvent damageEvent, Ability source, Game game, int amountToPrevent);
void start(UUID choosingPlayerId);
void resume();
void pause();
boolean isPaused();
void end();
void cleanUp();
/*
* Gives back the number of cards the player has after the next mulligan
*/
int mulliganDownTo(UUID playerId);
void mulligan(UUID playerId);
void endMulligan(UUID playerId);
// void quit(UUID playerId);
void timerTimeout(UUID playerId);
void idleTimeout(UUID playerId);
void concede(UUID playerId);
void setConcedingPlayer(UUID playerId);
void setManaPaymentMode(UUID playerId, boolean autoPayment);
void setManaPaymentModeRestricted(UUID playerId, boolean autoPaymentRestricted);
void setUseFirstManaAbility(UUID playerId, boolean useFirstManaAbility);
void undo(UUID playerId);
/**
* Empty mana pool with mana burn and life lose checks
*
* @param source must be null for default game events
*/
void emptyManaPools(Ability source);
void addEffect(ContinuousEffect continuousEffect, Ability source);
void addEmblem(Emblem emblem, MageObject sourceObject, Ability source);
void addEmblem(Emblem emblem, MageObject sourceObject, UUID toPlayerId);
boolean addPlane(Plane plane, UUID toPlayerId);
void addCommander(Commander commander);
Dungeon addDungeon(Dungeon dungeon, UUID playerId);
void ventureIntoDungeon(UUID playerId, boolean undercity);
void temptWithTheRing(UUID playerId);
/**
* Tells whether the current game has day or night, defaults to false
*/
boolean hasDayNight();
/**
* Sets game to day or night, sets hasDayNight to true
*
* @param daytime day is true, night is false
*/
void setDaytime(boolean daytime);
/**
* Returns true if hasDayNight is true and parameter matches current day/night value
* Returns false if hasDayNight is false
*
* @param daytime day is true, night is false
*/
boolean checkDayNight(boolean daytime);
/**
* Adds a permanent to the battlefield
*
* @param permanent
* @param createOrder upcounting number from state about the create order of
* all permanents. Can equal for multiple permanents, if
* they go to battlefield at the same time. If the value
* is set to 0, a next number will be set automatically.
*/
void addPermanent(Permanent permanent, int createOrder);
// priority method
void sendPlayerAction(PlayerAction playerAction, UUID playerId, Object data);
/**
* This version supports copying of copies of any depth.
*
* @param copyFromPermanent
* @param copyToPermanentId
* @param source
* @param applier
* @return
*/
Permanent copyPermanent(Permanent copyFromPermanent, UUID copyToPermanentId, Ability source, CopyApplier applier);
Permanent copyPermanent(Duration duration, Permanent copyFromPermanent, UUID copyToPermanentId, Ability source, CopyApplier applier);
Card copyCard(Card cardToCopy, Ability source, UUID newController);
void addTriggeredAbility(TriggeredAbility ability, GameEvent triggeringEvent);
UUID addDelayedTriggeredAbility(DelayedTriggeredAbility delayedAbility, Ability source);
UUID fireReflexiveTriggeredAbility(ReflexiveTriggeredAbility reflexiveAbility, Ability source);
/**
* Inner game engine call to reset game objects to actual versions
* (reset all objects and apply all effects due layer system)
* <p>
* Warning, if you need to process object moves in the middle of the effect/ability
* then call game.getState().processAction(game) instead
*/
void applyEffects();
@Deprecated // TODO: must research usage and remove it from all non engine code (example: Bestow ability, ProcessActions must be used instead)
boolean checkStateAndTriggered();
void playPriority(UUID activePlayerId, boolean resuming);
void resetControlAfterSpellResolve(UUID topId);
boolean endTurn(Ability source);
int doAction(Ability source, MageAction action);
//game transaction methods
void saveState(boolean bookmark);
/**
* Save current game state and return bookmark to it
*
* @return
*/
int bookmarkState();
GameState restoreState(int bookmark, String context);
/**
* Remove selected bookmark and all newer bookmarks and game states
* Part of restore/rollback lifecycle
*
* @param bookmark
*/
void removeBookmark(int bookmark);
/**
* TODO: remove logic changed, must research each usage of removeBookmark and replace it with new code
* @param bookmark
*/
void removeBookmark_v2(int bookmark);
int getSavedStateSize();
boolean isSaveGame();
void setSaveGame(boolean saveGame);
// game options
void setGameOptions(GameOptions options);
// game times
Date getStartTime();
Date getEndTime();
// game cheats (for tests only)
void cheat(UUID ownerId, Map<Zone, String> commands);
void cheat(UUID ownerId, List<Card> library, List<Card> hand, List<PutToBattlefieldInfo> battlefield, List<Card> graveyard, List<Card> command, List<Card> exiled);
// controlling the behaviour of replacement effects while permanents entering the battlefield
void setScopeRelevant(boolean scopeRelevant);
boolean getScopeRelevant();
// players' timers
void initTimer(UUID playerId);
void resumeTimer(UUID playerId);
void pauseTimer(UUID playerId);
int getPriorityTime();
void setPriorityTime(int priorityTime);
int getBufferTime();
void setBufferTime(int bufferTime);
UUID getStartingPlayerId();
void setStartingPlayerId(UUID startingPlayerId);
void saveRollBackGameState();
boolean canRollbackTurns(int turnsToRollback);
void rollbackTurns(int turnsToRollback);
boolean executingRollback();
/**
* Add counters to permanent before ETB. Use it before put real permanent to battlefield.
*/
void setEnterWithCounters(UUID sourceId, Counters counters);
Counters getEnterWithCounters(UUID sourceId);
/**
* Get the UUID of the current player who is the Monarch, or null if nobody has it.
*
* @return UUID of the Monarch (null if nobody has it).
*/
UUID getMonarchId();
void setMonarchId(Ability source, UUID monarchId);
/**
* Get the UUID of the current player who has the initiative, or null if nobody has it.
*
* @return UUID of the player who currently has the Initiative (null if nobody has it).
*/
UUID getInitiativeId();
/**
* Function to call for a player to take the initiative.
*
* @param source The ability granting initiative.
* @param initiativeId UUID of the player taking the initiative
*/
void takeInitiative(Ability source, UUID initiativeId);
int damagePlayerOrPermanent(UUID playerOrPermanent, int damage, UUID attackerId, Ability source, Game game, boolean combatDamage, boolean preventable);
int damagePlayerOrPermanent(UUID playerOrPermanent, int damage, UUID attackerId, Ability source, Game game, boolean combatDamage, boolean preventable, List<UUID> appliedEffects);
Mulligan getMulligan();
Set<UUID> getCommandersIds(Player player, CommanderCardType commanderCardType, boolean returnAllCardParts);
/**
* Return not played commander cards from command zone
* Read comments for CommanderCardType for more info on commanderCardType usage
*
* @param player
* @return
*/
default Set<Card> getCommanderCardsFromCommandZone(Player player, CommanderCardType commanderCardType) {
// commanders in command zone aren't cards so you must call getCard instead getObject
return getCommandersIds(player, commanderCardType, false).stream()
.map(this::getCard)
.filter(Objects::nonNull)
.filter(card -> Zone.COMMAND.equals(this.getState().getZone(card.getId())))
.collect(Collectors.toSet());
}
/**
* Return commander cards from any zones (main card from command and permanent card from battlefield)
* Read comments for CommanderCardType for more info on commanderCardType usage
*
* @param player
* @param commanderCardType commander or signature spell
* @return
*/
default Set<Card> getCommanderCardsFromAnyZones(Player player, CommanderCardType commanderCardType, Zone... searchZones) {
Set<Zone> needZones = Arrays.stream(searchZones).collect(Collectors.toSet());
if (needZones.isEmpty()) {
throw new IllegalArgumentException("Empty zones list in searching commanders");
}
Set<UUID> needCommandersIds = this.getCommandersIds(player, commanderCardType, true);
Set<Card> needCommandersCards = needCommandersIds.stream()
.map(this::getCard)
.filter(Objects::nonNull)
.collect(Collectors.toSet());
Set<Card> res = new HashSet<>();
// hand
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.HAND)) {
needCommandersCards.stream()
.filter(card -> Zone.HAND.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// graveyard
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.GRAVEYARD)) {
needCommandersCards.stream()
.filter(card -> Zone.GRAVEYARD.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// library
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.LIBRARY)) {
needCommandersCards.stream()
.filter(card -> Zone.LIBRARY.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// battlefield (need permanent card)
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.BATTLEFIELD)) {
needCommandersIds.stream()
.map(this::getPermanent)
.filter(Objects::nonNull)
.forEach(res::add);
}
// stack
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.STACK)) {
needCommandersCards.stream()
.filter(card -> Zone.STACK.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// exiled
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.EXILED)) {
needCommandersCards.stream()
.filter(card -> Zone.EXILED.equals(this.getState().getZone(card.getId())))
.forEach(res::add);
}
// command
if (needZones.contains(Zone.ALL) || needZones.contains(Zone.COMMAND)) {
res.addAll(getCommanderCardsFromCommandZone(player, commanderCardType));
}
// outside must be ignored (example: second side of MDFC commander after cast)
if (needZones.contains(Zone.OUTSIDE)) {
throw new IllegalArgumentException("Outside zone doesn't supported in searching commanders");
}
return res;
}
/**
* Finds is it a commander card/object (use it in conditional and other things)
*
* @param player
* @param object
* @return
*/
default boolean isCommanderObject(Player player, MageObject object) {
UUID idToCheck = null;
if (object instanceof Spell) {
idToCheck = ((Spell) object).getCard().getId();
}
if (object instanceof CommandObject) {
idToCheck = object.getId();
}
if (object instanceof Card) {
idToCheck = ((Card) object).getMainCard().getId();
}
return idToCheck != null && this.getCommandersIds(player, CommanderCardType.COMMANDER_OR_OATHBREAKER, false).contains(idToCheck);
}
void setGameStopped(boolean gameStopped);
boolean isGameStopped();
boolean isTurnOrderReversed();
}
| False |
1,477 | 79324_11 | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| RobinHoutevelts/DynwebFramework | src/java/framework/database/Database.java | 1,400 | // MetaData is nodig, daarin zit het aantal kolommen en hoe ze heten_x000D_ | line_comment | nl | package framework.database;_x000D_
_x000D_
import java.lang.reflect.Constructor;_x000D_
import java.sql.Connection;_x000D_
import java.sql.Driver;_x000D_
import java.sql.DriverManager;_x000D_
import java.sql.PreparedStatement;_x000D_
import java.sql.ResultSet;_x000D_
import java.sql.ResultSetMetaData;_x000D_
import java.sql.SQLException;_x000D_
import java.util.ArrayList;_x000D_
import java.util.Enumeration;_x000D_
import java.util.HashMap;_x000D_
_x000D_
public class Database {_x000D_
_x000D_
protected Connection conn;_x000D_
protected String connectionUrl;_x000D_
protected String username;_x000D_
protected String password; // TODO: kijken in hoeverre het haalbaar is het wachtwoord hier weg te laten_x000D_
_x000D_
@SuppressWarnings({ "unchecked", "rawtypes" })_x000D_
public Database(String driver, String connectionUrl, String username, String password)_x000D_
{_x000D_
try {_x000D_
// Kijken of de driver bestaat_x000D_
Class DriverClass = Class.forName(driver);_x000D_
_x000D_
Constructor constructorClass = DriverClass.getConstructor();_x000D_
Driver dbDriver = (Driver) constructorClass.newInstance();_x000D_
DriverManager.registerDriver(dbDriver);_x000D_
_x000D_
} catch (Exception e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
_x000D_
this.connectionUrl = connectionUrl;_x000D_
this.username = username;_x000D_
this.password = password;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Maakt connectie naar de databank_x000D_
* _x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public Connection getConnection() throws SQLException_x000D_
{_x000D_
if(this.conn == null || this.conn.isClosed())_x000D_
this.conn = DriverManager.getConnection(connectionUrl,username,password);_x000D_
_x000D_
return this.conn;_x000D_
}_x000D_
_x000D_
public PreparedStatement prepareStatement(String query) throws SQLException_x000D_
{_x000D_
return conn.prepareStatement(query);_x000D_
}_x000D_
_x000D_
public NamedParamStatement namedParamStatement(String query) throws SQLException_x000D_
{_x000D_
return new NamedParamStatement(getConnection(), query);_x000D_
}_x000D_
_x000D_
/**_x000D_
* Geeft alle rows van een result in een handige ArrayList_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public ArrayList<DatabaseRow> getAllRows(ResultSet res) throws SQLException_x000D_
{_x000D_
ArrayList<DatabaseRow> rows = new ArrayList<DatabaseRow>();_x000D_
_x000D_
// Cursor naar -1 zetten._x000D_
res.beforeFirst();_x000D_
_x000D_
// Kijken of er op index 0 iets zit._x000D_
if(res.next()){_x000D_
// Blijkbaar zijn er rows_x000D_
// Cursor terug naar -1 zetten alle rows aflopen._x000D_
res.beforeFirst();_x000D_
_x000D_
// Pas als we aan de EOL zitten van de resultset stoppen we_x000D_
while(!res.isAfterLast()) {_x000D_
// Row ophalen en toevoegen aan Arraylist_x000D_
DatabaseRow row = this.getRow(res);_x000D_
if(row != null)_x000D_
rows.add(row);_x000D_
}_x000D_
}_x000D_
_x000D_
res.close();_x000D_
_x000D_
return rows;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Haalt de volgende row uit een resultset een geeft dit terug in een Hashmap<Kolomnaam,Object>_x000D_
* _x000D_
* @param res_x000D_
* @return_x000D_
* @throws SQLException_x000D_
*/_x000D_
public DatabaseRow getRow(ResultSet res) throws SQLException_x000D_
{_x000D_
HashMap<String, Object> row = new HashMap<String, Object>();_x000D_
_x000D_
// MetaData is<SUF>
ResultSetMetaData metaData = res.getMetaData();_x000D_
int columnCount = metaData.getColumnCount();_x000D_
_x000D_
ArrayList<String> columns = new ArrayList<String>();_x000D_
_x000D_
// Alle kolommen aflopen en hun naam bijhouden in de Array._x000D_
for (int columnNr=1; columnNr<=columnCount; columnNr++){_x000D_
String columnName = metaData.getColumnName(columnNr);_x000D_
columns.add(columnName);_x000D_
}_x000D_
_x000D_
// Springen naar de volgende row_x000D_
if (res.next()){_x000D_
// Alle kolommen in deze row aflopen_x000D_
for (String columnName:columns) {_x000D_
// De waarde van deze kolom ophalen_x000D_
Object rowData = res.getObject(columnName);_x000D_
// Toevoegen aan de hashmap_x000D_
row.put(columnName,rowData);_x000D_
}_x000D_
}_x000D_
_x000D_
if(row.size() <= 0)_x000D_
return null;_x000D_
_x000D_
return new DatabaseRow(row);_x000D_
}_x000D_
_x000D_
public void closeConnection() {_x000D_
try {_x000D_
conn.close();_x000D_
_x000D_
// This manually deregisters JDBC driver, which prevents Tomcat 7_x000D_
// from complaining about memory leaks wrto this class_x000D_
// http://stackoverflow.com/a/5315467/1306509_x000D_
Enumeration<Driver> drivers = DriverManager.getDrivers();_x000D_
while (drivers.hasMoreElements()) {_x000D_
Driver driver = drivers.nextElement();_x000D_
DriverManager.deregisterDriver(driver);_x000D_
}_x000D_
_x000D_
} catch (SQLException e) {_x000D_
// TODO Exception-handling_x000D_
e.printStackTrace();_x000D_
}_x000D_
}_x000D_
}_x000D_
| True |
2,528 | 6614_13 | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.modality.nlp.generate;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.index.NDIndex;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
/**
* {@code StepGeneration} is a utility class containing the step generation utility functions used
* in autoregressive search.
*/
public final class StepGeneration {
private StepGeneration() {}
/**
* Generate the output token id and selecting indices used in contrastive search.
*
* @param topKIds the topk candidate token ids
* @param logits the logits from the language model
* @param contextHiddenStates the embedding of the past generated token ids
* @param topkHiddenStates the embedding of the topk candidate token ids
* @param offSets the offsets
* @param alpha the repetition penalty
* @return the output token ids and selecting indices
*/
public static NDList constrastiveStepGeneration(
NDArray topKIds,
NDArray logits,
NDArray contextHiddenStates,
NDArray topkHiddenStates,
NDArray offSets,
float alpha) {
/*
topKIds: [batch, topK]
attentionMask: [batch, past_seq]
logits: [batch, vocabSize]
contextHiddenStates: [batch, past_seq, dim]
topkHiddenStates: [batch*topK, seq=1, dim]
attentionMaskSlice: [batch, 2]: (startPosition, endPosition)
*/
long batch = topKIds.getShape().get(0);
long topK = topKIds.getShape().get(1);
long hiddenDim = topkHiddenStates.getShape().getLastDimension();
// [batch*topK, seq=1, dim] -> [batch, topK, dim]
topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim);
// [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq]
topkHiddenStates = topkHiddenStates.normalize(2, 2);
contextHiddenStates = contextHiddenStates.normalize(2, 2);
NDArray cosSimilarity =
topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1));
// Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step
long[] offSetsArray = offSets.toLongArray();
for (int i = 0; i < offSetsArray.length; i++) {
cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1);
}
// [batch, topK, past_seq] -> [batch, topK]
NDArray topkScorePart1 = cosSimilarity.max(new int[] {2});
assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size";
// [batch, logitDim].gather([batch, topK) -> [batch, topK]
NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1);
NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha));
// [batch, topK] => [batch, 1]
NDArray select = topkScore.argMax(1);
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64),
select);
NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1);
return new NDList(outputIds, select);
}
// TODO: add support of Einstein summation:
// a = torch.randn(batch, past_seq, dim)
// b = torch.randn(batch, topK, dim)
// result = torch.einsum('bik,bjk->bij', a, b)
/**
* Generates the output token id for greedy search.
*
* @param logits the logits from the language model
* @return the output token ids
*/
public static NDArray greedyStepGen(NDArray logits) {
// logits: [batch, seq, probDim]
assert logits.getShape().getShape().length == 3 : "unexpected input";
logits = logits.get(":, -1, :");
return logits.argMax(-1).expandDims(1); // [batch, vacDim]
}
/**
* Generates the output token id and selecting indices used in beam search.
*
* @param lastProbs the probabilities of the past prefix sequences
* @param logits the logits
* @param numBatch number of batch
* @param numBeam number of beam
* @return the output token ids and selecting indices
*/
public static NDList beamStepGeneration(
NDArray lastProbs, NDArray logits, long numBatch, long numBeam) {
// [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim]
NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1);
// Argmax over the probs in the prob dimension.
// [batch, beamSource, probDim] -> [batch, beamSource, beamChild]
NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false);
NDArray outputIs = topK.get(1);
NDArray stepProbs = topK.get(0);
// Chain the probability
// [batch, beamSource] -> [batch, beamSource, 1]
lastProbs = lastProbs.reshape(numBatch, numBeam, 1);
// [batch, beamSource, beamChild]
NDArray newProbs = stepProbs.muli(lastProbs);
// Argmax over the (beamSource * beamChild) dimension
topK =
newProbs.reshape(numBatch, numBeam * numBeam)
.topK(Math.toIntExact(numBeam), -1, true, false);
// The select indices act on (beamSource, beamChild) dimension. Decides how the new
// generated tokenIds correspond to the past tokenIds.
// [batch, beamNew].
NDArray select = topK.get(1);
// Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...]
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager()
.arange(0, numBatch, 1, DataType.INT64)
.expandDims(1)
.repeat(1, numBeam),
select);
// [batch, beamNew]
outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2);
// [batch, beamNew]
newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1);
/* During the beam selection process, some source beams are selected several times while
some source beams are not selected even once. The pastOutputs should be reselected to
have the right correspondence to the newInputIds.
*/
// [batch, beamNew]
assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division";
assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]";
// For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in
// beamSource dimension: index2 = index1 / numBeam.
long[] index = select.toLongArray();
for (int i = 0; i < index.length; i++) {
index[i] = Math.floorDiv(index[i], numBeam);
}
NDArray sourceBeamSelected =
logits.getManager().create(index, new Shape(numBatch, numBeam));
return new NDList(outputIs, newProbs, sourceBeamSelected);
}
// TODO: implement pytorch floor_divide.
}
| deepjavalibrary/djl | api/src/main/java/ai/djl/modality/nlp/generate/StepGeneration.java | 2,376 | // result = torch.einsum('bik,bjk->bij', a, b) | line_comment | nl | /*
* Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file 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 ai.djl.modality.nlp.generate;
import ai.djl.ndarray.NDArray;
import ai.djl.ndarray.NDList;
import ai.djl.ndarray.index.NDIndex;
import ai.djl.ndarray.types.DataType;
import ai.djl.ndarray.types.Shape;
/**
* {@code StepGeneration} is a utility class containing the step generation utility functions used
* in autoregressive search.
*/
public final class StepGeneration {
private StepGeneration() {}
/**
* Generate the output token id and selecting indices used in contrastive search.
*
* @param topKIds the topk candidate token ids
* @param logits the logits from the language model
* @param contextHiddenStates the embedding of the past generated token ids
* @param topkHiddenStates the embedding of the topk candidate token ids
* @param offSets the offsets
* @param alpha the repetition penalty
* @return the output token ids and selecting indices
*/
public static NDList constrastiveStepGeneration(
NDArray topKIds,
NDArray logits,
NDArray contextHiddenStates,
NDArray topkHiddenStates,
NDArray offSets,
float alpha) {
/*
topKIds: [batch, topK]
attentionMask: [batch, past_seq]
logits: [batch, vocabSize]
contextHiddenStates: [batch, past_seq, dim]
topkHiddenStates: [batch*topK, seq=1, dim]
attentionMaskSlice: [batch, 2]: (startPosition, endPosition)
*/
long batch = topKIds.getShape().get(0);
long topK = topKIds.getShape().get(1);
long hiddenDim = topkHiddenStates.getShape().getLastDimension();
// [batch*topK, seq=1, dim] -> [batch, topK, dim]
topkHiddenStates = topkHiddenStates.reshape(batch, topK, hiddenDim);
// [batch, topK, dim] * [batch, past_seq, dim] -> [batch, topK, past_seq]
topkHiddenStates = topkHiddenStates.normalize(2, 2);
contextHiddenStates = contextHiddenStates.normalize(2, 2);
NDArray cosSimilarity =
topkHiddenStates.batchMatMul(contextHiddenStates.transpose(0, 2, 1));
// Deactivate entries (batch_idx, :, zero_attention_idx_slice) in max{cosSim} step
long[] offSetsArray = offSets.toLongArray();
for (int i = 0; i < offSetsArray.length; i++) {
cosSimilarity.set(new NDIndex("{}, :, {}:{}", i, 0, offSetsArray[i]), -1);
}
// [batch, topK, past_seq] -> [batch, topK]
NDArray topkScorePart1 = cosSimilarity.max(new int[] {2});
assert topkScorePart1.getShape().getShape().length == 2 : "Wrong output size";
// [batch, logitDim].gather([batch, topK) -> [batch, topK]
NDArray topkScorePart2 = logits.softmax(1).gather(topKIds, 1);
NDArray topkScore = topkScorePart2.muli(1 - alpha).subi(topkScorePart1.muli(alpha));
// [batch, topK] => [batch, 1]
NDArray select = topkScore.argMax(1);
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager().arange(0, topKIds.getShape().get(0), 1, DataType.INT64),
select);
NDArray outputIds = topKIds.get(selectIndex).reshape(-1, 1);
return new NDList(outputIds, select);
}
// TODO: add support of Einstein summation:
// a = torch.randn(batch, past_seq, dim)
// b = torch.randn(batch, topK, dim)
// result =<SUF>
/**
* Generates the output token id for greedy search.
*
* @param logits the logits from the language model
* @return the output token ids
*/
public static NDArray greedyStepGen(NDArray logits) {
// logits: [batch, seq, probDim]
assert logits.getShape().getShape().length == 3 : "unexpected input";
logits = logits.get(":, -1, :");
return logits.argMax(-1).expandDims(1); // [batch, vacDim]
}
/**
* Generates the output token id and selecting indices used in beam search.
*
* @param lastProbs the probabilities of the past prefix sequences
* @param logits the logits
* @param numBatch number of batch
* @param numBeam number of beam
* @return the output token ids and selecting indices
*/
public static NDList beamStepGeneration(
NDArray lastProbs, NDArray logits, long numBatch, long numBeam) {
// [batch * beamSource, seq, probDim] -> [batch, beamSource, probDim]
NDArray allProbs = logits.get(":, -1, :").softmax(1).reshape(numBatch, numBeam, -1);
// Argmax over the probs in the prob dimension.
// [batch, beamSource, probDim] -> [batch, beamSource, beamChild]
NDList topK = allProbs.topK(Math.toIntExact(numBeam), -1, true, false);
NDArray outputIs = topK.get(1);
NDArray stepProbs = topK.get(0);
// Chain the probability
// [batch, beamSource] -> [batch, beamSource, 1]
lastProbs = lastProbs.reshape(numBatch, numBeam, 1);
// [batch, beamSource, beamChild]
NDArray newProbs = stepProbs.muli(lastProbs);
// Argmax over the (beamSource * beamChild) dimension
topK =
newProbs.reshape(numBatch, numBeam * numBeam)
.topK(Math.toIntExact(numBeam), -1, true, false);
// The select indices act on (beamSource, beamChild) dimension. Decides how the new
// generated tokenIds correspond to the past tokenIds.
// [batch, beamNew].
NDArray select = topK.get(1);
// Act on [batch, beam, ...] dimension and the output will be [batch, beam, ...]
NDIndex selectIndex =
new NDIndex(
"{}, {}, ...",
logits.getManager()
.arange(0, numBatch, 1, DataType.INT64)
.expandDims(1)
.repeat(1, numBeam),
select);
// [batch, beamNew]
outputIs = outputIs.reshape(numBatch, numBeam * numBeam).get(selectIndex).expandDims(2);
// [batch, beamNew]
newProbs = newProbs.reshape(numBatch, numBeam * numBeam).get(selectIndex).normalize(1, 1);
/* During the beam selection process, some source beams are selected several times while
some source beams are not selected even once. The pastOutputs should be reselected to
have the right correspondence to the newInputIds.
*/
// [batch, beamNew]
assert select.getDataType() == DataType.INT64 : "Wrong output! Expect integer division";
assert select.getShape().getShape().length == 2 : "Wrong size. Expect [batch, beamNew]";
// For each batch, convert the index1 in beamSource*beamChild dimension to its index2 in
// beamSource dimension: index2 = index1 / numBeam.
long[] index = select.toLongArray();
for (int i = 0; i < index.length; i++) {
index[i] = Math.floorDiv(index[i], numBeam);
}
NDArray sourceBeamSelected =
logits.getManager().create(index, new Shape(numBatch, numBeam));
return new NDList(outputIs, newProbs, sourceBeamSelected);
}
// TODO: implement pytorch floor_divide.
}
| False |
3,484 | 19674_12 | /**
* Copyright (c) 2015 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.qiniuimageloader;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by Jacksgong on 15/8/3.
*
* @Api: http://developer.qiniu.com/docs/v6/api/reference/fop/image/imagemogr2.html
*/
public class QiniuImageLoader<T extends QiniuImageLoader> {
private final static String TAG = "QiniuImageLoader";
private int mode = MODE_FIT_XY;
private int w = 0;
private int h = 0;
private String oriUrl;
private ImageView imageView;
/**
* 限定缩略图的宽最少为<Width>,高最少为<Height>,进行等比缩放,居中裁剪。
* <p/>
* 转后的缩略图通常恰好是 <Width>x<Height> 的大小(有一个边缩放的时候会因为超出矩形框而被裁剪掉多余部分)。
* <p/>
* 如果只指定 w 参数或只指定 h 参数,代表限定为长宽相等的正方图。
* <p/>
* 强制使用给定w与h
*/
private final static int MODE_CENTER_CROP = 1;
/**
* 限定缩略图的宽最多为<Width>,高最多为<Height>,进行等比缩放,不裁剪。
* <p/>
* 如果只指定 w 参数则表示限定宽(长自适应),只指定 h 参数则表示限定长(宽自适应)。
* <p/>
* 如果给定的w或h大于原图,则采用原图
*/
private final static int MODE_FIT_XY = 2;
/**
* 强制需要原图,通常是图片需要动态缩放才需要
*/
private final static int MODE_FORCE_ORIGIN = -1;
public QiniuImageLoader(final Context context, final String oriUrl) {
this.context = context;
this.oriUrl = oriUrl;
}
public QiniuImageLoader(final ImageView imageView, final String oriUrl) {
this.imageView = imageView;
this.oriUrl = oriUrl;
}
/**
* 指定最大宽度 为w
*
* @param w
* @return
*/
public T w(final int w) {
this.w = w;
return (T) this;
}
/**
* 指定最大宽度
*
* @param wResource DimenRes
* @return
*/
public T wR(final int wResource) {
if (getContext() == null) {
return (T) this;
}
this.w = getContext().getResources().getDimensionPixelSize(wResource);
return (T) this;
}
/**
* 指定最大宽高
*
* @param size
* @return
*/
public T size(final int size) {
w(size);
h(size);
return (T) this;
}
/**
* 指定最大宽高
*
* @param sizeResource DimenRes
* @return
*/
public T sizeR(final int sizeResource) {
if (getContext() == null) {
return (T) this;
}
final int size = getContext().getResources().getDimensionPixelSize(sizeResource);
size(size);
return (T) this;
}
/**
* 指定最大高度
*
* @param h
* @return
*/
public T h(final int h) {
this.h = h;
return (T) this;
}
/**
* 指定最大高度
*
* @param hResource DimenRes
* @return
*/
public T hR(final int hResource) {
if (getContext() == null) {
return (T) this;
}
this.h = getContext().getResources().getDimensionPixelSize(hResource);
return (T) this;
}
/**
* 指定模式为mode
*
* @param mode
* @return
*/
public T mode(final int mode) {
this.mode = mode;
return (T) this;
}
/**
* {@link #mode} to {@link #MODE_FIT_XY}
* <p/>
* 指定模式为FitXY
*
* @return
* @see <url></url>https://github.com/lingochamp/QiniuImageLoader</url>
*/
public T fitXY() {
return mode(MODE_FIT_XY);
}
/**
* 指定模式为CenterCrop
*
* @return
* @see <url>https://github.com/lingochamp/QiniuImageLoader</url>
*/
public T centerCrop() {
return mode(MODE_CENTER_CROP);
}
/**
* 请求图片最大宽高为GL10.GL_MAX_TEXTURE_SIZE
*
* @return
* @see #MODE_FORCE_ORIGIN
*/
public T forceOrigin() {
return mode(MODE_FORCE_ORIGIN);
}
/**
* 根据七牛提供的API生成目标URL
*
* @return 目标URL
* @see <url>http://developer.qiniu.com/docs/v6/api/reference/fop/image/imageview2.html</url>
*/
public String createQiniuUrl() {
String u = this.oriUrl;
if (!isUrl(u)) {
return u;
}
int width = this.w;
int height = this.h;
final int maxWidth = getScreenWith();
final int maxHeight = getMaxHeight();
if (this.mode == MODE_FORCE_ORIGIN) {
width = GL10.GL_MAX_TEXTURE_SIZE;
height = GL10.GL_MAX_TEXTURE_SIZE;
} else {
// 其中一个有效
width = (height <= 0 && width > 0 && width > maxWidth) ? maxWidth : width;
height = (width <= 0 && height > 0 && height > maxHeight) ? maxHeight : height;
// 两个都无效
width = (width <= 0 && height <= 0) ? maxWidth : width;
//两个都有效
if (width > 0 && height > 0) {
if (width > maxWidth) {
height = (int) (height * ((float) maxWidth / width));
width = maxWidth;
}
if (height > maxHeight) {
width = (int) (width * ((float) maxHeight / height));
height = maxHeight;
}
}
}
// size /thumbnail/<width>x<height>[>最大宽高/<最小宽高]
// /thumbnail/[!]<width>x<height>[r] 限定短边,生成不小于<width>x<height>的 默认不指定!与r,为限定长边
// %3E = URLEncoder.encoder(">", "utf-8")
final String maxHeightUtf8 = "%3E";
String resizeParams = "";
if (width > 0 || height > 0) {
if (width <= 0) {
// h > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/x%d%s", height, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", height, height, height, height);
} else if (height <= 0) {
// w > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/%dx%s", width, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, width, width, width);
} else {
// h > 0 && w > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/%dx%d%s", width, height, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, height, width, height);
}
}
//op
String opParams = "";
for (Op op : opList) {
opParams += op.getOpUrlParam();
}
// format
String formatParams = "";
switch (this.format) {
case webp:
case jpg:
case gif:
case png:
formatParams = String.format("/format/%s", this.format.toString());
break;
case origin:
break;
}
if (!TextUtils.isEmpty(resizeParams) || !TextUtils.isEmpty(formatParams)) {
if (oriUrl.contains("?ImageView") || oriUrl.contains("?imageMogr2") || oriUrl.contains("?imageView2")) {
Log.e(TAG, String.format("oriUrl should create 7Niu url by self, %s", oriUrl));
if (!oriUrl.contains("/format")) {
u = String.format("%s%s", oriUrl, formatParams);
}
} else {
u = String.format("%s?imageMogr2/auto-orient%s%s%s", oriUrl, resizeParams, opParams, formatParams);
}
}
Log.d(TAG, String.format("【oriUrl】: %s 【url】: %s , (w: %d, h: %d)", oriUrl, u, w, h));
return u;
}
public void clear() {
this.context = null;
this.imageView = null;
this.mode = MODE_FIT_XY;
this.w = 0;
this.h = 0;
this.opList.clear();
}
/**
* 宽度等于屏幕的宽度
*
* @return
*/
public T screenW() {
if (getContext() == null) {
return (T) this;
}
this.w = getScreenWith();
return (T) this;
}
/**
* 宽度为屏幕的宽度的一半
*
* @return
*/
public T halfScreenW() {
if (getContext() == null) {
return (T) this;
}
this.w = getScreenWith() / 2;
return (T) this;
}
/**
* @param n n倍
* @return 高度会等于 宽度的n倍
*/
public T wTimesN2H(final float n) {
this.h = (int) (this.w * n);
return (T) this;
}
private static boolean isUrl(final String url) {
return !TextUtils.isEmpty(url) && url.startsWith("http");
}
protected Context getContext() {
Context context = this.context;
if (context == null) {
context = this.imageView == null ? null : this.imageView.getContext();
}
return context;
}
// for format
private enum Format {
origin, jpg, gif, png, webp
}
private enum OpName {
none, blur, rotate
}
private static class Op {
OpName name = OpName.none;
int val1;
int val2;
/**
* @param radius [1, 50]
* @param sigma [0, -]
* @return
*/
public Op blur(final int radius, final int sigma) {
this.name = OpName.blur;
this.val1 = radius;
this.val2 = sigma;
return this;
}
/**
* @param rotateDegree [1, 360]
* @return
*/
public Op rotate(final int rotateDegree) {
this.name = OpName.rotate;
this.val1 = rotateDegree;
return this;
}
public String getOpUrlParam() {
switch (name) {
case none:
return "";
case blur:
return String.format("/blur/%dx%d", this.val1, this.val2);
case rotate:
return String.format("/rotate/%d", this.val1);
}
return "";
}
}
private final static Format COMMEND_FORMAT = Format.webp;
private Format format = COMMEND_FORMAT;
private List<Op> opList = new ArrayList<>();
/**
* 请求图片进行高斯模糊处理
*
* @param radius [1, 50]
* @param sigma [0, -]
* @return
*/
public T addOpBlur(final int radius, final int sigma) {
opList.add(new Op().blur(radius, sigma));
return (T) this;
}
/**
* 请求图片进行旋转处理
*
* @param rotateDegree [1, 360]
* @return
*/
public T addOpRotate(final int rotateDegree) {
opList.add(new Op().rotate(rotateDegree));
return (T) this;
}
/**
* 请求图片jpg格式
*
* @return
*/
public T formatJpg() {
this.format = Format.jpg;
return (T) this;
}
/**
* 请求图片原格式
*
* @return
*/
public T formatOrigin() {
this.format = Format.origin;
return (T) this;
}
/**
* 请求图片png格式
*
* @return
*/
public T formatPng() {
this.format = Format.png;
return (T) this;
}
/**
* 请求图片webp格式(默认格式)
*
* @return
*/
public T formatWebp() {
this.format = Format.webp;
return (T) this;
}
private Context context;
private int getScreenWith() {
return getContext().getResources().getDisplayMetrics().widthPixels;
}
private int getMaxHeight() {
return getContext().getResources().getDisplayMetrics().heightPixels;
}
/**
* 加载图片到目标ImageView上并清理所有变量
*
* @see #attachWithNoClear()
*/
public void attach() {
attachWithNoClear();
clear();
}
/**
* for download & attach image 2 imageView
*/
public void attachWithNoClear() {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
/**
* for just download image
*/
public void fetch() {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
protected ImageView getImageView() {
return imageView;
}
protected String getOriUrl() {
return oriUrl;
}
protected int getW() {
return w;
}
protected int getH() {
return h;
}
protected int getMode() {
return mode;
}
protected Format getFormat() {
return format;
}
protected List<Op> getOpList() {
return opList;
}
}
| lingochamp/QiniuImageLoader | library/src/main/java/com/liulishuo/qiniuimageloader/QiniuImageLoader.java | 4,355 | /**
* {@link #mode} to {@link #MODE_FIT_XY}
* <p/>
* 指定模式为FitXY
*
* @return
* @see <url></url>https://github.com/lingochamp/QiniuImageLoader</url>
*/ | block_comment | nl | /**
* Copyright (c) 2015 LingoChamp Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.liulishuo.qiniuimageloader;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import javax.microedition.khronos.opengles.GL10;
/**
* Created by Jacksgong on 15/8/3.
*
* @Api: http://developer.qiniu.com/docs/v6/api/reference/fop/image/imagemogr2.html
*/
public class QiniuImageLoader<T extends QiniuImageLoader> {
private final static String TAG = "QiniuImageLoader";
private int mode = MODE_FIT_XY;
private int w = 0;
private int h = 0;
private String oriUrl;
private ImageView imageView;
/**
* 限定缩略图的宽最少为<Width>,高最少为<Height>,进行等比缩放,居中裁剪。
* <p/>
* 转后的缩略图通常恰好是 <Width>x<Height> 的大小(有一个边缩放的时候会因为超出矩形框而被裁剪掉多余部分)。
* <p/>
* 如果只指定 w 参数或只指定 h 参数,代表限定为长宽相等的正方图。
* <p/>
* 强制使用给定w与h
*/
private final static int MODE_CENTER_CROP = 1;
/**
* 限定缩略图的宽最多为<Width>,高最多为<Height>,进行等比缩放,不裁剪。
* <p/>
* 如果只指定 w 参数则表示限定宽(长自适应),只指定 h 参数则表示限定长(宽自适应)。
* <p/>
* 如果给定的w或h大于原图,则采用原图
*/
private final static int MODE_FIT_XY = 2;
/**
* 强制需要原图,通常是图片需要动态缩放才需要
*/
private final static int MODE_FORCE_ORIGIN = -1;
public QiniuImageLoader(final Context context, final String oriUrl) {
this.context = context;
this.oriUrl = oriUrl;
}
public QiniuImageLoader(final ImageView imageView, final String oriUrl) {
this.imageView = imageView;
this.oriUrl = oriUrl;
}
/**
* 指定最大宽度 为w
*
* @param w
* @return
*/
public T w(final int w) {
this.w = w;
return (T) this;
}
/**
* 指定最大宽度
*
* @param wResource DimenRes
* @return
*/
public T wR(final int wResource) {
if (getContext() == null) {
return (T) this;
}
this.w = getContext().getResources().getDimensionPixelSize(wResource);
return (T) this;
}
/**
* 指定最大宽高
*
* @param size
* @return
*/
public T size(final int size) {
w(size);
h(size);
return (T) this;
}
/**
* 指定最大宽高
*
* @param sizeResource DimenRes
* @return
*/
public T sizeR(final int sizeResource) {
if (getContext() == null) {
return (T) this;
}
final int size = getContext().getResources().getDimensionPixelSize(sizeResource);
size(size);
return (T) this;
}
/**
* 指定最大高度
*
* @param h
* @return
*/
public T h(final int h) {
this.h = h;
return (T) this;
}
/**
* 指定最大高度
*
* @param hResource DimenRes
* @return
*/
public T hR(final int hResource) {
if (getContext() == null) {
return (T) this;
}
this.h = getContext().getResources().getDimensionPixelSize(hResource);
return (T) this;
}
/**
* 指定模式为mode
*
* @param mode
* @return
*/
public T mode(final int mode) {
this.mode = mode;
return (T) this;
}
/**
* {@link #mode} to<SUF>*/
public T fitXY() {
return mode(MODE_FIT_XY);
}
/**
* 指定模式为CenterCrop
*
* @return
* @see <url>https://github.com/lingochamp/QiniuImageLoader</url>
*/
public T centerCrop() {
return mode(MODE_CENTER_CROP);
}
/**
* 请求图片最大宽高为GL10.GL_MAX_TEXTURE_SIZE
*
* @return
* @see #MODE_FORCE_ORIGIN
*/
public T forceOrigin() {
return mode(MODE_FORCE_ORIGIN);
}
/**
* 根据七牛提供的API生成目标URL
*
* @return 目标URL
* @see <url>http://developer.qiniu.com/docs/v6/api/reference/fop/image/imageview2.html</url>
*/
public String createQiniuUrl() {
String u = this.oriUrl;
if (!isUrl(u)) {
return u;
}
int width = this.w;
int height = this.h;
final int maxWidth = getScreenWith();
final int maxHeight = getMaxHeight();
if (this.mode == MODE_FORCE_ORIGIN) {
width = GL10.GL_MAX_TEXTURE_SIZE;
height = GL10.GL_MAX_TEXTURE_SIZE;
} else {
// 其中一个有效
width = (height <= 0 && width > 0 && width > maxWidth) ? maxWidth : width;
height = (width <= 0 && height > 0 && height > maxHeight) ? maxHeight : height;
// 两个都无效
width = (width <= 0 && height <= 0) ? maxWidth : width;
//两个都有效
if (width > 0 && height > 0) {
if (width > maxWidth) {
height = (int) (height * ((float) maxWidth / width));
width = maxWidth;
}
if (height > maxHeight) {
width = (int) (width * ((float) maxHeight / height));
height = maxHeight;
}
}
}
// size /thumbnail/<width>x<height>[>最大宽高/<最小宽高]
// /thumbnail/[!]<width>x<height>[r] 限定短边,生成不小于<width>x<height>的 默认不指定!与r,为限定长边
// %3E = URLEncoder.encoder(">", "utf-8")
final String maxHeightUtf8 = "%3E";
String resizeParams = "";
if (width > 0 || height > 0) {
if (width <= 0) {
// h > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/x%d%s", height, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", height, height, height, height);
} else if (height <= 0) {
// w > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/%dx%s", width, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, width, width, width);
} else {
// h > 0 && w > 0
resizeParams = this.mode == MODE_FORCE_ORIGIN || this.mode == MODE_FIT_XY ?
// fit xy
String.format("/thumbnail/%dx%d%s", width, height, maxHeightUtf8) :
// center crop
String.format("/thumbnail/!%dx%dr/gravity/Center/crop/%dx%d", width, height, width, height);
}
}
//op
String opParams = "";
for (Op op : opList) {
opParams += op.getOpUrlParam();
}
// format
String formatParams = "";
switch (this.format) {
case webp:
case jpg:
case gif:
case png:
formatParams = String.format("/format/%s", this.format.toString());
break;
case origin:
break;
}
if (!TextUtils.isEmpty(resizeParams) || !TextUtils.isEmpty(formatParams)) {
if (oriUrl.contains("?ImageView") || oriUrl.contains("?imageMogr2") || oriUrl.contains("?imageView2")) {
Log.e(TAG, String.format("oriUrl should create 7Niu url by self, %s", oriUrl));
if (!oriUrl.contains("/format")) {
u = String.format("%s%s", oriUrl, formatParams);
}
} else {
u = String.format("%s?imageMogr2/auto-orient%s%s%s", oriUrl, resizeParams, opParams, formatParams);
}
}
Log.d(TAG, String.format("【oriUrl】: %s 【url】: %s , (w: %d, h: %d)", oriUrl, u, w, h));
return u;
}
public void clear() {
this.context = null;
this.imageView = null;
this.mode = MODE_FIT_XY;
this.w = 0;
this.h = 0;
this.opList.clear();
}
/**
* 宽度等于屏幕的宽度
*
* @return
*/
public T screenW() {
if (getContext() == null) {
return (T) this;
}
this.w = getScreenWith();
return (T) this;
}
/**
* 宽度为屏幕的宽度的一半
*
* @return
*/
public T halfScreenW() {
if (getContext() == null) {
return (T) this;
}
this.w = getScreenWith() / 2;
return (T) this;
}
/**
* @param n n倍
* @return 高度会等于 宽度的n倍
*/
public T wTimesN2H(final float n) {
this.h = (int) (this.w * n);
return (T) this;
}
private static boolean isUrl(final String url) {
return !TextUtils.isEmpty(url) && url.startsWith("http");
}
protected Context getContext() {
Context context = this.context;
if (context == null) {
context = this.imageView == null ? null : this.imageView.getContext();
}
return context;
}
// for format
private enum Format {
origin, jpg, gif, png, webp
}
private enum OpName {
none, blur, rotate
}
private static class Op {
OpName name = OpName.none;
int val1;
int val2;
/**
* @param radius [1, 50]
* @param sigma [0, -]
* @return
*/
public Op blur(final int radius, final int sigma) {
this.name = OpName.blur;
this.val1 = radius;
this.val2 = sigma;
return this;
}
/**
* @param rotateDegree [1, 360]
* @return
*/
public Op rotate(final int rotateDegree) {
this.name = OpName.rotate;
this.val1 = rotateDegree;
return this;
}
public String getOpUrlParam() {
switch (name) {
case none:
return "";
case blur:
return String.format("/blur/%dx%d", this.val1, this.val2);
case rotate:
return String.format("/rotate/%d", this.val1);
}
return "";
}
}
private final static Format COMMEND_FORMAT = Format.webp;
private Format format = COMMEND_FORMAT;
private List<Op> opList = new ArrayList<>();
/**
* 请求图片进行高斯模糊处理
*
* @param radius [1, 50]
* @param sigma [0, -]
* @return
*/
public T addOpBlur(final int radius, final int sigma) {
opList.add(new Op().blur(radius, sigma));
return (T) this;
}
/**
* 请求图片进行旋转处理
*
* @param rotateDegree [1, 360]
* @return
*/
public T addOpRotate(final int rotateDegree) {
opList.add(new Op().rotate(rotateDegree));
return (T) this;
}
/**
* 请求图片jpg格式
*
* @return
*/
public T formatJpg() {
this.format = Format.jpg;
return (T) this;
}
/**
* 请求图片原格式
*
* @return
*/
public T formatOrigin() {
this.format = Format.origin;
return (T) this;
}
/**
* 请求图片png格式
*
* @return
*/
public T formatPng() {
this.format = Format.png;
return (T) this;
}
/**
* 请求图片webp格式(默认格式)
*
* @return
*/
public T formatWebp() {
this.format = Format.webp;
return (T) this;
}
private Context context;
private int getScreenWith() {
return getContext().getResources().getDisplayMetrics().widthPixels;
}
private int getMaxHeight() {
return getContext().getResources().getDisplayMetrics().heightPixels;
}
/**
* 加载图片到目标ImageView上并清理所有变量
*
* @see #attachWithNoClear()
*/
public void attach() {
attachWithNoClear();
clear();
}
/**
* for download & attach image 2 imageView
*/
public void attachWithNoClear() {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
/**
* for just download image
*/
public void fetch() {
throw new UnsupportedOperationException(
"Required method instantiateItem was not overridden");
}
protected ImageView getImageView() {
return imageView;
}
protected String getOriUrl() {
return oriUrl;
}
protected int getW() {
return w;
}
protected int getH() {
return h;
}
protected int getMode() {
return mode;
}
protected Format getFormat() {
return format;
}
protected List<Op> getOpList() {
return opList;
}
}
| False |
3,194 | 187427_1 | class RingBuffer {
int size;
int[] smg;
int start;
int end;
// returns a rb of the size
RingBuffer(int size) {
this.size = size;
this.smg = new int[size];
this.start = 0;
this.end = 0;
}
// insert : int ->
public RingBuffer insert( int elem ) {
this.smg[ this.end ] = elem;
this.end = (this.end + 1) % this.size;
return this;
}
// read : int -> int
// REQUIRES: insert() has been called at least idx times
// idx < size
// returns the element inserted idx times in the past
// EXAMPLE
// (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1)
// = 2
public int read ( int idx ) {
return
this.smg[ (this.end - idx + this.size - 1)
% this.size ];
}
// BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? }
// insert(1)
// AFTER: smg = { 1 , ? }, end = 1
// insert(2)
// AFTER: smg = { 1 , 2 }, end = 0
// insert(3)
// AFTER: smg = { 3 , 2 }, end = 1
// read(1)
}
class Box {
boolean d;
Box() {
this.d = true;
}
// observe : -> bool
// EFFECTS: this
// IMPL: flips the booleanosity of this.d
// CLIENT: cycles between false and true
// CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false
// BIG DEAL: Specs are for clients, not implementers
public boolean observe() {
this.d = ! this.d;
return this.d;
}
}
class C7 {
// returns three more than the input
// REQUIRES: x be even
static int f ( int x ) {
return x + 3;
}
// g : ->
// REQUIRES: amanda_before is even
// EFFECTS: amanda
// amanda_after is amanda_before + 3
static int amanda = 0;
static void g ( ) {
amanda = amanda + 3;
}
static class Store {
public int amanda;
Store ( int amanda ) {
this.amanda = amanda;
}
}
// XXXg : Store -> Store
// REQUIRES: the store contain an even amanda
// produces a new store that contains an amanda three degrees
// cooler
static Store XXXg ( Store st ) {
return new Store ( st.amanda + 3 );
}
static int isabella = 0;
// hm : int -> int
// REQUIRES: y can't be zero
// EFFECTS: isabella
// isabella_after is one more than isabella_before
// returns isabella_before divided by y
static int hm ( int y ) {
int r = isabella / y;
isabella = isabella + 1;
return r;
}
static class HMStore {
public int isabella;
HMStore ( int isabella ) {
this.isabella = isabella;
}
}
static class IntAndHMStore {
int r;
HMStore st;
IntAndHMStore( int r, HMStore st ) {
this.r = r;
this.st = st;
}
}
// XXXh : Store int -> int x Store
// REQUIRES: y can't be zero
// returns st.isabella divided by y and a store where isabella is
// one more than st.isabella
static IntAndHMStore XXXhm ( HMStore st, int y ) {
int r = st.isabella / y;
HMStore stp = new HMStore( st.isabella + 1 );
return new IntAndHMStore( r, stp );
}
// The transformation is called "Store-Passing Style"
public static void main(String[] args) {
System.out.println("Yo! Raps!");
System.out.println(f(4) + " should be " + 7);
int x = 4;
System.out.println(f(x) + " should be " + 7);
System.out.println((x + 3) + " should be " + 7);
System.out.println((4 + 3) + " should be " + 7);
x = x / 2;
System.out.println(f(x) + " should be " + 5);
System.out.println((x + 3) + " should be " + 5);
System.out.println((2 + 3) + " should be " + 5);
amanda = 4;
// BEFORE amanda = 4
g();
// AFTER amanda = 7
System.out.println(amanda + " should be " + 7);
g();
System.out.println(amanda + " should be " + 10);
// From here
Store st_0 = new Store( 4 );
Store st_1 = XXXg( st_0 );
System.out.println(st_1.amanda + " should be " + 7);
Store st_2 = XXXg( st_1 );
System.out.println(st_2.amanda + " should be " + 10);
// to here
// st_x is used "linearly"
System.out.println(st_0.amanda + " should be " + 4);
Box sb = new Box();
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The fox says, ?");
RingBuffer rb = (new RingBuffer(2));
rb.insert(1);
System.out.println(rb.read(0) + " should be " + 1 );
rb.insert(2);
System.out.println(rb.read(0) + " should be " + 2 );
System.out.println(rb.read(1) + " should be " + 1 );
rb.insert(3);
System.out.println(rb.read(0) + " should be " + 3 );
System.out.println(rb.read(1) + " should be " + 2 );
rb.insert(4);
System.out.println(rb.read(0) + " should be " + 4 );
System.out.println(rb.read(1) + " should be " + 3 );
}
}
| jeapostrophe/jeapostrophe.github.com | courses/2014/fall/203/notes/7.java | 1,812 | // insert : int -> | line_comment | nl | class RingBuffer {
int size;
int[] smg;
int start;
int end;
// returns a rb of the size
RingBuffer(int size) {
this.size = size;
this.smg = new int[size];
this.start = 0;
this.end = 0;
}
// insert :<SUF>
public RingBuffer insert( int elem ) {
this.smg[ this.end ] = elem;
this.end = (this.end + 1) % this.size;
return this;
}
// read : int -> int
// REQUIRES: insert() has been called at least idx times
// idx < size
// returns the element inserted idx times in the past
// EXAMPLE
// (new RingBuffer(2)).insert(1).insert(2).insert(3).read(1)
// = 2
public int read ( int idx ) {
return
this.smg[ (this.end - idx + this.size - 1)
% this.size ];
}
// BEFORE: start = 0, end = 0, size = 2, smg = { ? , ? }
// insert(1)
// AFTER: smg = { 1 , ? }, end = 1
// insert(2)
// AFTER: smg = { 1 , 2 }, end = 0
// insert(3)
// AFTER: smg = { 3 , 2 }, end = 1
// read(1)
}
class Box {
boolean d;
Box() {
this.d = true;
}
// observe : -> bool
// EFFECTS: this
// IMPL: flips the booleanosity of this.d
// CLIENT: cycles between false and true
// CLIENT: the next call to observe will return the opposite of what this one does; the first call returns false
// BIG DEAL: Specs are for clients, not implementers
public boolean observe() {
this.d = ! this.d;
return this.d;
}
}
class C7 {
// returns three more than the input
// REQUIRES: x be even
static int f ( int x ) {
return x + 3;
}
// g : ->
// REQUIRES: amanda_before is even
// EFFECTS: amanda
// amanda_after is amanda_before + 3
static int amanda = 0;
static void g ( ) {
amanda = amanda + 3;
}
static class Store {
public int amanda;
Store ( int amanda ) {
this.amanda = amanda;
}
}
// XXXg : Store -> Store
// REQUIRES: the store contain an even amanda
// produces a new store that contains an amanda three degrees
// cooler
static Store XXXg ( Store st ) {
return new Store ( st.amanda + 3 );
}
static int isabella = 0;
// hm : int -> int
// REQUIRES: y can't be zero
// EFFECTS: isabella
// isabella_after is one more than isabella_before
// returns isabella_before divided by y
static int hm ( int y ) {
int r = isabella / y;
isabella = isabella + 1;
return r;
}
static class HMStore {
public int isabella;
HMStore ( int isabella ) {
this.isabella = isabella;
}
}
static class IntAndHMStore {
int r;
HMStore st;
IntAndHMStore( int r, HMStore st ) {
this.r = r;
this.st = st;
}
}
// XXXh : Store int -> int x Store
// REQUIRES: y can't be zero
// returns st.isabella divided by y and a store where isabella is
// one more than st.isabella
static IntAndHMStore XXXhm ( HMStore st, int y ) {
int r = st.isabella / y;
HMStore stp = new HMStore( st.isabella + 1 );
return new IntAndHMStore( r, stp );
}
// The transformation is called "Store-Passing Style"
public static void main(String[] args) {
System.out.println("Yo! Raps!");
System.out.println(f(4) + " should be " + 7);
int x = 4;
System.out.println(f(x) + " should be " + 7);
System.out.println((x + 3) + " should be " + 7);
System.out.println((4 + 3) + " should be " + 7);
x = x / 2;
System.out.println(f(x) + " should be " + 5);
System.out.println((x + 3) + " should be " + 5);
System.out.println((2 + 3) + " should be " + 5);
amanda = 4;
// BEFORE amanda = 4
g();
// AFTER amanda = 7
System.out.println(amanda + " should be " + 7);
g();
System.out.println(amanda + " should be " + 10);
// From here
Store st_0 = new Store( 4 );
Store st_1 = XXXg( st_0 );
System.out.println(st_1.amanda + " should be " + 7);
Store st_2 = XXXg( st_1 );
System.out.println(st_2.amanda + " should be " + 10);
// to here
// st_x is used "linearly"
System.out.println(st_0.amanda + " should be " + 4);
Box sb = new Box();
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The box says, " + sb.observe());
System.out.println("The fox says, ?");
RingBuffer rb = (new RingBuffer(2));
rb.insert(1);
System.out.println(rb.read(0) + " should be " + 1 );
rb.insert(2);
System.out.println(rb.read(0) + " should be " + 2 );
System.out.println(rb.read(1) + " should be " + 1 );
rb.insert(3);
System.out.println(rb.read(0) + " should be " + 3 );
System.out.println(rb.read(1) + " should be " + 2 );
rb.insert(4);
System.out.println(rb.read(0) + " should be " + 4 );
System.out.println(rb.read(1) + " should be " + 3 );
}
}
| False |
325 | 30224_11 | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een 204 status
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | Christiaan83/backend-spring-boot-tech-it-easy | src/main/java/nl/novi/techiteasy/controllers/TelevisionControllerBonus.java | 897 | // Return een 204 status | line_comment | nl | package nl.novi.techiteasy.controllers;
import nl.novi.techiteasy.exceptions.RecordNotFoundException;
import nl.novi.techiteasy.exceptions.TelevisionNameTooLongException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
// Deze RequestMapping" op klasse niveau betekent dat elke Mapping in deze klasse begint met "localhost:8080/bonus/..."
@RequestMapping(value = "/bonus")
public class TelevisionControllerBonus {
// De lijst is static, omdat er maar 1 lijst kan zijn.
// De lijst is final, omdat de lijst op zich niet kan veranderen, enkel de waardes die er in staan.
private static final List<String> televisionDatabase = new ArrayList<>();
@GetMapping("/televisions")
public ResponseEntity<List<String>> getAllTelevisions() {
// Return de complete lijst met een 200 status
return ResponseEntity.ok(televisionDatabase);
}
@GetMapping("/televisions/{id}")
public ResponseEntity<String> getTelevision(@PathVariable int id) {
// Return de waarde die op index(id) staat en een 200 status
// Wanneer de gebruiker een request doet met id=300, maar de lijst heeft maar 3 items.
// Dan gooit java een IndexOutOfBoundsException. De bonus methode in de ExceptionController vangt dit op en stuurt de gebruiker een berichtje.
return ResponseEntity.ok(televisionDatabase.get(id));
}
@PostMapping("/televisions")
public ResponseEntity<String> addTelevision(@RequestBody String television) {
// Bonus bonus: check voor 20 letters:
if(television.length()>20){
throw new TelevisionNameTooLongException("Televisienaam is te lang");
} else {
// Voeg de televisie uit de parameter toe aan de lijst
televisionDatabase.add(television);
// Return de televisie uit de parameter met een 201 status
return ResponseEntity.created(null).body(television);
}
}
@DeleteMapping("/televisions/{id}")
public ResponseEntity<Void> deleteTelevision(@PathVariable int id) {
// Vervang de waarde op index(id) met null. Als we de waarde zouden verwijderen, zouden alle indexen die na deze waarden komen in de lijst met 1 afnemen.
televisionDatabase.set(id, null);
// Return een<SUF>
return ResponseEntity.noContent().build();
}
@PutMapping("/televisions/{id}")
public ResponseEntity<Void> updateTelevision(@PathVariable int id, @RequestBody String television) {
// In de vorige methodes hebben we impliciet gebruik gemaakt van "IndexOUtOfBoundsException" als het id groter was dan de lijst.
// In deze methode checken we daar expliciet voor en gooien we een custom exception op.
if(televisionDatabase.isEmpty() || id>televisionDatabase.size()){
throw new RecordNotFoundException("Record met id: " + id + " niet gevonden in de database.");
} else {
// Vervang de waarde op index(id) met de television uit de parameter
televisionDatabase.set(id, television);
// Return een 204 status
return ResponseEntity.noContent().build();
}
}
} | True |
62 | 25179_6 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| AVEHD/fox_bunny | SimulatorView.java | 2,166 | /**
* Methode om een actie uit te voeren wanneer er op een knop wordt geklikt
*/ | block_comment | nl | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedHashMap;
import java.util.Map;
import java.awt.event.ActionListener;
/**
* A graphical view of the simulation grid.
* The view displays a colored rectangle for each location
* representing its contents. It uses a default background color.
* Colors for each type of species can be defined using the
* setColor method.
*
* @author Adriaan van Elk, Eric Gunnink & Jelmer Postma
* @version 27-1-2015
*/
public class SimulatorView extends JFrame implements ActionListener
{
// Colors used for empty locations.
private static final Color EMPTY_COLOR = Color.white;
// Color used for objects that have no defined color.
private static final Color UNKNOWN_COLOR = Color.gray;
private final String STEP_PREFIX = "Step: ";
private final String POPULATION_PREFIX = "Population: ";
private JLabel stepLabel, population;
private JPanel linkerMenu;
private FieldView fieldView;
public JButton oneStepButton = new JButton("1 stap");
public JButton oneHundredStepButton = new JButton("100 stappen");
// A map for storing colors for participants in the simulation
private Map<Class, Color> colors;
// A statistics object computing and storing simulation information
private FieldStats stats;
private Simulator theSimulator;
/**
* Create a view of the given width and height.
* @param height The simulation's height.
* @param width The simulation's width.
*/
public SimulatorView(int height, int width, Simulator simulator)
{
stats = new FieldStats();
colors = new LinkedHashMap<Class, Color>();
setTitle("Fox and Rabbit Simulation");
stepLabel = new JLabel(STEP_PREFIX, JLabel.CENTER);
population = new JLabel(POPULATION_PREFIX, JLabel.CENTER);
linkerMenu = new JPanel(new GridLayout(2,1));
theSimulator = simulator;
setLocation(100, 50);
fieldView = new FieldView(height, width);
Container contents = getContentPane();
contents.add(stepLabel, BorderLayout.NORTH);
contents.add(fieldView, BorderLayout.CENTER);
contents.add(population, BorderLayout.SOUTH);
contents.add(linkerMenu, BorderLayout.WEST);
addButton();
pack();
setVisible(true);
}
private void addButton()
{
linkerMenu.add(oneStepButton);
linkerMenu.add(oneHundredStepButton);
oneStepButton.addActionListener(this);
oneHundredStepButton.addActionListener(this);
}
/**
* Methode om een<SUF>*/
public void actionPerformed(ActionEvent event)
{
String command = event.getActionCommand();
if(command.equals("1 stap"))
{
theSimulator.simulateOneStep();
}
if(command.equals("100 stappen"))
{
theSimulator.simulate(100);
}
}
/**
* Define a color to be used for a given class of animal.
* @param animalClass The animal's Class object.
* @param color The color to be used for the given class.
*/
public void setColor(Class animalClass, Color color)
{
colors.put(animalClass, color);
}
/**
* @return The color to be used for a given class of animal.
*/
private Color getColor(Class animalClass)
{
Color col = colors.get(animalClass);
if(col == null) {
// no color defined for this class
return UNKNOWN_COLOR;
}
else {
return col;
}
}
/**
* Show the current status of the field.
* @param step Which iteration step it is.
* @param field The field whose status is to be displayed.
*/
public void showStatus(int step, Field field)
{
if(!isVisible()) {
setVisible(true);
}
stepLabel.setText(STEP_PREFIX + step);
stats.reset();
fieldView.preparePaint();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
Object animal = field.getObjectAt(row, col);
if(animal != null) {
stats.incrementCount(animal.getClass());
fieldView.drawMark(col, row, getColor(animal.getClass()));
}
else {
fieldView.drawMark(col, row, EMPTY_COLOR);
}
}
}
stats.countFinished();
population.setText(POPULATION_PREFIX + stats.getPopulationDetails(field));
fieldView.repaint();
}
/**
* Determine whether the simulation should continue to run.
* @return true If there is more than one species alive.
*/
public boolean isViable(Field field)
{
return stats.isViable(field);
}
/**
* Provide a graphical view of a rectangular field. This is
* a nested class (a class defined inside a class) which
* defines a custom component for the user interface. This
* component displays the field.
* This is rather advanced GUI stuff - you can ignore this
* for your project if you like.
*/
private class FieldView extends JPanel
{
private final int GRID_VIEW_SCALING_FACTOR = 6;
private int gridWidth, gridHeight;
private int xScale, yScale;
Dimension size;
private Graphics g;
private Image fieldImage;
/**
* Create a new FieldView component.
*/
public FieldView(int height, int width)
{
gridHeight = height;
gridWidth = width;
size = new Dimension(0, 0);
}
/**
* Tell the GUI manager how big we would like to be.
*/
public Dimension getPreferredSize()
{
return new Dimension(gridWidth * GRID_VIEW_SCALING_FACTOR,
gridHeight * GRID_VIEW_SCALING_FACTOR);
}
/**
* Prepare for a new round of painting. Since the component
* may be resized, compute the scaling factor again.
*/
public void preparePaint()
{
if(! size.equals(getSize())) { // if the size has changed...
size = getSize();
fieldImage = fieldView.createImage(size.width, size.height);
g = fieldImage.getGraphics();
xScale = size.width / gridWidth;
if(xScale < 1) {
xScale = GRID_VIEW_SCALING_FACTOR;
}
yScale = size.height / gridHeight;
if(yScale < 1) {
yScale = GRID_VIEW_SCALING_FACTOR;
}
}
}
/**
* Paint on grid location on this field in a given color.
*/
public void drawMark(int x, int y, Color color)
{
g.setColor(color);
g.fillRect(x * xScale, y * yScale, xScale-1, yScale-1);
}
/**
* The field view component needs to be redisplayed. Copy the
* internal image to screen.
*/
public void paintComponent(Graphics g)
{
if(fieldImage != null) {
Dimension currentSize = getSize();
if(size.equals(currentSize)) {
g.drawImage(fieldImage, 0, 0, null);
}
else {
// Rescale the previous image.
g.drawImage(fieldImage, 0, 0, currentSize.width, currentSize.height, null);
}
}
}
}
}
| True |
2,579 | 36942_4 | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Well Known Services - Lists services offered by this host.
*
* @author Brian Wellington
* @see <a href="https://tools.ietf.org/html/rfc1035">RFC 1035: Domain Names - Implementation and
* Specification</a>
*/
public class WKSRecord extends Record {
/**
* IP protocol identifiers. This is basically copied out of RFC 1010.
*
* @see <a href="https://tools.ietf.org/html/rfc1010">RFC 1010: Assigned Numbers</a>
*/
public static class Protocol {
private Protocol() {}
/** Internet Control Message */
public static final int ICMP = 1;
/** Internet Group Management */
public static final int IGMP = 2;
/** Gateway-to-Gateway */
public static final int GGP = 3;
/** Stream */
public static final int ST = 5;
/** Transmission Control */
public static final int TCP = 6;
/** UCL */
public static final int UCL = 7;
/** Exterior Gateway Protocol */
public static final int EGP = 8;
/** any private interior gateway */
public static final int IGP = 9;
/** BBN RCC Monitoring */
public static final int BBN_RCC_MON = 10;
/** Network Voice Protocol */
public static final int NVP_II = 11;
/** PUP */
public static final int PUP = 12;
/** ARGUS */
public static final int ARGUS = 13;
/** EMCON */
public static final int EMCON = 14;
/** Cross Net Debugger */
public static final int XNET = 15;
/** Chaos */
public static final int CHAOS = 16;
/** User Datagram */
public static final int UDP = 17;
/** Multiplexing */
public static final int MUX = 18;
/** DCN Measurement Subsystems */
public static final int DCN_MEAS = 19;
/** Host Monitoring */
public static final int HMP = 20;
/** Packet Radio Measurement */
public static final int PRM = 21;
/** XEROX NS IDP */
public static final int XNS_IDP = 22;
/** Trunk-1 */
public static final int TRUNK_1 = 23;
/** Trunk-2 */
public static final int TRUNK_2 = 24;
/** Leaf-1 */
public static final int LEAF_1 = 25;
/** Leaf-2 */
public static final int LEAF_2 = 26;
/** Reliable Data Protocol */
public static final int RDP = 27;
/** Internet Reliable Transaction */
public static final int IRTP = 28;
/** ISO Transport Protocol Class 4 */
public static final int ISO_TP4 = 29;
/** Bulk Data Transfer Protocol */
public static final int NETBLT = 30;
/** MFE Network Services Protocol */
public static final int MFE_NSP = 31;
/** MERIT Internodal Protocol */
public static final int MERIT_INP = 32;
/** Sequential Exchange Protocol */
public static final int SEP = 33;
/** CFTP */
public static final int CFTP = 62;
/** SATNET and Backroom EXPAK */
public static final int SAT_EXPAK = 64;
/** MIT Subnet Support */
public static final int MIT_SUBNET = 65;
/** MIT Remote Virtual Disk Protocol */
public static final int RVD = 66;
/** Internet Pluribus Packet Core */
public static final int IPPC = 67;
/** SATNET Monitoring */
public static final int SAT_MON = 69;
/** Internet Packet Core Utility */
public static final int IPCV = 71;
/** Backroom SATNET Monitoring */
public static final int BR_SAT_MON = 76;
/** WIDEBAND Monitoring */
public static final int WB_MON = 78;
/** WIDEBAND EXPAK */
public static final int WB_EXPAK = 79;
private static final Mnemonic protocols = new Mnemonic("IP protocol", Mnemonic.CASE_LOWER);
static {
protocols.setMaximum(0xFF);
protocols.setNumericAllowed(true);
protocols.add(ICMP, "icmp");
protocols.add(IGMP, "igmp");
protocols.add(GGP, "ggp");
protocols.add(ST, "st");
protocols.add(TCP, "tcp");
protocols.add(UCL, "ucl");
protocols.add(EGP, "egp");
protocols.add(IGP, "igp");
protocols.add(BBN_RCC_MON, "bbn-rcc-mon");
protocols.add(NVP_II, "nvp-ii");
protocols.add(PUP, "pup");
protocols.add(ARGUS, "argus");
protocols.add(EMCON, "emcon");
protocols.add(XNET, "xnet");
protocols.add(CHAOS, "chaos");
protocols.add(UDP, "udp");
protocols.add(MUX, "mux");
protocols.add(DCN_MEAS, "dcn-meas");
protocols.add(HMP, "hmp");
protocols.add(PRM, "prm");
protocols.add(XNS_IDP, "xns-idp");
protocols.add(TRUNK_1, "trunk-1");
protocols.add(TRUNK_2, "trunk-2");
protocols.add(LEAF_1, "leaf-1");
protocols.add(LEAF_2, "leaf-2");
protocols.add(RDP, "rdp");
protocols.add(IRTP, "irtp");
protocols.add(ISO_TP4, "iso-tp4");
protocols.add(NETBLT, "netblt");
protocols.add(MFE_NSP, "mfe-nsp");
protocols.add(MERIT_INP, "merit-inp");
protocols.add(SEP, "sep");
protocols.add(CFTP, "cftp");
protocols.add(SAT_EXPAK, "sat-expak");
protocols.add(MIT_SUBNET, "mit-subnet");
protocols.add(RVD, "rvd");
protocols.add(IPPC, "ippc");
protocols.add(SAT_MON, "sat-mon");
protocols.add(IPCV, "ipcv");
protocols.add(BR_SAT_MON, "br-sat-mon");
protocols.add(WB_MON, "wb-mon");
protocols.add(WB_EXPAK, "wb-expak");
}
/** Converts an IP protocol value into its textual representation */
public static String string(int type) {
return protocols.getText(type);
}
/**
* Converts a textual representation of an IP protocol into its numeric code. Integers in the
* range 0..255 are also accepted.
*
* @param s The textual representation of the protocol
* @return The protocol code, or -1 on error.
*/
public static int value(String s) {
return protocols.getValue(s);
}
}
public static class Service {
/**
* TCP/UDP services. This is basically copied out of RFC 1010, with MIT-ML-DEV removed, as it is
* not unique, and the description of SWIFT-RVF fixed.
*/
private Service() {}
/** Remote Job Entry */
public static final int RJE = 5;
/** Echo */
public static final int ECHO = 7;
/** Discard */
public static final int DISCARD = 9;
/** Active Users */
public static final int USERS = 11;
/** Daytime */
public static final int DAYTIME = 13;
/** Quote of the Day */
public static final int QUOTE = 17;
/** Character Generator */
public static final int CHARGEN = 19;
/** File Transfer [Default Data] */
public static final int FTP_DATA = 20;
/** File Transfer [Control] */
public static final int FTP = 21;
/** Telnet */
public static final int TELNET = 23;
/** Simple Mail Transfer */
public static final int SMTP = 25;
/** NSW User System FE */
public static final int NSW_FE = 27;
/** MSG ICP */
public static final int MSG_ICP = 29;
/** MSG Authentication */
public static final int MSG_AUTH = 31;
/** Display Support Protocol */
public static final int DSP = 33;
/** Time */
public static final int TIME = 37;
/** Resource Location Protocol */
public static final int RLP = 39;
/** Graphics */
public static final int GRAPHICS = 41;
/** Host Name Server */
public static final int NAMESERVER = 42;
/** Who Is */
public static final int NICNAME = 43;
/** MPM FLAGS Protocol */
public static final int MPM_FLAGS = 44;
/** Message Processing Module [recv] */
public static final int MPM = 45;
/** MPM [default send] */
public static final int MPM_SND = 46;
/** NI FTP */
public static final int NI_FTP = 47;
/** Login Host Protocol */
public static final int LOGIN = 49;
/** IMP Logical Address Maintenance */
public static final int LA_MAINT = 51;
/** Domain Name Server */
public static final int DOMAIN = 53;
/** ISI Graphics Language */
public static final int ISI_GL = 55;
/** NI MAIL */
public static final int NI_MAIL = 61;
/** VIA Systems - FTP */
public static final int VIA_FTP = 63;
/** TACACS-Database Service */
public static final int TACACS_DS = 65;
/** Bootstrap Protocol Server */
public static final int BOOTPS = 67;
/** Bootstrap Protocol Client */
public static final int BOOTPC = 68;
/** Trivial File Transfer */
public static final int TFTP = 69;
/** Remote Job Service */
public static final int NETRJS_1 = 71;
/** Remote Job Service */
public static final int NETRJS_2 = 72;
/** Remote Job Service */
public static final int NETRJS_3 = 73;
/** Remote Job Service */
public static final int NETRJS_4 = 74;
/** Finger */
public static final int FINGER = 79;
/** HOSTS2 Name Server */
public static final int HOSTS2_NS = 81;
/** SU/MIT Telnet Gateway */
public static final int SU_MIT_TG = 89;
/** MIT Dover Spooler */
public static final int MIT_DOV = 91;
/** Device Control Protocol */
public static final int DCP = 93;
/** SUPDUP */
public static final int SUPDUP = 95;
/** Swift Remote Virtual File Protocol */
public static final int SWIFT_RVF = 97;
/** TAC News */
public static final int TACNEWS = 98;
/** Metagram Relay */
public static final int METAGRAM = 99;
/** NIC Host Name Server */
public static final int HOSTNAME = 101;
/** ISO-TSAP */
public static final int ISO_TSAP = 102;
/** X400 */
public static final int X400 = 103;
/** X400-SND */
public static final int X400_SND = 104;
/** Mailbox Name Nameserver */
public static final int CSNET_NS = 105;
/** Remote Telnet Service */
public static final int RTELNET = 107;
/** Post Office Protocol - Version 2 */
public static final int POP_2 = 109;
/** SUN Remote Procedure Call */
public static final int SUNRPC = 111;
/** Authentication Service */
public static final int AUTH = 113;
/** Simple File Transfer Protocol */
public static final int SFTP = 115;
/** UUCP Path Service */
public static final int UUCP_PATH = 117;
/** Network News Transfer Protocol */
public static final int NNTP = 119;
/** HYDRA Expedited Remote Procedure */
public static final int ERPC = 121;
/** Network Time Protocol */
public static final int NTP = 123;
/** Locus PC-Interface Net Map Server */
public static final int LOCUS_MAP = 125;
/** Locus PC-Interface Conn Server */
public static final int LOCUS_CON = 127;
/** Password Generator Protocol */
public static final int PWDGEN = 129;
/** CISCO FNATIVE */
public static final int CISCO_FNA = 130;
/** CISCO TNATIVE */
public static final int CISCO_TNA = 131;
/** CISCO SYSMAINT */
public static final int CISCO_SYS = 132;
/** Statistics Service */
public static final int STATSRV = 133;
/** INGRES-NET Service */
public static final int INGRES_NET = 134;
/** Location Service */
public static final int LOC_SRV = 135;
/** PROFILE Naming System */
public static final int PROFILE = 136;
/** NETBIOS Name Service */
public static final int NETBIOS_NS = 137;
/** NETBIOS Datagram Service */
public static final int NETBIOS_DGM = 138;
/** NETBIOS Session Service */
public static final int NETBIOS_SSN = 139;
/** EMFIS Data Service */
public static final int EMFIS_DATA = 140;
/** EMFIS Control Service */
public static final int EMFIS_CNTL = 141;
/** Britton-Lee IDM */
public static final int BL_IDM = 142;
/** Survey Measurement */
public static final int SUR_MEAS = 243;
/** LINK */
public static final int LINK = 245;
private static final Mnemonic services = new Mnemonic("TCP/UDP service", Mnemonic.CASE_LOWER);
static {
services.setMaximum(0xFFFF);
services.setNumericAllowed(true);
services.add(RJE, "rje");
services.add(ECHO, "echo");
services.add(DISCARD, "discard");
services.add(USERS, "users");
services.add(DAYTIME, "daytime");
services.add(QUOTE, "quote");
services.add(CHARGEN, "chargen");
services.add(FTP_DATA, "ftp-data");
services.add(FTP, "ftp");
services.add(TELNET, "telnet");
services.add(SMTP, "smtp");
services.add(NSW_FE, "nsw-fe");
services.add(MSG_ICP, "msg-icp");
services.add(MSG_AUTH, "msg-auth");
services.add(DSP, "dsp");
services.add(TIME, "time");
services.add(RLP, "rlp");
services.add(GRAPHICS, "graphics");
services.add(NAMESERVER, "nameserver");
services.add(NICNAME, "nicname");
services.add(MPM_FLAGS, "mpm-flags");
services.add(MPM, "mpm");
services.add(MPM_SND, "mpm-snd");
services.add(NI_FTP, "ni-ftp");
services.add(LOGIN, "login");
services.add(LA_MAINT, "la-maint");
services.add(DOMAIN, "domain");
services.add(ISI_GL, "isi-gl");
services.add(NI_MAIL, "ni-mail");
services.add(VIA_FTP, "via-ftp");
services.add(TACACS_DS, "tacacs-ds");
services.add(BOOTPS, "bootps");
services.add(BOOTPC, "bootpc");
services.add(TFTP, "tftp");
services.add(NETRJS_1, "netrjs-1");
services.add(NETRJS_2, "netrjs-2");
services.add(NETRJS_3, "netrjs-3");
services.add(NETRJS_4, "netrjs-4");
services.add(FINGER, "finger");
services.add(HOSTS2_NS, "hosts2-ns");
services.add(SU_MIT_TG, "su-mit-tg");
services.add(MIT_DOV, "mit-dov");
services.add(DCP, "dcp");
services.add(SUPDUP, "supdup");
services.add(SWIFT_RVF, "swift-rvf");
services.add(TACNEWS, "tacnews");
services.add(METAGRAM, "metagram");
services.add(HOSTNAME, "hostname");
services.add(ISO_TSAP, "iso-tsap");
services.add(X400, "x400");
services.add(X400_SND, "x400-snd");
services.add(CSNET_NS, "csnet-ns");
services.add(RTELNET, "rtelnet");
services.add(POP_2, "pop-2");
services.add(SUNRPC, "sunrpc");
services.add(AUTH, "auth");
services.add(SFTP, "sftp");
services.add(UUCP_PATH, "uucp-path");
services.add(NNTP, "nntp");
services.add(ERPC, "erpc");
services.add(NTP, "ntp");
services.add(LOCUS_MAP, "locus-map");
services.add(LOCUS_CON, "locus-con");
services.add(PWDGEN, "pwdgen");
services.add(CISCO_FNA, "cisco-fna");
services.add(CISCO_TNA, "cisco-tna");
services.add(CISCO_SYS, "cisco-sys");
services.add(STATSRV, "statsrv");
services.add(INGRES_NET, "ingres-net");
services.add(LOC_SRV, "loc-srv");
services.add(PROFILE, "profile");
services.add(NETBIOS_NS, "netbios-ns");
services.add(NETBIOS_DGM, "netbios-dgm");
services.add(NETBIOS_SSN, "netbios-ssn");
services.add(EMFIS_DATA, "emfis-data");
services.add(EMFIS_CNTL, "emfis-cntl");
services.add(BL_IDM, "bl-idm");
services.add(SUR_MEAS, "sur-meas");
services.add(LINK, "link");
}
/** Converts a TCP/UDP service port number into its textual representation. */
public static String string(int type) {
return services.getText(type);
}
/**
* Converts a textual representation of a TCP/UDP service into its port number. Integers in the
* range 0..65535 are also accepted.
*
* @param s The textual representation of the service.
* @return The port number, or -1 on error.
*/
public static int value(String s) {
return services.getValue(s);
}
}
private byte[] address;
private int protocol;
private int[] services;
WKSRecord() {}
/**
* Creates a WKS Record from the given data
*
* @param address The IP address
* @param protocol The IP protocol number
* @param services An array of supported services, represented by port number.
*/
public WKSRecord(
Name name, int dclass, long ttl, InetAddress address, int protocol, int[] services) {
super(name, Type.WKS, dclass, ttl);
if (Address.familyOf(address) != Address.IPv4) {
throw new IllegalArgumentException("invalid IPv4 address");
}
this.address = address.getAddress();
this.protocol = checkU8("protocol", protocol);
for (int service : services) {
checkU16("service", service);
}
this.services = new int[services.length];
System.arraycopy(services, 0, this.services, 0, services.length);
Arrays.sort(this.services);
}
@Override
protected void rrFromWire(DNSInput in) throws IOException {
address = in.readByteArray(4);
protocol = in.readU8();
byte[] array = in.readByteArray();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < 8; j++) {
int octet = array[i] & 0xFF;
if ((octet & (1 << (7 - j))) != 0) {
list.add(i * 8 + j);
}
}
}
services = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
services[i] = list.get(i);
}
}
@Override
protected void rdataFromString(Tokenizer st, Name origin) throws IOException {
String s = st.getString();
address = Address.toByteArray(s, Address.IPv4);
if (address == null) {
throw st.exception("invalid address");
}
s = st.getString();
protocol = Protocol.value(s);
if (protocol < 0) {
throw st.exception("Invalid IP protocol: " + s);
}
List<Integer> list = new ArrayList<>();
while (true) {
Tokenizer.Token t = st.get();
if (!t.isString()) {
break;
}
int service = Service.value(t.value());
if (service < 0) {
throw st.exception("Invalid TCP/UDP service: " + t.value());
}
list.add(service);
}
st.unget();
services = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
services[i] = list.get(i);
}
}
/** Converts rdata to a String */
@Override
protected String rrToString() {
StringBuilder sb = new StringBuilder();
sb.append(Address.toDottedQuad(address));
sb.append(" ");
sb.append(protocol);
for (int service : services) {
sb.append(" ").append(service);
}
return sb.toString();
}
/** Returns the IP address. */
public InetAddress getAddress() {
try {
return InetAddress.getByAddress(address);
} catch (UnknownHostException e) {
return null;
}
}
/** Returns the IP protocol. */
public int getProtocol() {
return protocol;
}
/** Returns the services provided by the host on the specified address. */
public int[] getServices() {
return services;
}
@Override
protected void rrToWire(DNSOutput out, Compression c, boolean canonical) {
out.writeByteArray(address);
out.writeU8(protocol);
int highestPort = services[services.length - 1];
byte[] array = new byte[highestPort / 8 + 1];
for (int port : services) {
array[port / 8] |= 1 << (7 - port % 8);
}
out.writeByteArray(array);
}
}
| dnsjava/dnsjava | src/main/java/org/xbill/DNS/WKSRecord.java | 6,662 | /** Internet Group Management */ | block_comment | nl | // SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)
package org.xbill.DNS;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Well Known Services - Lists services offered by this host.
*
* @author Brian Wellington
* @see <a href="https://tools.ietf.org/html/rfc1035">RFC 1035: Domain Names - Implementation and
* Specification</a>
*/
public class WKSRecord extends Record {
/**
* IP protocol identifiers. This is basically copied out of RFC 1010.
*
* @see <a href="https://tools.ietf.org/html/rfc1010">RFC 1010: Assigned Numbers</a>
*/
public static class Protocol {
private Protocol() {}
/** Internet Control Message */
public static final int ICMP = 1;
/** Internet Group Management<SUF>*/
public static final int IGMP = 2;
/** Gateway-to-Gateway */
public static final int GGP = 3;
/** Stream */
public static final int ST = 5;
/** Transmission Control */
public static final int TCP = 6;
/** UCL */
public static final int UCL = 7;
/** Exterior Gateway Protocol */
public static final int EGP = 8;
/** any private interior gateway */
public static final int IGP = 9;
/** BBN RCC Monitoring */
public static final int BBN_RCC_MON = 10;
/** Network Voice Protocol */
public static final int NVP_II = 11;
/** PUP */
public static final int PUP = 12;
/** ARGUS */
public static final int ARGUS = 13;
/** EMCON */
public static final int EMCON = 14;
/** Cross Net Debugger */
public static final int XNET = 15;
/** Chaos */
public static final int CHAOS = 16;
/** User Datagram */
public static final int UDP = 17;
/** Multiplexing */
public static final int MUX = 18;
/** DCN Measurement Subsystems */
public static final int DCN_MEAS = 19;
/** Host Monitoring */
public static final int HMP = 20;
/** Packet Radio Measurement */
public static final int PRM = 21;
/** XEROX NS IDP */
public static final int XNS_IDP = 22;
/** Trunk-1 */
public static final int TRUNK_1 = 23;
/** Trunk-2 */
public static final int TRUNK_2 = 24;
/** Leaf-1 */
public static final int LEAF_1 = 25;
/** Leaf-2 */
public static final int LEAF_2 = 26;
/** Reliable Data Protocol */
public static final int RDP = 27;
/** Internet Reliable Transaction */
public static final int IRTP = 28;
/** ISO Transport Protocol Class 4 */
public static final int ISO_TP4 = 29;
/** Bulk Data Transfer Protocol */
public static final int NETBLT = 30;
/** MFE Network Services Protocol */
public static final int MFE_NSP = 31;
/** MERIT Internodal Protocol */
public static final int MERIT_INP = 32;
/** Sequential Exchange Protocol */
public static final int SEP = 33;
/** CFTP */
public static final int CFTP = 62;
/** SATNET and Backroom EXPAK */
public static final int SAT_EXPAK = 64;
/** MIT Subnet Support */
public static final int MIT_SUBNET = 65;
/** MIT Remote Virtual Disk Protocol */
public static final int RVD = 66;
/** Internet Pluribus Packet Core */
public static final int IPPC = 67;
/** SATNET Monitoring */
public static final int SAT_MON = 69;
/** Internet Packet Core Utility */
public static final int IPCV = 71;
/** Backroom SATNET Monitoring */
public static final int BR_SAT_MON = 76;
/** WIDEBAND Monitoring */
public static final int WB_MON = 78;
/** WIDEBAND EXPAK */
public static final int WB_EXPAK = 79;
private static final Mnemonic protocols = new Mnemonic("IP protocol", Mnemonic.CASE_LOWER);
static {
protocols.setMaximum(0xFF);
protocols.setNumericAllowed(true);
protocols.add(ICMP, "icmp");
protocols.add(IGMP, "igmp");
protocols.add(GGP, "ggp");
protocols.add(ST, "st");
protocols.add(TCP, "tcp");
protocols.add(UCL, "ucl");
protocols.add(EGP, "egp");
protocols.add(IGP, "igp");
protocols.add(BBN_RCC_MON, "bbn-rcc-mon");
protocols.add(NVP_II, "nvp-ii");
protocols.add(PUP, "pup");
protocols.add(ARGUS, "argus");
protocols.add(EMCON, "emcon");
protocols.add(XNET, "xnet");
protocols.add(CHAOS, "chaos");
protocols.add(UDP, "udp");
protocols.add(MUX, "mux");
protocols.add(DCN_MEAS, "dcn-meas");
protocols.add(HMP, "hmp");
protocols.add(PRM, "prm");
protocols.add(XNS_IDP, "xns-idp");
protocols.add(TRUNK_1, "trunk-1");
protocols.add(TRUNK_2, "trunk-2");
protocols.add(LEAF_1, "leaf-1");
protocols.add(LEAF_2, "leaf-2");
protocols.add(RDP, "rdp");
protocols.add(IRTP, "irtp");
protocols.add(ISO_TP4, "iso-tp4");
protocols.add(NETBLT, "netblt");
protocols.add(MFE_NSP, "mfe-nsp");
protocols.add(MERIT_INP, "merit-inp");
protocols.add(SEP, "sep");
protocols.add(CFTP, "cftp");
protocols.add(SAT_EXPAK, "sat-expak");
protocols.add(MIT_SUBNET, "mit-subnet");
protocols.add(RVD, "rvd");
protocols.add(IPPC, "ippc");
protocols.add(SAT_MON, "sat-mon");
protocols.add(IPCV, "ipcv");
protocols.add(BR_SAT_MON, "br-sat-mon");
protocols.add(WB_MON, "wb-mon");
protocols.add(WB_EXPAK, "wb-expak");
}
/** Converts an IP protocol value into its textual representation */
public static String string(int type) {
return protocols.getText(type);
}
/**
* Converts a textual representation of an IP protocol into its numeric code. Integers in the
* range 0..255 are also accepted.
*
* @param s The textual representation of the protocol
* @return The protocol code, or -1 on error.
*/
public static int value(String s) {
return protocols.getValue(s);
}
}
public static class Service {
/**
* TCP/UDP services. This is basically copied out of RFC 1010, with MIT-ML-DEV removed, as it is
* not unique, and the description of SWIFT-RVF fixed.
*/
private Service() {}
/** Remote Job Entry */
public static final int RJE = 5;
/** Echo */
public static final int ECHO = 7;
/** Discard */
public static final int DISCARD = 9;
/** Active Users */
public static final int USERS = 11;
/** Daytime */
public static final int DAYTIME = 13;
/** Quote of the Day */
public static final int QUOTE = 17;
/** Character Generator */
public static final int CHARGEN = 19;
/** File Transfer [Default Data] */
public static final int FTP_DATA = 20;
/** File Transfer [Control] */
public static final int FTP = 21;
/** Telnet */
public static final int TELNET = 23;
/** Simple Mail Transfer */
public static final int SMTP = 25;
/** NSW User System FE */
public static final int NSW_FE = 27;
/** MSG ICP */
public static final int MSG_ICP = 29;
/** MSG Authentication */
public static final int MSG_AUTH = 31;
/** Display Support Protocol */
public static final int DSP = 33;
/** Time */
public static final int TIME = 37;
/** Resource Location Protocol */
public static final int RLP = 39;
/** Graphics */
public static final int GRAPHICS = 41;
/** Host Name Server */
public static final int NAMESERVER = 42;
/** Who Is */
public static final int NICNAME = 43;
/** MPM FLAGS Protocol */
public static final int MPM_FLAGS = 44;
/** Message Processing Module [recv] */
public static final int MPM = 45;
/** MPM [default send] */
public static final int MPM_SND = 46;
/** NI FTP */
public static final int NI_FTP = 47;
/** Login Host Protocol */
public static final int LOGIN = 49;
/** IMP Logical Address Maintenance */
public static final int LA_MAINT = 51;
/** Domain Name Server */
public static final int DOMAIN = 53;
/** ISI Graphics Language */
public static final int ISI_GL = 55;
/** NI MAIL */
public static final int NI_MAIL = 61;
/** VIA Systems - FTP */
public static final int VIA_FTP = 63;
/** TACACS-Database Service */
public static final int TACACS_DS = 65;
/** Bootstrap Protocol Server */
public static final int BOOTPS = 67;
/** Bootstrap Protocol Client */
public static final int BOOTPC = 68;
/** Trivial File Transfer */
public static final int TFTP = 69;
/** Remote Job Service */
public static final int NETRJS_1 = 71;
/** Remote Job Service */
public static final int NETRJS_2 = 72;
/** Remote Job Service */
public static final int NETRJS_3 = 73;
/** Remote Job Service */
public static final int NETRJS_4 = 74;
/** Finger */
public static final int FINGER = 79;
/** HOSTS2 Name Server */
public static final int HOSTS2_NS = 81;
/** SU/MIT Telnet Gateway */
public static final int SU_MIT_TG = 89;
/** MIT Dover Spooler */
public static final int MIT_DOV = 91;
/** Device Control Protocol */
public static final int DCP = 93;
/** SUPDUP */
public static final int SUPDUP = 95;
/** Swift Remote Virtual File Protocol */
public static final int SWIFT_RVF = 97;
/** TAC News */
public static final int TACNEWS = 98;
/** Metagram Relay */
public static final int METAGRAM = 99;
/** NIC Host Name Server */
public static final int HOSTNAME = 101;
/** ISO-TSAP */
public static final int ISO_TSAP = 102;
/** X400 */
public static final int X400 = 103;
/** X400-SND */
public static final int X400_SND = 104;
/** Mailbox Name Nameserver */
public static final int CSNET_NS = 105;
/** Remote Telnet Service */
public static final int RTELNET = 107;
/** Post Office Protocol - Version 2 */
public static final int POP_2 = 109;
/** SUN Remote Procedure Call */
public static final int SUNRPC = 111;
/** Authentication Service */
public static final int AUTH = 113;
/** Simple File Transfer Protocol */
public static final int SFTP = 115;
/** UUCP Path Service */
public static final int UUCP_PATH = 117;
/** Network News Transfer Protocol */
public static final int NNTP = 119;
/** HYDRA Expedited Remote Procedure */
public static final int ERPC = 121;
/** Network Time Protocol */
public static final int NTP = 123;
/** Locus PC-Interface Net Map Server */
public static final int LOCUS_MAP = 125;
/** Locus PC-Interface Conn Server */
public static final int LOCUS_CON = 127;
/** Password Generator Protocol */
public static final int PWDGEN = 129;
/** CISCO FNATIVE */
public static final int CISCO_FNA = 130;
/** CISCO TNATIVE */
public static final int CISCO_TNA = 131;
/** CISCO SYSMAINT */
public static final int CISCO_SYS = 132;
/** Statistics Service */
public static final int STATSRV = 133;
/** INGRES-NET Service */
public static final int INGRES_NET = 134;
/** Location Service */
public static final int LOC_SRV = 135;
/** PROFILE Naming System */
public static final int PROFILE = 136;
/** NETBIOS Name Service */
public static final int NETBIOS_NS = 137;
/** NETBIOS Datagram Service */
public static final int NETBIOS_DGM = 138;
/** NETBIOS Session Service */
public static final int NETBIOS_SSN = 139;
/** EMFIS Data Service */
public static final int EMFIS_DATA = 140;
/** EMFIS Control Service */
public static final int EMFIS_CNTL = 141;
/** Britton-Lee IDM */
public static final int BL_IDM = 142;
/** Survey Measurement */
public static final int SUR_MEAS = 243;
/** LINK */
public static final int LINK = 245;
private static final Mnemonic services = new Mnemonic("TCP/UDP service", Mnemonic.CASE_LOWER);
static {
services.setMaximum(0xFFFF);
services.setNumericAllowed(true);
services.add(RJE, "rje");
services.add(ECHO, "echo");
services.add(DISCARD, "discard");
services.add(USERS, "users");
services.add(DAYTIME, "daytime");
services.add(QUOTE, "quote");
services.add(CHARGEN, "chargen");
services.add(FTP_DATA, "ftp-data");
services.add(FTP, "ftp");
services.add(TELNET, "telnet");
services.add(SMTP, "smtp");
services.add(NSW_FE, "nsw-fe");
services.add(MSG_ICP, "msg-icp");
services.add(MSG_AUTH, "msg-auth");
services.add(DSP, "dsp");
services.add(TIME, "time");
services.add(RLP, "rlp");
services.add(GRAPHICS, "graphics");
services.add(NAMESERVER, "nameserver");
services.add(NICNAME, "nicname");
services.add(MPM_FLAGS, "mpm-flags");
services.add(MPM, "mpm");
services.add(MPM_SND, "mpm-snd");
services.add(NI_FTP, "ni-ftp");
services.add(LOGIN, "login");
services.add(LA_MAINT, "la-maint");
services.add(DOMAIN, "domain");
services.add(ISI_GL, "isi-gl");
services.add(NI_MAIL, "ni-mail");
services.add(VIA_FTP, "via-ftp");
services.add(TACACS_DS, "tacacs-ds");
services.add(BOOTPS, "bootps");
services.add(BOOTPC, "bootpc");
services.add(TFTP, "tftp");
services.add(NETRJS_1, "netrjs-1");
services.add(NETRJS_2, "netrjs-2");
services.add(NETRJS_3, "netrjs-3");
services.add(NETRJS_4, "netrjs-4");
services.add(FINGER, "finger");
services.add(HOSTS2_NS, "hosts2-ns");
services.add(SU_MIT_TG, "su-mit-tg");
services.add(MIT_DOV, "mit-dov");
services.add(DCP, "dcp");
services.add(SUPDUP, "supdup");
services.add(SWIFT_RVF, "swift-rvf");
services.add(TACNEWS, "tacnews");
services.add(METAGRAM, "metagram");
services.add(HOSTNAME, "hostname");
services.add(ISO_TSAP, "iso-tsap");
services.add(X400, "x400");
services.add(X400_SND, "x400-snd");
services.add(CSNET_NS, "csnet-ns");
services.add(RTELNET, "rtelnet");
services.add(POP_2, "pop-2");
services.add(SUNRPC, "sunrpc");
services.add(AUTH, "auth");
services.add(SFTP, "sftp");
services.add(UUCP_PATH, "uucp-path");
services.add(NNTP, "nntp");
services.add(ERPC, "erpc");
services.add(NTP, "ntp");
services.add(LOCUS_MAP, "locus-map");
services.add(LOCUS_CON, "locus-con");
services.add(PWDGEN, "pwdgen");
services.add(CISCO_FNA, "cisco-fna");
services.add(CISCO_TNA, "cisco-tna");
services.add(CISCO_SYS, "cisco-sys");
services.add(STATSRV, "statsrv");
services.add(INGRES_NET, "ingres-net");
services.add(LOC_SRV, "loc-srv");
services.add(PROFILE, "profile");
services.add(NETBIOS_NS, "netbios-ns");
services.add(NETBIOS_DGM, "netbios-dgm");
services.add(NETBIOS_SSN, "netbios-ssn");
services.add(EMFIS_DATA, "emfis-data");
services.add(EMFIS_CNTL, "emfis-cntl");
services.add(BL_IDM, "bl-idm");
services.add(SUR_MEAS, "sur-meas");
services.add(LINK, "link");
}
/** Converts a TCP/UDP service port number into its textual representation. */
public static String string(int type) {
return services.getText(type);
}
/**
* Converts a textual representation of a TCP/UDP service into its port number. Integers in the
* range 0..65535 are also accepted.
*
* @param s The textual representation of the service.
* @return The port number, or -1 on error.
*/
public static int value(String s) {
return services.getValue(s);
}
}
private byte[] address;
private int protocol;
private int[] services;
WKSRecord() {}
/**
* Creates a WKS Record from the given data
*
* @param address The IP address
* @param protocol The IP protocol number
* @param services An array of supported services, represented by port number.
*/
public WKSRecord(
Name name, int dclass, long ttl, InetAddress address, int protocol, int[] services) {
super(name, Type.WKS, dclass, ttl);
if (Address.familyOf(address) != Address.IPv4) {
throw new IllegalArgumentException("invalid IPv4 address");
}
this.address = address.getAddress();
this.protocol = checkU8("protocol", protocol);
for (int service : services) {
checkU16("service", service);
}
this.services = new int[services.length];
System.arraycopy(services, 0, this.services, 0, services.length);
Arrays.sort(this.services);
}
@Override
protected void rrFromWire(DNSInput in) throws IOException {
address = in.readByteArray(4);
protocol = in.readU8();
byte[] array = in.readByteArray();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < 8; j++) {
int octet = array[i] & 0xFF;
if ((octet & (1 << (7 - j))) != 0) {
list.add(i * 8 + j);
}
}
}
services = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
services[i] = list.get(i);
}
}
@Override
protected void rdataFromString(Tokenizer st, Name origin) throws IOException {
String s = st.getString();
address = Address.toByteArray(s, Address.IPv4);
if (address == null) {
throw st.exception("invalid address");
}
s = st.getString();
protocol = Protocol.value(s);
if (protocol < 0) {
throw st.exception("Invalid IP protocol: " + s);
}
List<Integer> list = new ArrayList<>();
while (true) {
Tokenizer.Token t = st.get();
if (!t.isString()) {
break;
}
int service = Service.value(t.value());
if (service < 0) {
throw st.exception("Invalid TCP/UDP service: " + t.value());
}
list.add(service);
}
st.unget();
services = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
services[i] = list.get(i);
}
}
/** Converts rdata to a String */
@Override
protected String rrToString() {
StringBuilder sb = new StringBuilder();
sb.append(Address.toDottedQuad(address));
sb.append(" ");
sb.append(protocol);
for (int service : services) {
sb.append(" ").append(service);
}
return sb.toString();
}
/** Returns the IP address. */
public InetAddress getAddress() {
try {
return InetAddress.getByAddress(address);
} catch (UnknownHostException e) {
return null;
}
}
/** Returns the IP protocol. */
public int getProtocol() {
return protocol;
}
/** Returns the services provided by the host on the specified address. */
public int[] getServices() {
return services;
}
@Override
protected void rrToWire(DNSOutput out, Compression c, boolean canonical) {
out.writeByteArray(address);
out.writeU8(protocol);
int highestPort = services[services.length - 1];
byte[] array = new byte[highestPort / 8 + 1];
for (int port : services) {
array[port / 8] |= 1 << (7 - port % 8);
}
out.writeByteArray(array);
}
}
| False |
1,216 | 42865_0 | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| NoNamer777/hva-tic-tac-toe | src/controllers/PlayController.java | 900 | /**
* Zorgt voor de setup en het uitvoeren het spel
*
* @author Miguel
*/ | block_comment | nl | package controllers;
import data.ReadData;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import models.Player;
import views.CreateNewPlayerView;
import views.TicTacToeView;
/**
* Zorgt voor de<SUF>*/
public class PlayController {
private BorderPane borderPane;
private Player player1;
private Player player2;
private ComboBox p1ComboBox;
private ComboBox p2ComboBox;
private Button playButton;
private ObservableList players;
/**
* initialiseerd de play controller
*/
public void initialize() {
CreateNewPlayerController createNewPlayerController = new CreateNewPlayerController();
CreateNewPlayerView createNewPlayerView = new CreateNewPlayerView(createNewPlayerController);
players = FXCollections.observableList(ReadData.readDataFile("Player_Archive.dat"));
p1ComboBox.setItems(players);
p1ComboBox.setValue("Choose");
p1ComboBox.setOnAction(t -> {
onComboBoxChange();
});
p2ComboBox.setItems(players);
p2ComboBox.setValue("Choose");
p2ComboBox.setOnAction(t -> {
onComboBoxChange();
});
playButton.setOnAction(t -> {
System.out.println("play game");
TicTacToeController ticTacToeController = new TicTacToeController(player1, player2);
TicTacToeView ticTacToeView = new TicTacToeView(ticTacToeController);
borderPane = ticTacToeView.changeBorderPane(borderPane);
});
}
/**
* veranderd de visibility als de players een waarde hebben die niet hetzelfde zijn
*/
private void onComboBoxChange() {
if (!p1ComboBox.getValue().toString().equals("Choose")) {
player1 = (Player) p1ComboBox.getValue();
}
if (!p2ComboBox.getValue().toString().equals("Choose")) {
player2 = (Player) p2ComboBox.getValue();
}
playButton.setDisable(!(player1 != null && player2 != null && !player1.equals(player2)));
}
/**
* setter voor p1 combobox
* @param p1ComboBox
*/
public void setP1ComboBox(ComboBox p1ComboBox) {
this.p1ComboBox = p1ComboBox;
}
/**
* setter voor p2 combobox
* @param p2ComboBox
*/
public void setP2ComboBox(ComboBox p2ComboBox) {
this.p2ComboBox = p2ComboBox;
}
/**
* setter voor play button
* @param playButton
*/
public void setPlayButton(Button playButton) {
this.playButton = playButton;
}
/**
* setter voor borderpane
* @param borderPane
*/
public void setBorderPane(BorderPane borderPane) {
this.borderPane = borderPane;
}
}
| True |
3,400 | 43884_1 | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | krisBroekstra1/Nerdygadgets | src/nerdygadgets/backoffice/main/JDBC/Driver.java | 1,876 | //Zo lees je de gegevens uit | line_comment | nl | package nerdygadgets.backoffice.main.JDBC;
import nerdygadgets.backoffice.main.data.Shaa256;
import java.sql.*;
public class Driver {
public static void main(String[] args) {
}
//Functies
//Functie adressen
public static ResultSet adressen() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT DeliveryInstructions FROM invoices");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees<SUF>
/*ResultSet myRs = Driver.adressen();
try {
while (myRs.next()) {
System.out.println(myRs.getString("DeliveryInstructions"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie medewerkers
public static ResultSet medewerkers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT FullName, EmailAddress, PhoneNumber FROM people");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet login(String username, String password) {
try {
password = Shaa256.toHexString(Shaa256.getSHA(password));
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
String sql = "SELECT COUNT(*) FROM people WHERE LogonName = ? AND fixedpassword = ?";
PreparedStatement ps = myConn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ResultSet myRs = ps.executeQuery();
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//Zo lees je de gegevens uit
/*ResultSet myRs = Driver.medewerkers();
try {
while (myRs.next()) {
System.out.println(myRs.getString("FullName"));
System.out.println(myRs.getString("EmailAddress"));
System.out.println(myRs.getString("PhoneNumber"));
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}*/
//Functie Orders
public static ResultSet orders() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.OrderID, c.CustomerName, ci.Cityname FROM orders o LEFT JOIN customers c ON o.CustomerID = c.CustomerID LEFT JOIN cities ci ON c.DeliveryCityID = ci.CityID ORDER BY OrderID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getStock() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT o.StockItemID, o.StockItemName AS `Productnaam`, QuantityOnHand AS `Aantal`FROM wideworldimporters.stockitems o LEFT JOIN stockitemholdings sh ON o.StockItemID = sh.StockItemID ORDER BY o.StockItemID");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static ResultSet getCustomers() {
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("SELECT * FROM customer_ned");
return myRs;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void UpdateCustomer(String id, String cust, String city, String adres, String post, String email, String tel){
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query = "UPDATE customer_ned SET CustomerName = ?, City = ?, Adres = ?, Postalcode = ?, EmailAddress = ?, TelephoneNumber = ? WHERE CustomerID = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, cust);
preparedStmt.setString(2, city);
preparedStmt.setString(3, adres);
preparedStmt.setString(4, post);
preparedStmt.setString(5, email);
preparedStmt.setString(6, tel);
preparedStmt.setString(7, id);
// execute the java preparedstatement
int rowsAffected = preparedStmt.executeUpdate();
System.out.println("Hoeveelheid rows veranderd: "+rowsAffected);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void UpdateVoorraad(String id, String itemname, String Quantity){ //Moet nog iets gebeuren als 1 niet werkt
try {
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost/wideworldimporters", "root", "");
// create the java mysql update preparedstatement
String query1 = "UPDATE stockitems SET StockItemName = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt1 = myConn.prepareStatement(query1);
preparedStmt1.setString(1, itemname);
preparedStmt1.setString(2, id);
int rowsAffected1 = preparedStmt1.executeUpdate();
String query2 = "UPDATE stockitemholdings SET QuantityOnHand = ? WHERE StockItemId = ?";
PreparedStatement preparedStmt2 = myConn.prepareStatement(query2);
preparedStmt2.setString(1, Quantity);
preparedStmt2.setString(2, id);
int rowsAffected2 = preparedStmt2.executeUpdate();
System.out.println("Hoeveelheid rows veranderd in tabel 1: "+rowsAffected1);
System.out.println("Hoeveelheid rows veranderd in tabel 2: "+rowsAffected2);
} catch (Exception e) {
e.printStackTrace();
}
}
} | True |
4,369 | 60894_0 | package org.robolectric.gradle;
import static org.gradle.api.internal.artifacts.ArtifactAttributes.ARTIFACT_FORMAT;
import com.android.build.gradle.internal.dependency.ExtractAarTransform;
import com.google.common.base.Joiner;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.compile.JavaCompile;
/** Resolve aar dependencies into jars for non-Android projects. */
public class AarDepsPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project
.getDependencies()
.registerTransform(
reg -> {
reg.getFrom().attribute(ARTIFACT_FORMAT, "aar");
reg.getTo().attribute(ARTIFACT_FORMAT, "jar");
reg.artifactTransform(ClassesJarExtractor.class);
});
project.afterEvaluate(
p ->
project
.getConfigurations()
.forEach(
c -> {
// I suspect we're meant to use the org.gradle.usage attribute, but this
// works.
if (c.getName().endsWith("Classpath")) {
c.attributes(cfgAttrs -> cfgAttrs.attribute(ARTIFACT_FORMAT, "jar"));
}
}));
// warn if any AARs do make it through somehow; there must be a gradle configuration
// that isn't matched above.
project
.getTasks()
.withType(JavaCompile.class)
.all(
t -> {
t.doFirst(
task -> {
List<File> aarFiles = findAarFiles(t.getClasspath());
if (!aarFiles.isEmpty()) {
throw new IllegalStateException(
"AARs on classpath: " + Joiner.on("\n ").join(aarFiles));
}
});
});
}
private List<File> findAarFiles(FileCollection files) {
List<File> bad = new ArrayList<>();
for (File file : files.getFiles()) {
if (file.getName().toLowerCase().endsWith(".aar")) {
bad.add(file);
}
}
return bad;
}
static class ClassesJarExtractor extends ExtractAarTransform {
@Override
public List<File> transform(File input) {
List<File> out = super.transform(input);
File classesJar = new File(out.get(0), "jars/classes.jar");
// jar needs a quasi-unique name or IntelliJ Gradle/Android plugins get confused...
File renamed = new File(classesJar.getParent(), input.getName().replace(".aar", ".jar"));
classesJar.renameTo(renamed);
return Collections.singletonList(renamed);
}
}
}
| spotify/robolectric | buildSrc/src/main/groovy/org/robolectric/gradle/AarDepsPlugin.java | 811 | /** Resolve aar dependencies into jars for non-Android projects. */ | block_comment | nl | package org.robolectric.gradle;
import static org.gradle.api.internal.artifacts.ArtifactAttributes.ARTIFACT_FORMAT;
import com.android.build.gradle.internal.dependency.ExtractAarTransform;
import com.google.common.base.Joiner;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.compile.JavaCompile;
/** Resolve aar dependencies<SUF>*/
public class AarDepsPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project
.getDependencies()
.registerTransform(
reg -> {
reg.getFrom().attribute(ARTIFACT_FORMAT, "aar");
reg.getTo().attribute(ARTIFACT_FORMAT, "jar");
reg.artifactTransform(ClassesJarExtractor.class);
});
project.afterEvaluate(
p ->
project
.getConfigurations()
.forEach(
c -> {
// I suspect we're meant to use the org.gradle.usage attribute, but this
// works.
if (c.getName().endsWith("Classpath")) {
c.attributes(cfgAttrs -> cfgAttrs.attribute(ARTIFACT_FORMAT, "jar"));
}
}));
// warn if any AARs do make it through somehow; there must be a gradle configuration
// that isn't matched above.
project
.getTasks()
.withType(JavaCompile.class)
.all(
t -> {
t.doFirst(
task -> {
List<File> aarFiles = findAarFiles(t.getClasspath());
if (!aarFiles.isEmpty()) {
throw new IllegalStateException(
"AARs on classpath: " + Joiner.on("\n ").join(aarFiles));
}
});
});
}
private List<File> findAarFiles(FileCollection files) {
List<File> bad = new ArrayList<>();
for (File file : files.getFiles()) {
if (file.getName().toLowerCase().endsWith(".aar")) {
bad.add(file);
}
}
return bad;
}
static class ClassesJarExtractor extends ExtractAarTransform {
@Override
public List<File> transform(File input) {
List<File> out = super.transform(input);
File classesJar = new File(out.get(0), "jars/classes.jar");
// jar needs a quasi-unique name or IntelliJ Gradle/Android plugins get confused...
File renamed = new File(classesJar.getParent(), input.getName().replace(".aar", ".jar"));
classesJar.renameTo(renamed);
return Collections.singletonList(renamed);
}
}
}
| False |
2,215 | 29018_8 | /*
* EigenDecomposition.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.substmodel;
import java.io.Serializable;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @Author Marc A. Suchard
* @version $Id$
*/
public class EigenDecomposition implements Serializable {
public EigenDecomposition(double[] evec, double[] ievc, double[] eval) {
Evec = evec;
Ievc = ievc;
Eval = eval;
}
public EigenDecomposition copy() {
double[] evec = Evec.clone();
double[] ievc = Ievc.clone();
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
public EigenDecomposition transpose() {
// note: exchange e/ivec
int dim = (int) Math.sqrt(Ievc.length);
double[] evec = Ievc.clone();
transposeInPlace(evec, dim);
double[] ievc = Evec.clone();
transposeInPlace(ievc, dim);
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
private static void transposeInPlace(double[] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int index1 = i * n + j;
int index2 = j * n + i;
double temp = matrix[index1];
matrix[index1] = matrix[index2];
matrix[index2] = temp;
}
}
}
/**
* This function returns the Eigen vectors.
* @return the array
*/
public final double[] getEigenVectors() {
return Evec;
}
/**
* This function returns the inverse Eigen vectors.
* @return the array
*/
public final double[] getInverseEigenVectors() {
return Ievc;
}
/**
* This function returns the Eigen values.
* @return the Eigen values
*/
public final double[] getEigenValues() {
return Eval;
}
/**
* This function returns the normalization factor
* @return normalization factor
*/
public final double getNormalization() { return normalization; }
/**
* This function rescales the eigen values; this is more stable than
* rescaling the original Q matrix, also O(stateCount) instead of O(stateCount^2)
*/
public void normalizeEigenValues(double scale) {
this.normalization = scale;
int dim = Eval.length;
for (int i = 0; i < dim; i++) {
Eval[i] /= scale;
}
}
// Eigenvalues, eigenvectors, and inverse eigenvectors
private final double[] Evec;
private final double[] Ievc;
private final double[] Eval;
private double normalization = 1.0;
}
| beast-dev/beast-mcmc | src/dr/evomodel/substmodel/EigenDecomposition.java | 1,060 | // Eigenvalues, eigenvectors, and inverse eigenvectors | line_comment | nl | /*
* EigenDecomposition.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.substmodel;
import java.io.Serializable;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @Author Marc A. Suchard
* @version $Id$
*/
public class EigenDecomposition implements Serializable {
public EigenDecomposition(double[] evec, double[] ievc, double[] eval) {
Evec = evec;
Ievc = ievc;
Eval = eval;
}
public EigenDecomposition copy() {
double[] evec = Evec.clone();
double[] ievc = Ievc.clone();
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
public EigenDecomposition transpose() {
// note: exchange e/ivec
int dim = (int) Math.sqrt(Ievc.length);
double[] evec = Ievc.clone();
transposeInPlace(evec, dim);
double[] ievc = Evec.clone();
transposeInPlace(ievc, dim);
double[] eval = Eval.clone();
return new EigenDecomposition(evec, ievc, eval);
}
private static void transposeInPlace(double[] matrix, int n) {
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int index1 = i * n + j;
int index2 = j * n + i;
double temp = matrix[index1];
matrix[index1] = matrix[index2];
matrix[index2] = temp;
}
}
}
/**
* This function returns the Eigen vectors.
* @return the array
*/
public final double[] getEigenVectors() {
return Evec;
}
/**
* This function returns the inverse Eigen vectors.
* @return the array
*/
public final double[] getInverseEigenVectors() {
return Ievc;
}
/**
* This function returns the Eigen values.
* @return the Eigen values
*/
public final double[] getEigenValues() {
return Eval;
}
/**
* This function returns the normalization factor
* @return normalization factor
*/
public final double getNormalization() { return normalization; }
/**
* This function rescales the eigen values; this is more stable than
* rescaling the original Q matrix, also O(stateCount) instead of O(stateCount^2)
*/
public void normalizeEigenValues(double scale) {
this.normalization = scale;
int dim = Eval.length;
for (int i = 0; i < dim; i++) {
Eval[i] /= scale;
}
}
// Eigenvalues, eigenvectors,<SUF>
private final double[] Evec;
private final double[] Ievc;
private final double[] Eval;
private double normalization = 1.0;
}
| False |
792 | 175575_7 | import java.util.Scanner;_x000D_
_x000D_
public class Exercise19 {_x000D_
public static void main(String[] args) {_x000D_
// INTERLEAVE_x000D_
Scanner console = new Scanner(System.in);_x000D_
_x000D_
System.out.print("First string: ");_x000D_
String first = console.nextLine();_x000D_
_x000D_
System.out.print("Second string: ");_x000D_
String second = console.nextLine();_x000D_
_x000D_
// 1. Write a loop to interleave two strings to form a new string._x000D_
// To interleave, during each loop take one character from the first string and add it to the result_x000D_
// and take one character from the second string and add it to the result._x000D_
// If there are no more characters available, don't add characters._x000D_
// 2. Print the result._x000D_
int max = Math.max(first.length(),second.length());_x000D_
String mix = "";_x000D_
for (int i = 0; i < max; i++) {_x000D_
if (i < Math.min(first.length(), second.length())) {_x000D_
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));_x000D_
continue;_x000D_
}_x000D_
if (first.length() == max){_x000D_
mix += (Character.toString((first.charAt(i))));_x000D_
}_x000D_
if (second.length() == max){_x000D_
mix += (Character.toString((second.charAt(i))));_x000D_
}_x000D_
}_x000D_
System.out.println(mix);_x000D_
_x000D_
// Examples_x000D_
// "abc", "123" -> "a1b2c3"_x000D_
// "cat", "dog" -> "cdaotg"_x000D_
// "wonder", "o" -> "woonder"_x000D_
// "B", "igstar" -> "Bigstar"_x000D_
// "", "huh?" -> "huh?"_x000D_
// "wha?", "" -> "wha?"_x000D_
}_x000D_
}_x000D_
| JacobBMitchell/java-exercises-JacobMitchell | week-01/exercises/repetition-exercises/src/Exercise19.java | 479 | // "wonder", "o" -> "woonder"_x000D_ | line_comment | nl | import java.util.Scanner;_x000D_
_x000D_
public class Exercise19 {_x000D_
public static void main(String[] args) {_x000D_
// INTERLEAVE_x000D_
Scanner console = new Scanner(System.in);_x000D_
_x000D_
System.out.print("First string: ");_x000D_
String first = console.nextLine();_x000D_
_x000D_
System.out.print("Second string: ");_x000D_
String second = console.nextLine();_x000D_
_x000D_
// 1. Write a loop to interleave two strings to form a new string._x000D_
// To interleave, during each loop take one character from the first string and add it to the result_x000D_
// and take one character from the second string and add it to the result._x000D_
// If there are no more characters available, don't add characters._x000D_
// 2. Print the result._x000D_
int max = Math.max(first.length(),second.length());_x000D_
String mix = "";_x000D_
for (int i = 0; i < max; i++) {_x000D_
if (i < Math.min(first.length(), second.length())) {_x000D_
mix += (Character.toString(first.charAt(i)) + Character.toString(second.charAt(i)));_x000D_
continue;_x000D_
}_x000D_
if (first.length() == max){_x000D_
mix += (Character.toString((first.charAt(i))));_x000D_
}_x000D_
if (second.length() == max){_x000D_
mix += (Character.toString((second.charAt(i))));_x000D_
}_x000D_
}_x000D_
System.out.println(mix);_x000D_
_x000D_
// Examples_x000D_
// "abc", "123" -> "a1b2c3"_x000D_
// "cat", "dog" -> "cdaotg"_x000D_
// "wonder", "o"<SUF>
// "B", "igstar" -> "Bigstar"_x000D_
// "", "huh?" -> "huh?"_x000D_
// "wha?", "" -> "wha?"_x000D_
}_x000D_
}_x000D_
| False |
662 | 33859_6 | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler krijgt als eerste de beurt in een nieuwe ronde
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| HUSACCT/SaccWithHusacctExample_Maven | src/main/java/nl/hu/husacct/game31/domein/ComputerSpeler.java | 2,758 | //de computerspeler krijgt als eerste de beurt in een nieuwe ronde | line_comment | nl | package nl.hu.husacct.game31.domein;
import java.util.*;
public class ComputerSpeler extends Speler{
private double[][][] kaartenTabel;
private Kaart[] kaartenIndex;
private Vector alleKaarten;
private Spel spel;
private int schuifCounter = 0;
public ComputerSpeler(String naam, int fices, Tafel tafel, Pot pot, KaartStapel kaartStapel, Spel spel)
{
super(naam,fices, tafel, pot);
this.alleKaarten = kaartStapel.getKaarten();
this.spel = spel;
vulKaartenTabel();
printTabel();
}
private void vulKaartenTabel()
{
kaartenIndex = new Kaart[32];
Vector kaarten = alleKaarten;
//kaarten ophalen en in een array plaatsen
int index = 0;
for(Iterator itr = kaarten.iterator();itr.hasNext();index++)
{
Kaart k = (Kaart) itr.next();
kaartenIndex[index] = k;
//System.out.println(index + " " + k.geefSymbool() + " " + k.geefGetal());
}
//kaartenTabel invullen, de coordinaten geven de index van de Kaart in de kaartenIndex aan
//op de locatie staat het aantal punten dat een combinatie oplevert
kaartenTabel = new double[32][32][32];
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
//niet dezelfde kaart
if(kaartenIndex[i] != kaartenIndex[j] && kaartenIndex[i] != kaartenIndex[k] && kaartenIndex[j] != kaartenIndex[k])
{
//zelfde getal
String getalK1 = kaartenIndex[i].geefGetal();
String getalK2 = kaartenIndex[j].geefGetal();
String getalK3 = kaartenIndex[k].geefGetal();
if(getalK1.equals(getalK2) && getalK1.equals(getalK3) && getalK3.equals(getalK2))
{
kaartenTabel[i][j][k] = 30.5;
}
//zelfde kleur
String symbool = kaartenIndex[i].geefSymbool();
if(symbool.equals(kaartenIndex[j].geefSymbool()) && symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(symbool.equals(kaartenIndex[j].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[j].geefWaarde();
}
else if(symbool.equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[i].geefWaarde() + kaartenIndex[k].geefWaarde();
}
else if(kaartenIndex[j].geefSymbool().equals(kaartenIndex[k].geefSymbool()))
{
kaartenTabel[i][j][k] = kaartenIndex[j].geefWaarde() + kaartenIndex[k].geefWaarde();
}
}
}
}
}
}
//de computerspeler krijgt de beurt
public void aanDeBeurt()
{
Vector opTafel = tafel.getKaarten();
Vector inHand = deelname.getKaarten();
double puntenOpTafel = zoekPunten(opTafel);
double puntenInHand = zoekPunten(inHand);
int[] indexHand = new int[3];
int[] indexTafel = new int[3];
for(int i=0;i<3;i++)
{
indexHand[i] = zoekIndex((Kaart)inHand.elementAt(i));
indexTafel[i] = zoekIndex((Kaart)opTafel.elementAt(i));
}
double[][] puntenTabel = combineer(indexHand, indexTafel);
int[] besteCoords = zoekCoordsBeste(puntenTabel);
double bestePunten = puntenTabel[besteCoords[0]][besteCoords[1]];
if(bestePunten > puntenOpTafel && bestePunten > puntenInHand)
{
//1kaart wisselen
tafel.selecteerKaart(besteCoords[1]);
deelname.selecteerKaart(besteCoords[0]);
spel.ruil1Kaart(deelname.getSelected(), tafel.getSelected());
}
else if(bestePunten < puntenOpTafel)
{
//alles wisselen
spel.ruil3Kaart();
schuifCounter = 0;
}
else if(bestePunten <= puntenInHand)
{
if(puntenInHand > 25 || schuifCounter == 2)
{
//pass
spel.pas();
}
else
{
//doorschuiven
schuifCounter++;
spel.doorSchuiven();
}
}
Vector handkaartjes = deelname.getKaarten();
for(int i=0;i<3;i++)
{
Kaart k = (Kaart)handkaartjes.elementAt(i);
System.out.println(k.geefSymbool() + " " + k.geefGetal());
}
}
//de computerspeler<SUF>
public void eersteKeerInRonde()
{
schuifCounter = 0;
Vector inHand = deelname.getKaarten();
double puntenInHand = zoekPunten(inHand);
//kan er 30.5 worden gescoord met deze kaarten?
Vector kaarten = deelname.getKaarten();
Kaart krt1 = (Kaart) kaarten.elementAt(0);
Kaart krt2 = (Kaart) kaarten.elementAt(1);
Kaart krt3 = (Kaart) kaarten.elementAt(2);
if(puntenInHand == 31.0)
{
//doorschuiven
spel.doorSchuiven();
schuifCounter++;
}
else if(puntenInHand > 25)
{
//pass
spel.pas();
}
else if(krt1.geefGetal().equals(krt2.geefGetal()) || krt1.geefGetal().equals(krt3.geefGetal()) || krt2.geefGetal().equals(krt3.geefGetal()))
{
//kaarten bekijken
//zoek beste ruil
//aanDeBeurt heeft dezelfde functionaliteiten dus roep ik die hier aan
aanDeBeurt();
}
else if(puntenInHand == 0.0)
{
spel.ruil3Kaart();
}
}
private int[] zoekCoordsBeste(double[][] puntenTabel)
{
int[] coords = new int[2];
double grootste = 0;
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
if(puntenTabel[i][j] > grootste)
{
coords[0] = i;
coords[1] = j;
}
}
}
return coords;
}
private double[][] combineer(int[] hand, int[] tafel)
{
double[][] tabel = new double[3][3];
for(int i=0;i<3;i++) //regel
{
for(int j=0;j<3;j++) //kolom
{
int[] combinatie = new int[3];
for(int k=0;k<3;k++)
{
if(k == i)
{
combinatie[k] = tafel[j];
}
else
{
combinatie[k] = hand[k];
}
}
tabel[i][j] = kaartenTabel[combinatie[0]][combinatie[1]][combinatie[2]];
}
}
return tabel;
}
private int zoekIndex(Kaart k)
{
int index = 0;
for(int i=0;i<32;i++)
{
if(kaartenIndex[i] == k)
{
return i;
}
}
return -1;
}
private double zoekPunten(Vector kaarten)
{
double aantalPunten = 0;
int[] index = new int[3];
index[0] = zoekIndex((Kaart)kaarten.elementAt(0));
index[1] = zoekIndex((Kaart)kaarten.elementAt(1));
index[2] = zoekIndex((Kaart)kaarten.elementAt(2));
aantalPunten = kaartenTabel[index[0]][index[1]][index[2]];
return aantalPunten;
}
private void printTabel()
{
for(int i=0;i<32;i++)
{
for(int j=0;j<32;j++)
{
for(int k=0;k<32;k++)
{
System.out.print(" " + kaartenTabel[i][j][k]);
}
System.out.print('\n');
}
System.out.print('\n');
}
}
}
| True |
322 | 81720_14 | package com.chickenmobile.chickensorigins.client.renderers;
import com.chickenmobile.chickensorigins.ChickensOrigins;
import com.chickenmobile.chickensorigins.ChickensOriginsClient;
import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel;
import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust;
import com.chickenmobile.chickensorigins.core.registry.ModParticles;
import com.chickenmobile.chickensorigins.util.WingsData;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.EntityModelLoader;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.random.Random;
public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
private final ButterflyWingModel<T> butterflyWings;
private long lastRenderTime;
private final int sparkleRenderDelay = 10;
public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) {
super(context);
this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY));
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) {
// Get wingType from wings data.
String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none");
// 'None' is a valid, even for pixie. Don't render.
if (wingType == "none") {
return;
}
Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png");
matrices.push();
matrices.translate(0.0D, -0.5D, 0.2D);
this.getContextModel().copyStateTo(this.butterflyWings);
this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch);
float[] color = DyeColor.WHITE.getColorComponents();
this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]);
matrices.pop();
// Render pixie sparkle.
renderParticles(player, wingType);
}
}
public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) {
VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false);
this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F);
}
// Unused for now
public void renderParticles(PlayerEntity player, String wingType) {
//Random rand = player.world.random;
// Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP.
if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) {
lastRenderTime = player.age;
// Create particle based on facing of player
// minecraft is off by 90deg for normal sin/cos circle mathos
// double yaw = Math.toRadians(player.getBodyYaw() - 90);
// double xCos = Math.cos(yaw);
// double zSin = Math.sin(yaw);
ParticlePixieDust.SparkleColor color = switch (wingType) {
case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN;
case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE;
case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN;
case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE;
case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK;
case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE;
case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED;
case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW;
default -> ParticlePixieDust.SparkleColor.WHITE;
};
// Create & Render the particle
// player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
// player.getX() + (0.2F * xCos),
// player.getY() + 0.2F + 0.1F * rand.nextGaussian(),
// player.getZ() + (0.2F * zSin),
// color.r, color.g, color.b);
player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
player.getParticleX(1.0),
player.getRandomBodyY(),
player.getParticleZ(1.0),
color.r, color.g, color.b);
// rand.nextGaussian()) * 0.005D
}
}
} | ChickenMobile/chickens-origins | src/main/java/com/chickenmobile/chickensorigins/client/renderers/WingsFeatureRenderer.java | 1,705 | // player.getZ() + (0.2F * zSin), | line_comment | nl | package com.chickenmobile.chickensorigins.client.renderers;
import com.chickenmobile.chickensorigins.ChickensOrigins;
import com.chickenmobile.chickensorigins.ChickensOriginsClient;
import com.chickenmobile.chickensorigins.client.models.ButterflyWingModel;
import com.chickenmobile.chickensorigins.client.particles.ParticlePixieDust;
import com.chickenmobile.chickensorigins.core.registry.ModParticles;
import com.chickenmobile.chickensorigins.util.WingsData;
import net.minecraft.client.render.OverlayTexture;
import net.minecraft.client.render.RenderLayer;
import net.minecraft.client.render.VertexConsumer;
import net.minecraft.client.render.VertexConsumerProvider;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.FeatureRendererContext;
import net.minecraft.client.render.entity.model.EntityModel;
import net.minecraft.client.render.entity.model.EntityModelLoader;
import net.minecraft.client.render.item.ItemRenderer;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.DyeColor;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.random.Random;
public class WingsFeatureRenderer<T extends LivingEntity, M extends EntityModel<T>> extends FeatureRenderer<T, M> {
private final ButterflyWingModel<T> butterflyWings;
private long lastRenderTime;
private final int sparkleRenderDelay = 10;
public WingsFeatureRenderer(FeatureRendererContext<T, M> context, EntityModelLoader loader) {
super(context);
this.butterflyWings = new ButterflyWingModel<>(loader.getModelPart(ChickensOriginsClient.BUTTERFLY));
}
@Override
public void render(MatrixStack matrices, VertexConsumerProvider vertexConsumers, int light, T entity, float limbAngle, float limbDistance, float tickDelta, float animationProgress, float headYaw, float headPitch) {
if (entity instanceof PlayerEntity player && ChickensOrigins.IS_PIXIE.test(player)) {
// Get wingType from wings data.
String wingType = WingsData.WINGS_DATA.WING_MAP.getOrDefault(player.getUuidAsString(), "none");
// 'None' is a valid, even for pixie. Don't render.
if (wingType == "none") {
return;
}
Identifier layer = new Identifier(ChickensOrigins.MOD_ID, "textures/entity/" + wingType + ".png");
matrices.push();
matrices.translate(0.0D, -0.5D, 0.2D);
this.getContextModel().copyStateTo(this.butterflyWings);
this.butterflyWings.setAngles(entity, limbAngle, limbDistance, animationProgress, headYaw, headPitch);
float[] color = DyeColor.WHITE.getColorComponents();
this.renderWings(matrices, vertexConsumers, RenderLayer.getEntityTranslucent(layer), light, color[0], color[1], color[2]);
matrices.pop();
// Render pixie sparkle.
renderParticles(player, wingType);
}
}
public void renderWings(MatrixStack matrices, VertexConsumerProvider vertexConsumers, RenderLayer renderLayer, int light, float r, float g, float b) {
VertexConsumer vertexConsumer = ItemRenderer.getArmorGlintConsumer(vertexConsumers, renderLayer, false, false);
this.butterflyWings.render(matrices, vertexConsumer, light, OverlayTexture.DEFAULT_UV, r, g, b, 0.9F);
}
// Unused for now
public void renderParticles(PlayerEntity player, String wingType) {
//Random rand = player.world.random;
// Don't render too many sparkles, render is 3x a tick (too much). This includes when game is paused in SP.
if (player.age != lastRenderTime && !player.isOnGround() && player.age % sparkleRenderDelay == 0) {
lastRenderTime = player.age;
// Create particle based on facing of player
// minecraft is off by 90deg for normal sin/cos circle mathos
// double yaw = Math.toRadians(player.getBodyYaw() - 90);
// double xCos = Math.cos(yaw);
// double zSin = Math.sin(yaw);
ParticlePixieDust.SparkleColor color = switch (wingType) {
case "birdwing", "green_spotted_triangle" -> ParticlePixieDust.SparkleColor.GREEN;
case "blue_morpho" -> ParticlePixieDust.SparkleColor.BLUE;
case "buckeye" -> ParticlePixieDust.SparkleColor.BROWN;
case "monarch" -> ParticlePixieDust.SparkleColor.ORANGE;
case "pink_rose" -> ParticlePixieDust.SparkleColor.PINK;
case "purple_emperor" -> ParticlePixieDust.SparkleColor.PURPLE;
case "red_lacewing" -> ParticlePixieDust.SparkleColor.RED;
case "tiger_swallowtail" -> ParticlePixieDust.SparkleColor.YELLOW;
default -> ParticlePixieDust.SparkleColor.WHITE;
};
// Create & Render the particle
// player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
// player.getX() + (0.2F * xCos),
// player.getY() + 0.2F + 0.1F * rand.nextGaussian(),
// player.getZ() +<SUF>
// color.r, color.g, color.b);
player.getWorld().addParticle(ModParticles.PARTICLE_PIXIE_DUST,
player.getParticleX(1.0),
player.getRandomBodyY(),
player.getParticleZ(1.0),
color.r, color.g, color.b);
// rand.nextGaussian()) * 0.005D
}
}
} | False |
1,264 | 122744_0 | import java.util.Scanner;
public class OnderdeelC {
// Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| Owain94/IOPR-Java | Week2/Werkcolleges/opgave1/src/OnderdeelC.java | 366 | // Alles onder de case die geselecteerd wordt zal uitgeprint worden dit komt omdat de code niet weet waar het moet stoppen door het ontbreken van een break | line_comment | nl | import java.util.Scanner;
public class OnderdeelC {
// Alles onder<SUF>
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Vul een maand in:\n");
int month = input.nextInt();
switch (month) {
case 1:
System.out.println("januari");
case 2:
System.out.println("februari");
case 3:
System.out.println("maart");
case 4:
System.out.println("april");
case 5:
System.out.println("mei");
case 6:
System.out.println("juni");
case 7:
System.out.println("juli");
case 8:
System.out.println("augustus");
case 9:
System.out.println("september");
case 10:
System.out.println("oktober");
case 11:
System.out.println("november");
case 12:
System.out.println("december");
default:
System.out.println("Geen geldige invoer");
}
}
}
| True |
2,966 | 30795_0 | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| hogeschoolnovi/SD-BE-JP-oefenopdrachten | src/nl/novi/uitleg/week2/io/Bestandslezer.java | 1,170 | /**
* Deze methode maakt een ArrayList<User> BufferedReader aan.
* De BufferedReader wordt vervolgens aan de readAllLines methode gegeven om het tekstbestand
* uit te lezen.
* @return lege of gevulde lijst met User-objecten.
*/ | block_comment | nl | package nl.novi.uitleg.week2.io;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Bestandslezer {
private static final String FILE_LOCATION = "src/nl/novi/uitleg/week2/io/bestand.txt";
/**
* Deze methode maakt<SUF>*/
public static List<User> readFile() {
List<User> gebruikers = new ArrayList<>();
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(FILE_LOCATION));
gebruikers = readAllLines(bufferedReader);
} catch (IOException ioException) {
ioException.printStackTrace();
}
return gebruikers;
}
/**
* Deze methode is private en kan dus alleen in de Bestandlezer.java klasse aangeroepen worden.
*
* Deze code ontvangt een BufferedReader en gaat het tekstbestand dat daaronder hangt regel voor regel
* uitlezen.
*
* Daarna wordt de gelezen regel in een String[] array geplaatst. Vanuit deze array wordt uiteindelijk een
* User-object aangemaakt. Dit User-object wordt toegevoegd aan de list en uiteindelijk gereturned.
*
* Deze methode is eigenlijk te groot. Deze heeft te veel verantwoordlijkheden. Het maken van een object op basis
* van een String of Array zou ik bijvoorbeeld in een andere methode of klasse zetten.
* Kun je verzinnen hoe dat moet? Deze oplossing is meer het niveau van Java 1.
*
* @param bufferedReader De bufferedreader met een FileReader en de locatie naar het tekstbestand
* @return Lijst met user-objecten.
* @throws IOException wanneer er iets fout gaat in de IO-operatie.
*/
private static List<User> readAllLines(BufferedReader bufferedReader) throws IOException {
List<User> gebruikers = new ArrayList<>();
String line;
while((line = bufferedReader.readLine()) != null) {
String[] inhoudRegel = line.split("\\|");
String username = inhoudRegel[0];
String score = inhoudRegel[1].trim();
int scoreConverted;
try {
scoreConverted = Integer.parseInt(score);
} catch (NumberFormatException numberFormatException) {
scoreConverted = 0;
}
User user = new User(username, scoreConverted);
gebruikers.add(user);
}
return gebruikers;
}
/**
* Deze methode ontvangt een lijst met User-objecten. Deze worden met een methode uit het user-object omgevormd
* naar Strings die opgeslagen kunnen worden.
* @param users Lijst van users die opgeslagen moeten worden.
* @throws IOException wanneer er iets foutgaat met het opslaan.
*/
public static void save(List<User> users) throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
for (User user : users) {
String lineToSave = user.getTextToSave();
writer.write(lineToSave + "\r\n");
}
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
/**
* Deze methode schrijft een lege String weg naar het tekstbestand. Alle data verdwijnt dus na het aanroepen van
* deze methode.
*
* Public methode, dus deze kan van buiten deze klasse aangeroepen worden.
*
* @throws IOException wanneer er iets fout gaat met het wegschrijven.
*/
public static void emptyFile() throws IOException {
FileWriter writer = null;
try {
writer = new FileWriter(FILE_LOCATION);
writer.write("");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
writer.close();
}
}
}
| True |
1,159 | 180433_6 | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en power zijn altijd gehele getallen dan is er geen afronding
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| Murrx/EWDC | ws-parent/ws-producer/src/main/java/nl/hu/fnt/gsos/wsproducer/PowerserviceImpl.java | 343 | //// // x en power zijn altijd gehele getallen dan is er geen afronding | line_comment | nl | //package nl.hu.fnt.gsos.wsproducer;
//
//import javax.jws.WebService;
//
//@WebService(endpointInterface = "nl.hu.fnt.gsos.wsinterface.WSInterface")
//public class PowerserviceImpl implements WSInterface {
//
// @Override
//// public Response calculatePower(Request request) throws Fault_Exception {
//// ObjectFactory factory = new ObjectFactory();
//// Response response = factory.createResponse();
//// try {
//// Double result = Math.pow(request.getX().doubleValue(), request
//// .getPower().doubleValue());
//// // x en<SUF>
//// long actualResult = result.longValue();
//// response.setResult(actualResult);
//// } catch (RuntimeException e) {
//// Fault x = factory.createFault();
//// x.setErrorCode((short) 1);
//// x.setMessage("Kan de macht van " + request.getX()
//// + " tot de macht " + request.getPower().toString()
//// + " niet berekenen.");
//// Fault_Exception fault = new Fault_Exception(
//// "Er ging iets mis met het berekenen van de power", x);
//// throw fault;
//// }
//// return response;
//// }
////
////}
| True |
599 | 202128_0 | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| GerjanWielink/software-systems | ss/src/main/java/ss/week6/voteMachine/gui/ResultJFrame.java | 415 | /**
* P2 prac wk3.
* UitslagJFrame: GUI voor een Uitslag.
* @author Arend Rensink en Theo Ruys
* @version 2005.02.15
*/ | block_comment | nl | package ss.week6.voteMachine.gui;
import java.awt.Container;
import java.awt.FlowLayout;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
/**
* P2 prac wk3.<SUF>*/
public class ResultJFrame extends JFrame {
// Grafische componenten
private JTextArea resultField;
private JLabel messageLabel;
/** Construeert een UitslagJFrame die een gegeven uitslag observeert. */
public ResultJFrame(VoteGUIView view) {
// Initialisatie grafische componenten
super("Result");
Container cc = getContentPane();
cc.setLayout(new FlowLayout());
messageLabel = new JLabel("Votes:");
cc.add(messageLabel);
resultField = new JTextArea("", 10, 20);
resultField.setEditable(false);
cc.add(resultField);
setSize(250, 255);
}
/** Zet de uitslag op het tekstveld, met 1 regel per partij. */
public void update(Map<String,Integer> votes) {
resultField.setText("");
for(Map.Entry<String,Integer> entry: votes.entrySet()){
resultField.append(entry.getKey() + ": " + entry.getValue() + "\n");
}
}
}
| False |
1,379 | 87130_11 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("space3.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,9,9,9,9},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,35,58,58,58,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,171,171,171,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{9,9,9,81,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,-1,-1,-1,182,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,168,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,87,81,-1,13,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,13,-1,85,9,-1,-1,-1,9,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,85,9,9,9,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,181,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,5,87,9,9,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,9,9,80,5,179,179,179,5,87,9,9,9,-1,-1,82,83,84,-1,-1,9,80,5,5,5,87,9,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,9,9,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,5,5,5,5,5,-1,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5,5,5,5,5,5,5,5,5,11,11,11,11,11,11,11,5,5,5,5,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,5,5},
{5,5,5,5,5,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 95, 672);
addObject(hero, 95,672);
addObject(new Enemy(), 2492, 826);
addObject(new Enemy(), 5190, 586);
addObject(new VliegendeEnemy(),1226, 580);
addObject(new Door1(), 5912, 325);
addObject(new DoorTop(), 5912, 265);
addObject(new FireBall(), 825, 695);
addObject(new FireBall(), 1880, 745);
// Force act zodat de camera op de juist plek staat.
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
prepare();
}
@Override
public void act() {
ce.update();
}
public void prepare()
{
PlayAgainTopLeft1 patl1 = new PlayAgainTopLeft1();
addObject(patl1, 100, 40);
HomeButton hb = new HomeButton();
addObject(hb, 40, 40);
}
} | ROCMondriaanTIN/project-greenfoot-game-JensDH | MyWorld.java | 4,768 | // Force act zodat de camera op de juist plek staat. | line_comment | nl | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class MyWorld extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class MyWorld.
*
*/
public MyWorld() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("space3.png");
int[][] map = {
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,9,9,9,9},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,35,58,58,58,37,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{-1,-1,-1,171,171,171,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,27,27,27,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{9,9,9,81,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,-1,-1,-1,182,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,168,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,77,9,76,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,87,81,-1,13,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,13,-1,85,9,-1,-1,-1,9,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,85,9,9,9,81,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,181,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,5,87,9,9,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,9,9,9,80,5,179,179,179,5,87,9,9,9,-1,-1,82,83,84,-1,-1,9,80,5,5,5,87,9,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,79,-1,-1,-1,-1,-1,9,9,9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5},
{5,5,5,5,5,5,5,5,-1,-1,-1,-1,-1,-1,-1,75,9,78,-1,-1,-1,-1,-1,-1,-1,5,5,5,5,5,5,5,5,5,5,5,5,5,11,11,11,11,11,11,11,5,5,5,5,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,5,5},
{5,5,5,5,5,5,5,5,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
{5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5,5,5,5,5,5,5,5,5,10,10,10,10,10,10,10,5,5,5,5,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,5,5,5,5,5},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 95, 672);
addObject(hero, 95,672);
addObject(new Enemy(), 2492, 826);
addObject(new Enemy(), 5190, 586);
addObject(new VliegendeEnemy(),1226, 580);
addObject(new Door1(), 5912, 325);
addObject(new DoorTop(), 5912, 265);
addObject(new FireBall(), 825, 695);
addObject(new FireBall(), 1880, 745);
// Force act<SUF>
camera.act();
hero.act();
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
prepare();
}
@Override
public void act() {
ce.update();
}
public void prepare()
{
PlayAgainTopLeft1 patl1 = new PlayAgainTopLeft1();
addObject(patl1, 100, 40);
HomeButton hb = new HomeButton();
addObject(hb, 40, 40);
}
} | True |
957 | 190590_3 | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| Laugslander/fontys-swipe | app/src/main/java/nl/fontys/smpt42_1/fontysswipe/controller/CompareController.java | 1,492 | /**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/ | block_comment | nl | package nl.fontys.smpt42_1.fontysswipe.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import nl.fontys.smpt42_1.fontysswipe.domain.Route;
import nl.fontys.smpt42_1.fontysswipe.domain.Teacher;
import nl.fontys.smpt42_1.fontysswipe.domain.interfaces.CompareAlgo;
import nl.fontys.smpt42_1.fontysswipe.util.FindRouteUtilKt;
/**
* @author SMPT42-1
*/
class CompareController {
private static CompareController instance;
private CompareController() {
// Marked private because the CompareController should never be instantianted outside this class.
}
public static CompareController getInstance() {
return instance == null ? instance = new CompareController() : instance;
}
/**
* Compare teacher methode compared alle docenten met 1 student en kijkt voor alle docenten welke docenten de beste match is.
*
* @param userPoints een hashmap met de studie profielen en het aantal punten dat de gebruiker daarbij heeft.
* @param comparables all comparable objects.
* @return een gesorteerde map van docenten met het aantal procenten dat matcht.
*/
List<Teacher> compareTeachers(List<Route> userPoints, List<Teacher> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> teachersMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : teachersMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
/**
* Compare teacher methode<SUF>*/
List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> compareWorkshops(List<Route> userPoints, List<nl.fontys.smpt42_1.fontysswipe.domain.Activity> comparables) {
HashMap<String, Double> differenceMap = new HashMap<>();
HashMap<CompareAlgo, Double> resultMap = new HashMap<>();
List<Route> correctUserPoints = getCorrectUserPoints(userPoints);
for (CompareAlgo comparable : comparables) {
double result = 0;
Map<String, Integer> workshopsMap = comparable.getPoints();
for (final Map.Entry<String, Integer> teacherEntry : workshopsMap.entrySet()) {
Route route = FindRouteUtilKt.findRoute(teacherEntry.getKey(), correctUserPoints);
double difference = Math.abs(route.getUserPoints() - teacherEntry.getValue());
differenceMap.put(teacherEntry.getKey(), difference);
result = result + (differenceMap.get(route.getAbbreviation()) * (route.getUserPoints() * 0.1));
}
resultMap.put(comparable, result);
}
return new ArrayList(sortByValue(resultMap).keySet());
}
private List<Route> getCorrectUserPoints(List<Route> userPoints) {
List<Route> correctUserPoints = new ArrayList<Route>();
for (Route route : userPoints) {
route.setUserPoints(route.getUserPoints() / (route.getMaxPoints() / 10));
correctUserPoints.add(route);
}
return correctUserPoints;
}
private static Map<CompareAlgo, Double> sortByValue(Map<CompareAlgo, Double> unsortMap) {
List<Map.Entry<CompareAlgo, Double>> list = new LinkedList<Map.Entry<CompareAlgo, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<CompareAlgo, Double>>() {
public int compare(Map.Entry<CompareAlgo, Double> o1,
Map.Entry<CompareAlgo, Double> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
Map<CompareAlgo, Double> sortedMap = new LinkedHashMap<CompareAlgo, Double>();
for (Map.Entry<CompareAlgo, Double> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
for (Map.Entry<CompareAlgo, Double> entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey().getName()
+ " Value : " + entry.getValue());
}
return sortedMap;
}
}
| True |
745 | 14017_0 | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| IcyPalm/AlphaReversi | src/alphareversi/commands/receive/RecvGameMoveCommand.java | 480 | /**
* Created by Joost van Berkel on 3/24/2016.
* Resultaat van een zet ontvangen, bericht naar beide spelers.
* S: SVR GAME MOVE {PLAYER: "--speler--", DETAILS: "--reactie spel op zet--", MOVE:"--zet--"}
* Er is een zet gedaan, dit bericht geeft aan wie deze gezet heeft,
* wat de reactie van het spel erop is
*/ | block_comment | nl | package alphareversi.commands.receive;
import alphareversi.commands.CommandParser;
import alphareversi.commands.RecvCommand;
import java.util.HashMap;
/**
* Created by Joost<SUF>*/
public class RecvGameMoveCommand extends RecvCommand {
private String player;
private String details;
private String move;
/**
* Parse string to create a filled RecvGamelistCommand.
* @param command string containing server message
*/
public RecvGameMoveCommand(String command) {
String[] parts = command.split(" ", 4);
this.setType(parts[0]);
this.setMethod(parts[1]);
this.setAction(parts[2]);
HashMap objects = CommandParser.parseObjectMap(parts[3]);
this.setPlayer((String) objects.get("PLAYER"));
this.setDetails((String) objects.get("DETAILS"));
this.setMove((String) objects.get("MOVE"));
}
public String getPlayer() {
return player;
}
public void setPlayer(String player) {
this.player = player;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
| True |
1,993 | 108485_13 |
import java.util.Scanner;
import java.text.DecimalFormat;
public class Freizeitpark {
public static Scanner scan = new Scanner(System.in);
public static int vergangeneZeit = 0;
public static int dauerImPark = 0;
public static void main(String[] args) {
// TODO Automatisch generierter Methodenstub
willkommen();
eintrittBezahlen();
durchDenParkSchlendern();
/*eisEssen();
achterbahnFahren();
wcBenutzen();
sichBetrinken();
parkVerlassen(); */
}
public static void willkommen() {
System.out.println("Willkommen in unserem Freizeitpark!");
}
public static void eintrittBezahlen() {
int preisFuerErwachsene = 20;
int preisFuerKinderu14 = 0;
double preisFuerKinder14u18 = preisFuerErwachsene * 0.75;
double preisFuerStudenten = preisFuerErwachsene * 0.75;
/* System.out.println("Ist der Besucher erwachsen, Student, Kind zwischen 14 und 18 oder Kind unter 14?");
String antwortDesBenutzers = scan.next();
if (antwortDesBenutzers.equalsIgnoreCase("erwachsen")) {
System.out.println("Sie muessen " + preisFuerErwachsene + " bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind unter 14 Jahre")) {
System.out.println("Fuer Kinder unter 14 Jahren ist der Eintritt kostenlos.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind zwischen 14 und 18 Jahren")) {
System.out.println("Fuer Kinder zwischen 14 und 18 Jahren muessen Sie " + preisFuerKinder14u18 + "bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Student")){
System.out.println("Sie muessen " + preisFuerStudenten + " bezahlen.");
} */
System.out.println("Wie viele Eintrittskarten fuer Erwachsene moechten Sie kaufen?");
int anzahlErwachsene = scan.nextInt();
int gesamtpreisErwachsene = anzahlErwachsene * preisFuerErwachsene;
System.out.println("Fuer wie viele Kinder zwischen 14 und 18 Jahren moechten Sie Eintrittskarten kaufen?");
int anzahlKinder14u18 = scan.nextInt();
double gesamtpreisKinder14u18 = anzahlKinder14u18 * preisFuerKinder14u18;
System.out.println("Wie viele Eintrittskarten fuer Studenten moechten Sie kaufen?");
int anzahlStudenten = scan.nextInt();
double gesamtpreisStudenten = anzahlStudenten * preisFuerStudenten;
System.out.println("Fuer wie viele Kinder unter 14 Jahren moechten Sie Eintrittskarte haben?");
int anzahlKinderu14 = scan.nextInt();
int gesamtpreisKinderu14 = preisFuerKinderu14 * anzahlKinderu14;
double gesamtpreis = gesamtpreisErwachsene + gesamtpreisKinder14u18 + gesamtpreisStudenten + gesamtpreisKinderu14;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterGesamtpreis = df.format(gesamtpreis);
System.out.println("Gesamtpreis fuer die Eintrittskarten: " + gerundeterGesamtpreis + " Euro.");
System.out.println();
scan.nextLine();
}
public static void eisEssen() {
/*System.out.println("Wollen Sie Eis essen?");
String eisEssen = scan.next();
if (eisEssen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele Kugeln moechten Sie?");
int anzahlDerKugeln = scan.nextInt();
double preisProKugel = 1.20;
double endpreisFuerEis = anzahlDerKugeln * preisProKugel;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragEis = df.format(endpreisFuerEis);
System.out.println("Sie muessen insgesamt " + gerundeterBetragEis + " Euro fuer das Eis bezahlen.");
//}
scan.nextLine();
}
// Zeiterfassung
public static void durchDenParkSchlendern() {
System.out.println("Wie lange moechten Sie durch den Park schlendern (in Minuten)?");
int dauerImPark = scan.nextInt();
int vergangeneZeit = 0;
System.out.println("Sie beginnen Ihren Spaziergang/Aufenthalt in unserem Park.");
// minutengenaue Erfassung der vergangenen Zeit
while (vergangeneZeit < dauerImPark) {
// Aktivitaeten im Park
System.out.println();
System.out.println("Was moechten Sie tun? Waehlen Sie eine von den 6 Optionen: ");
System.out.println("1. Eis kaufen");
System.out.println("2. Achterbahn fahren");
System.out.println("3. WC benutzen");
System.out.println("4. Sich betrinken");
System.out.println("5. Weiter durch den Park schlendern");
System.out.println("6. Park verlassen");
System.out.println();
int aktivitaet = scan.nextInt();
switch (aktivitaet) {
case 1:
eisEssen();
vergangeneZeit += 5;
break;
case 2:
achterbahnFahren();
vergangeneZeit += 10;
break;
case 3:
wcBenutzen();
vergangeneZeit += 5;
break;
case 4:
sichBetrinken();
vergangeneZeit += 20;
break;
case 5:
durchDenParkSchlendern();
vergangeneZeit += 10;
break;
case 6:
parkVerlassen();
vergangeneZeit += 10;
break;
default:
System.out.println("Ungueltige Benutzereingabe. Bitte waehlen Sie eine der 6 Optionen.");
}
// vergangeneZeit++;
System.out.println("Vergangene Zeit: " + vergangeneZeit + "Minuten von " + dauerImPark + " Minuten.");
}
// nach abgelaufener Zeit
System.out.println();
System.out.println("Sie haben keine Zeit mehr.");
parkVerlassen();
}
public static void achterbahnFahren() {
/* System.out.println("Wollen Sie Achterbahn fahren?");
String achterbahnFahren = scan.next();
if (achterbahnFahren.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen Achterbahn fahren?");
int anzahlDerAchterbahnfahrenden = scan.nextInt();
double preisProFahrenden = 2.80;
double endpreisFuerAchterbahn = anzahlDerAchterbahnfahrenden * preisProFahrenden;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragAchterbahn = df.format(endpreisFuerAchterbahn);
System.out.println("Sie muessen insgesamt " + gerundeterBetragAchterbahn + " Euro bezahlen.");
//}
scan.nextLine();
}
public static void wcBenutzen() {
/* System.out.println("Wollen Sie das WC benutzen?");
String wcBenutzen = scan.next();
if (wcBenutzen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen das WC benutzen?");
int anzahlWCBenutzenden = scan.nextInt();
double preisWC = 0.70;
double endpreisFuerWC = anzahlWCBenutzenden * preisWC;
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragWC = df.format(endpreisFuerWC);
System.out.println("Sie muessen insgesamt " + gerundeterBetragWC + " Euro zahlen.");
// }
}
public static void sichBetrinken() {
/*System.out.println("Wollen Sie sich betrinken?");
String sichBetrinken = scan.next();
if (sichBetrinken.equalsIgnoreCase("ja")) { */
System.out.println("Sind Sie volljaehrig?");
String volljaehrigBetrinken = scan.next();
if (volljaehrigBetrinken.equalsIgnoreCase("ja")) {
String weiterTrinken;
do {
System.out.println("Wie viele wollen Sie sich betrinken?");
int anzahlSichBetrinkenden = scan.nextInt();
int preisAlkohol = 21;
int endpreisFuerAlkohol = anzahlSichBetrinkenden * preisAlkohol;
System.out.println("Sie muessen insgesamt " + endpreisFuerAlkohol + " Euro bezahlen.");
System.out.println("Wollen Sie noch etwas trinken?");
weiterTrinken = scan.next();
} while (weiterTrinken.equalsIgnoreCase("ja"));
}
//}
}
public static void parkVerlassen() {
/*System.out.println("Wollen Sie den Park verlassen?");
String parkVerlassen = scan.next();
if (parkVerlassen.equalsIgnoreCase("ja")) { */
System.out.println("Vielen Dank fuer Ihren Besuch in unserem Freizeitpark! Wir hoffen, Sie hatten eine tolle Zeit und freuen uns darauf, Sie bald wieder bei uns begruessen zu duerfen. Auf Wiedersehen!");
// }
}
}
| akkorismeglesz/Freizeitpark | Freizeitpark.java | 2,829 | /*System.out.println("Wollen Sie den Park verlassen?");
String parkVerlassen = scan.next();
if (parkVerlassen.equalsIgnoreCase("ja")) { */ | block_comment | nl |
import java.util.Scanner;
import java.text.DecimalFormat;
public class Freizeitpark {
public static Scanner scan = new Scanner(System.in);
public static int vergangeneZeit = 0;
public static int dauerImPark = 0;
public static void main(String[] args) {
// TODO Automatisch generierter Methodenstub
willkommen();
eintrittBezahlen();
durchDenParkSchlendern();
/*eisEssen();
achterbahnFahren();
wcBenutzen();
sichBetrinken();
parkVerlassen(); */
}
public static void willkommen() {
System.out.println("Willkommen in unserem Freizeitpark!");
}
public static void eintrittBezahlen() {
int preisFuerErwachsene = 20;
int preisFuerKinderu14 = 0;
double preisFuerKinder14u18 = preisFuerErwachsene * 0.75;
double preisFuerStudenten = preisFuerErwachsene * 0.75;
/* System.out.println("Ist der Besucher erwachsen, Student, Kind zwischen 14 und 18 oder Kind unter 14?");
String antwortDesBenutzers = scan.next();
if (antwortDesBenutzers.equalsIgnoreCase("erwachsen")) {
System.out.println("Sie muessen " + preisFuerErwachsene + " bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind unter 14 Jahre")) {
System.out.println("Fuer Kinder unter 14 Jahren ist der Eintritt kostenlos.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Kind zwischen 14 und 18 Jahren")) {
System.out.println("Fuer Kinder zwischen 14 und 18 Jahren muessen Sie " + preisFuerKinder14u18 + "bezahlen.");
} else if (antwortDesBenutzers.equalsIgnoreCase("Student")){
System.out.println("Sie muessen " + preisFuerStudenten + " bezahlen.");
} */
System.out.println("Wie viele Eintrittskarten fuer Erwachsene moechten Sie kaufen?");
int anzahlErwachsene = scan.nextInt();
int gesamtpreisErwachsene = anzahlErwachsene * preisFuerErwachsene;
System.out.println("Fuer wie viele Kinder zwischen 14 und 18 Jahren moechten Sie Eintrittskarten kaufen?");
int anzahlKinder14u18 = scan.nextInt();
double gesamtpreisKinder14u18 = anzahlKinder14u18 * preisFuerKinder14u18;
System.out.println("Wie viele Eintrittskarten fuer Studenten moechten Sie kaufen?");
int anzahlStudenten = scan.nextInt();
double gesamtpreisStudenten = anzahlStudenten * preisFuerStudenten;
System.out.println("Fuer wie viele Kinder unter 14 Jahren moechten Sie Eintrittskarte haben?");
int anzahlKinderu14 = scan.nextInt();
int gesamtpreisKinderu14 = preisFuerKinderu14 * anzahlKinderu14;
double gesamtpreis = gesamtpreisErwachsene + gesamtpreisKinder14u18 + gesamtpreisStudenten + gesamtpreisKinderu14;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterGesamtpreis = df.format(gesamtpreis);
System.out.println("Gesamtpreis fuer die Eintrittskarten: " + gerundeterGesamtpreis + " Euro.");
System.out.println();
scan.nextLine();
}
public static void eisEssen() {
/*System.out.println("Wollen Sie Eis essen?");
String eisEssen = scan.next();
if (eisEssen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele Kugeln moechten Sie?");
int anzahlDerKugeln = scan.nextInt();
double preisProKugel = 1.20;
double endpreisFuerEis = anzahlDerKugeln * preisProKugel;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragEis = df.format(endpreisFuerEis);
System.out.println("Sie muessen insgesamt " + gerundeterBetragEis + " Euro fuer das Eis bezahlen.");
//}
scan.nextLine();
}
// Zeiterfassung
public static void durchDenParkSchlendern() {
System.out.println("Wie lange moechten Sie durch den Park schlendern (in Minuten)?");
int dauerImPark = scan.nextInt();
int vergangeneZeit = 0;
System.out.println("Sie beginnen Ihren Spaziergang/Aufenthalt in unserem Park.");
// minutengenaue Erfassung der vergangenen Zeit
while (vergangeneZeit < dauerImPark) {
// Aktivitaeten im Park
System.out.println();
System.out.println("Was moechten Sie tun? Waehlen Sie eine von den 6 Optionen: ");
System.out.println("1. Eis kaufen");
System.out.println("2. Achterbahn fahren");
System.out.println("3. WC benutzen");
System.out.println("4. Sich betrinken");
System.out.println("5. Weiter durch den Park schlendern");
System.out.println("6. Park verlassen");
System.out.println();
int aktivitaet = scan.nextInt();
switch (aktivitaet) {
case 1:
eisEssen();
vergangeneZeit += 5;
break;
case 2:
achterbahnFahren();
vergangeneZeit += 10;
break;
case 3:
wcBenutzen();
vergangeneZeit += 5;
break;
case 4:
sichBetrinken();
vergangeneZeit += 20;
break;
case 5:
durchDenParkSchlendern();
vergangeneZeit += 10;
break;
case 6:
parkVerlassen();
vergangeneZeit += 10;
break;
default:
System.out.println("Ungueltige Benutzereingabe. Bitte waehlen Sie eine der 6 Optionen.");
}
// vergangeneZeit++;
System.out.println("Vergangene Zeit: " + vergangeneZeit + "Minuten von " + dauerImPark + " Minuten.");
}
// nach abgelaufener Zeit
System.out.println();
System.out.println("Sie haben keine Zeit mehr.");
parkVerlassen();
}
public static void achterbahnFahren() {
/* System.out.println("Wollen Sie Achterbahn fahren?");
String achterbahnFahren = scan.next();
if (achterbahnFahren.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen Achterbahn fahren?");
int anzahlDerAchterbahnfahrenden = scan.nextInt();
double preisProFahrenden = 2.80;
double endpreisFuerAchterbahn = anzahlDerAchterbahnfahrenden * preisProFahrenden;
// Runden auf zwei Dezimalstellen
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragAchterbahn = df.format(endpreisFuerAchterbahn);
System.out.println("Sie muessen insgesamt " + gerundeterBetragAchterbahn + " Euro bezahlen.");
//}
scan.nextLine();
}
public static void wcBenutzen() {
/* System.out.println("Wollen Sie das WC benutzen?");
String wcBenutzen = scan.next();
if (wcBenutzen.equalsIgnoreCase("ja")) { */
System.out.println("Wie viele wollen das WC benutzen?");
int anzahlWCBenutzenden = scan.nextInt();
double preisWC = 0.70;
double endpreisFuerWC = anzahlWCBenutzenden * preisWC;
DecimalFormat df = new DecimalFormat("#.##");
String gerundeterBetragWC = df.format(endpreisFuerWC);
System.out.println("Sie muessen insgesamt " + gerundeterBetragWC + " Euro zahlen.");
// }
}
public static void sichBetrinken() {
/*System.out.println("Wollen Sie sich betrinken?");
String sichBetrinken = scan.next();
if (sichBetrinken.equalsIgnoreCase("ja")) { */
System.out.println("Sind Sie volljaehrig?");
String volljaehrigBetrinken = scan.next();
if (volljaehrigBetrinken.equalsIgnoreCase("ja")) {
String weiterTrinken;
do {
System.out.println("Wie viele wollen Sie sich betrinken?");
int anzahlSichBetrinkenden = scan.nextInt();
int preisAlkohol = 21;
int endpreisFuerAlkohol = anzahlSichBetrinkenden * preisAlkohol;
System.out.println("Sie muessen insgesamt " + endpreisFuerAlkohol + " Euro bezahlen.");
System.out.println("Wollen Sie noch etwas trinken?");
weiterTrinken = scan.next();
} while (weiterTrinken.equalsIgnoreCase("ja"));
}
//}
}
public static void parkVerlassen() {
/*System.out.println("Wollen Sie den<SUF>*/
System.out.println("Vielen Dank fuer Ihren Besuch in unserem Freizeitpark! Wir hoffen, Sie hatten eine tolle Zeit und freuen uns darauf, Sie bald wieder bei uns begruessen zu duerfen. Auf Wiedersehen!");
// }
}
}
| False |
4,438 | 111029_1 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet
*
*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| syncany/syncany-plugin-s3 | core/syncany-lib/src/main/java/org/syncany/operations/up/BlockingTransfersException.java | 290 | /**
* @author Jesse Donkervliet
*
*/ | block_comment | nl | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.operations.up;
/**
* @author Jesse Donkervliet<SUF>*/
public class BlockingTransfersException extends Exception {
/**
*
*/
private static final long serialVersionUID = -7635231951027588892L;
}
| False |
4,818 | 75371_48 | /** Generated Model - DO NOT CHANGE */
package de.metas.flatrate.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for C_SubscriptionProgress
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_C_SubscriptionProgress extends org.compiere.model.PO implements I_C_SubscriptionProgress, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -626565630L;
/** Standard Constructor */
public X_C_SubscriptionProgress (Properties ctx, int C_SubscriptionProgress_ID, String trxName)
{
super (ctx, C_SubscriptionProgress_ID, trxName);
/** if (C_SubscriptionProgress_ID == 0)
{
setC_Flatrate_Term_ID (0);
setC_SubscriptionProgress_ID (0);
setDropShip_BPartner_ID (0);
setDropShip_Location_ID (0);
setEventType (null);
setIsSubscriptionConfirmed (false);
// N
setProcessed (false);
// N
setStatus (null);
// P
} */
}
/** Load Constructor */
public X_C_SubscriptionProgress (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public de.metas.flatrate.model.I_C_Flatrate_Term getC_Flatrate_Term() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class);
}
@Override
public void setC_Flatrate_Term(de.metas.flatrate.model.I_C_Flatrate_Term C_Flatrate_Term)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class, C_Flatrate_Term);
}
/** Set Pauschale - Vertragsperiode.
@param C_Flatrate_Term_ID Pauschale - Vertragsperiode */
@Override
public void setC_Flatrate_Term_ID (int C_Flatrate_Term_ID)
{
if (C_Flatrate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, Integer.valueOf(C_Flatrate_Term_ID));
}
/** Get Pauschale - Vertragsperiode.
@return Pauschale - Vertragsperiode */
@Override
public int getC_Flatrate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ContractStatus AD_Reference_ID=540000
* Reference name: SubscriptionStatus
*/
public static final int CONTRACTSTATUS_AD_Reference_ID=540000;
/** Laufend = Ru */
public static final String CONTRACTSTATUS_Laufend = "Ru";
/** Lieferpause = Pa */
public static final String CONTRACTSTATUS_Lieferpause = "Pa";
/** Beendet = En */
public static final String CONTRACTSTATUS_Beendet = "En";
/** Gekündigt = Qu */
public static final String CONTRACTSTATUS_Gekuendigt = "Qu";
/** Wartet auf Bestätigung = St */
public static final String CONTRACTSTATUS_WartetAufBestaetigung = "St";
/** Info = In */
public static final String CONTRACTSTATUS_Info = "In";
/** Noch nicht begonnen = Wa */
public static final String CONTRACTSTATUS_NochNichtBegonnen = "Wa";
/** Set Vertrags-Status.
@param ContractStatus Vertrags-Status */
@Override
public void setContractStatus (java.lang.String ContractStatus)
{
set_Value (COLUMNNAME_ContractStatus, ContractStatus);
}
/** Get Vertrags-Status.
@return Vertrags-Status */
@Override
public java.lang.String getContractStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_ContractStatus);
}
/** Set Abo-Verlauf.
@param C_SubscriptionProgress_ID Abo-Verlauf */
@Override
public void setC_SubscriptionProgress_ID (int C_SubscriptionProgress_ID)
{
if (C_SubscriptionProgress_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, Integer.valueOf(C_SubscriptionProgress_ID));
}
/** Get Abo-Verlauf.
@return Abo-Verlauf */
@Override
public int getC_SubscriptionProgress_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_SubscriptionProgress_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner getDropShip_BPartner() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class);
}
@Override
public void setDropShip_BPartner(org.compiere.model.I_C_BPartner DropShip_BPartner)
{
set_ValueFromPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class, DropShip_BPartner);
}
/** Set Lieferempfänger.
@param DropShip_BPartner_ID
Business Partner to ship to
*/
@Override
public void setDropShip_BPartner_ID (int DropShip_BPartner_ID)
{
if (DropShip_BPartner_ID < 1)
set_Value (COLUMNNAME_DropShip_BPartner_ID, null);
else
set_Value (COLUMNNAME_DropShip_BPartner_ID, Integer.valueOf(DropShip_BPartner_ID));
}
/** Get Lieferempfänger.
@return Business Partner to ship to
*/
@Override
public int getDropShip_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner_Location getDropShip_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class);
}
@Override
public void setDropShip_Location(org.compiere.model.I_C_BPartner_Location DropShip_Location)
{
set_ValueFromPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class, DropShip_Location);
}
/** Set Lieferadresse.
@param DropShip_Location_ID
Business Partner Location for shipping to
*/
@Override
public void setDropShip_Location_ID (int DropShip_Location_ID)
{
if (DropShip_Location_ID < 1)
set_Value (COLUMNNAME_DropShip_Location_ID, null);
else
set_Value (COLUMNNAME_DropShip_Location_ID, Integer.valueOf(DropShip_Location_ID));
}
/** Get Lieferadresse.
@return Business Partner Location for shipping to
*/
@Override
public int getDropShip_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getDropShip_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setDropShip_User(org.compiere.model.I_AD_User DropShip_User)
{
set_ValueFromPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class, DropShip_User);
}
/** Set Lieferkontakt.
@param DropShip_User_ID
Business Partner Contact for drop shipment
*/
@Override
public void setDropShip_User_ID (int DropShip_User_ID)
{
if (DropShip_User_ID < 1)
set_Value (COLUMNNAME_DropShip_User_ID, null);
else
set_Value (COLUMNNAME_DropShip_User_ID, Integer.valueOf(DropShip_User_ID));
}
/** Get Lieferkontakt.
@return Business Partner Contact for drop shipment
*/
@Override
public int getDropShip_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum.
@param EventDate Datum */
@Override
public void setEventDate (java.sql.Timestamp EventDate)
{
set_Value (COLUMNNAME_EventDate, EventDate);
}
/** Get Datum.
@return Datum */
@Override
public java.sql.Timestamp getEventDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_EventDate);
}
/**
* EventType AD_Reference_ID=540013
* Reference name: C_SubscriptionProgress EventType
*/
public static final int EVENTTYPE_AD_Reference_ID=540013;
/** Lieferung = DE */
public static final String EVENTTYPE_Lieferung = "DE";
/** Abowechsel = SU */
public static final String EVENTTYPE_Abowechsel = "SU";
/** Statuswechsel = ST */
public static final String EVENTTYPE_Statuswechsel = "ST";
/** Abo-Ende = SE */
public static final String EVENTTYPE_Abo_Ende = "SE";
/** Abo-Beginn = SB */
public static final String EVENTTYPE_Abo_Beginn = "SB";
/** Abo-Autoverlängerung = SR */
public static final String EVENTTYPE_Abo_Autoverlaengerung = "SR";
/** Abopause-Beginn = PB */
public static final String EVENTTYPE_Abopause_Beginn = "PB";
/** Abopause-Ende = PE */
public static final String EVENTTYPE_Abopause_Ende = "PE";
/** Set Ereignisart.
@param EventType Ereignisart */
@Override
public void setEventType (java.lang.String EventType)
{
set_ValueNoCheck (COLUMNNAME_EventType, EventType);
}
/** Get Ereignisart.
@return Ereignisart */
@Override
public java.lang.String getEventType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EventType);
}
/** Set Bestätigung eingegangen.
@param IsSubscriptionConfirmed Bestätigung eingegangen */
@Override
public void setIsSubscriptionConfirmed (boolean IsSubscriptionConfirmed)
{
set_Value (COLUMNNAME_IsSubscriptionConfirmed, Boolean.valueOf(IsSubscriptionConfirmed));
}
/** Get Bestätigung eingegangen.
@return Bestätigung eingegangen */
@Override
public boolean isSubscriptionConfirmed ()
{
Object oo = get_Value(COLUMNNAME_IsSubscriptionConfirmed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class);
}
@Override
public void setM_ShipmentSchedule(de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule)
{
set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule);
}
/** Set Lieferdisposition.
@param M_ShipmentSchedule_ID Lieferdisposition */
@Override
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
/** Get Lieferdisposition.
@return Lieferdisposition */
@Override
public int getM_ShipmentSchedule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Status AD_Reference_ID=540002
* Reference name: C_SubscriptionProgress Status
*/
public static final int STATUS_AD_Reference_ID=540002;
/** Geplant = P */
public static final String STATUS_Geplant = "P";
/** Lieferung Offen = O */
public static final String STATUS_LieferungOffen = "O";
/** Ausgeliefert = D */
public static final String STATUS_Ausgeliefert = "D";
/** Wird kommissioniert = C */
public static final String STATUS_WirdKommissioniert = "C";
/** Ausgeführt = E */
public static final String STATUS_Ausgefuehrt = "E";
/** Verzögert = H */
public static final String STATUS_Verzoegert = "H";
/** Set Status.
@param Status
Status of the currently running check
*/
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | zoosky/metasfresh | de.metas.contracts/src/main/java-gen/de/metas/flatrate/model/X_C_SubscriptionProgress.java | 4,903 | /** Geplant = P */ | block_comment | nl | /** Generated Model - DO NOT CHANGE */
package de.metas.flatrate.model;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.Properties;
import org.compiere.util.Env;
/** Generated Model for C_SubscriptionProgress
* @author Adempiere (generated)
*/
@SuppressWarnings("javadoc")
public class X_C_SubscriptionProgress extends org.compiere.model.PO implements I_C_SubscriptionProgress, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -626565630L;
/** Standard Constructor */
public X_C_SubscriptionProgress (Properties ctx, int C_SubscriptionProgress_ID, String trxName)
{
super (ctx, C_SubscriptionProgress_ID, trxName);
/** if (C_SubscriptionProgress_ID == 0)
{
setC_Flatrate_Term_ID (0);
setC_SubscriptionProgress_ID (0);
setDropShip_BPartner_ID (0);
setDropShip_Location_ID (0);
setEventType (null);
setIsSubscriptionConfirmed (false);
// N
setProcessed (false);
// N
setStatus (null);
// P
} */
}
/** Load Constructor */
public X_C_SubscriptionProgress (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
@Override
public de.metas.flatrate.model.I_C_Flatrate_Term getC_Flatrate_Term() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class);
}
@Override
public void setC_Flatrate_Term(de.metas.flatrate.model.I_C_Flatrate_Term C_Flatrate_Term)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_Term_ID, de.metas.flatrate.model.I_C_Flatrate_Term.class, C_Flatrate_Term);
}
/** Set Pauschale - Vertragsperiode.
@param C_Flatrate_Term_ID Pauschale - Vertragsperiode */
@Override
public void setC_Flatrate_Term_ID (int C_Flatrate_Term_ID)
{
if (C_Flatrate_Term_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Term_ID, Integer.valueOf(C_Flatrate_Term_ID));
}
/** Get Pauschale - Vertragsperiode.
@return Pauschale - Vertragsperiode */
@Override
public int getC_Flatrate_Term_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_Term_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* ContractStatus AD_Reference_ID=540000
* Reference name: SubscriptionStatus
*/
public static final int CONTRACTSTATUS_AD_Reference_ID=540000;
/** Laufend = Ru */
public static final String CONTRACTSTATUS_Laufend = "Ru";
/** Lieferpause = Pa */
public static final String CONTRACTSTATUS_Lieferpause = "Pa";
/** Beendet = En */
public static final String CONTRACTSTATUS_Beendet = "En";
/** Gekündigt = Qu */
public static final String CONTRACTSTATUS_Gekuendigt = "Qu";
/** Wartet auf Bestätigung = St */
public static final String CONTRACTSTATUS_WartetAufBestaetigung = "St";
/** Info = In */
public static final String CONTRACTSTATUS_Info = "In";
/** Noch nicht begonnen = Wa */
public static final String CONTRACTSTATUS_NochNichtBegonnen = "Wa";
/** Set Vertrags-Status.
@param ContractStatus Vertrags-Status */
@Override
public void setContractStatus (java.lang.String ContractStatus)
{
set_Value (COLUMNNAME_ContractStatus, ContractStatus);
}
/** Get Vertrags-Status.
@return Vertrags-Status */
@Override
public java.lang.String getContractStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_ContractStatus);
}
/** Set Abo-Verlauf.
@param C_SubscriptionProgress_ID Abo-Verlauf */
@Override
public void setC_SubscriptionProgress_ID (int C_SubscriptionProgress_ID)
{
if (C_SubscriptionProgress_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_SubscriptionProgress_ID, Integer.valueOf(C_SubscriptionProgress_ID));
}
/** Get Abo-Verlauf.
@return Abo-Verlauf */
@Override
public int getC_SubscriptionProgress_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_SubscriptionProgress_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner getDropShip_BPartner() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class);
}
@Override
public void setDropShip_BPartner(org.compiere.model.I_C_BPartner DropShip_BPartner)
{
set_ValueFromPO(COLUMNNAME_DropShip_BPartner_ID, org.compiere.model.I_C_BPartner.class, DropShip_BPartner);
}
/** Set Lieferempfänger.
@param DropShip_BPartner_ID
Business Partner to ship to
*/
@Override
public void setDropShip_BPartner_ID (int DropShip_BPartner_ID)
{
if (DropShip_BPartner_ID < 1)
set_Value (COLUMNNAME_DropShip_BPartner_ID, null);
else
set_Value (COLUMNNAME_DropShip_BPartner_ID, Integer.valueOf(DropShip_BPartner_ID));
}
/** Get Lieferempfänger.
@return Business Partner to ship to
*/
@Override
public int getDropShip_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_BPartner_Location getDropShip_Location() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class);
}
@Override
public void setDropShip_Location(org.compiere.model.I_C_BPartner_Location DropShip_Location)
{
set_ValueFromPO(COLUMNNAME_DropShip_Location_ID, org.compiere.model.I_C_BPartner_Location.class, DropShip_Location);
}
/** Set Lieferadresse.
@param DropShip_Location_ID
Business Partner Location for shipping to
*/
@Override
public void setDropShip_Location_ID (int DropShip_Location_ID)
{
if (DropShip_Location_ID < 1)
set_Value (COLUMNNAME_DropShip_Location_ID, null);
else
set_Value (COLUMNNAME_DropShip_Location_ID, Integer.valueOf(DropShip_Location_ID));
}
/** Get Lieferadresse.
@return Business Partner Location for shipping to
*/
@Override
public int getDropShip_Location_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_Location_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getDropShip_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setDropShip_User(org.compiere.model.I_AD_User DropShip_User)
{
set_ValueFromPO(COLUMNNAME_DropShip_User_ID, org.compiere.model.I_AD_User.class, DropShip_User);
}
/** Set Lieferkontakt.
@param DropShip_User_ID
Business Partner Contact for drop shipment
*/
@Override
public void setDropShip_User_ID (int DropShip_User_ID)
{
if (DropShip_User_ID < 1)
set_Value (COLUMNNAME_DropShip_User_ID, null);
else
set_Value (COLUMNNAME_DropShip_User_ID, Integer.valueOf(DropShip_User_ID));
}
/** Get Lieferkontakt.
@return Business Partner Contact for drop shipment
*/
@Override
public int getDropShip_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DropShip_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Datum.
@param EventDate Datum */
@Override
public void setEventDate (java.sql.Timestamp EventDate)
{
set_Value (COLUMNNAME_EventDate, EventDate);
}
/** Get Datum.
@return Datum */
@Override
public java.sql.Timestamp getEventDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_EventDate);
}
/**
* EventType AD_Reference_ID=540013
* Reference name: C_SubscriptionProgress EventType
*/
public static final int EVENTTYPE_AD_Reference_ID=540013;
/** Lieferung = DE */
public static final String EVENTTYPE_Lieferung = "DE";
/** Abowechsel = SU */
public static final String EVENTTYPE_Abowechsel = "SU";
/** Statuswechsel = ST */
public static final String EVENTTYPE_Statuswechsel = "ST";
/** Abo-Ende = SE */
public static final String EVENTTYPE_Abo_Ende = "SE";
/** Abo-Beginn = SB */
public static final String EVENTTYPE_Abo_Beginn = "SB";
/** Abo-Autoverlängerung = SR */
public static final String EVENTTYPE_Abo_Autoverlaengerung = "SR";
/** Abopause-Beginn = PB */
public static final String EVENTTYPE_Abopause_Beginn = "PB";
/** Abopause-Ende = PE */
public static final String EVENTTYPE_Abopause_Ende = "PE";
/** Set Ereignisart.
@param EventType Ereignisart */
@Override
public void setEventType (java.lang.String EventType)
{
set_ValueNoCheck (COLUMNNAME_EventType, EventType);
}
/** Get Ereignisart.
@return Ereignisart */
@Override
public java.lang.String getEventType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EventType);
}
/** Set Bestätigung eingegangen.
@param IsSubscriptionConfirmed Bestätigung eingegangen */
@Override
public void setIsSubscriptionConfirmed (boolean IsSubscriptionConfirmed)
{
set_Value (COLUMNNAME_IsSubscriptionConfirmed, Boolean.valueOf(IsSubscriptionConfirmed));
}
/** Get Bestätigung eingegangen.
@return Bestätigung eingegangen */
@Override
public boolean isSubscriptionConfirmed ()
{
Object oo = get_Value(COLUMNNAME_IsSubscriptionConfirmed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class);
}
@Override
public void setM_ShipmentSchedule(de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule)
{
set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule);
}
/** Set Lieferdisposition.
@param M_ShipmentSchedule_ID Lieferdisposition */
@Override
public void setM_ShipmentSchedule_ID (int M_ShipmentSchedule_ID)
{
if (M_ShipmentSchedule_ID < 1)
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null);
else
set_Value (COLUMNNAME_M_ShipmentSchedule_ID, Integer.valueOf(M_ShipmentSchedule_ID));
}
/** Get Lieferdisposition.
@return Lieferdisposition */
@Override
public int getM_ShipmentSchedule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipmentSchedule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* Status AD_Reference_ID=540002
* Reference name: C_SubscriptionProgress Status
*/
public static final int STATUS_AD_Reference_ID=540002;
/** Geplant = P<SUF>*/
public static final String STATUS_Geplant = "P";
/** Lieferung Offen = O */
public static final String STATUS_LieferungOffen = "O";
/** Ausgeliefert = D */
public static final String STATUS_Ausgeliefert = "D";
/** Wird kommissioniert = C */
public static final String STATUS_WirdKommissioniert = "C";
/** Ausgeführt = E */
public static final String STATUS_Ausgefuehrt = "E";
/** Verzögert = H */
public static final String STATUS_Verzoegert = "H";
/** Set Status.
@param Status
Status of the currently running check
*/
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
@Override
public java.lang.String getStatus ()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | False |
428 | 111105_4 | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| Donneh/ovcasus | src/ReizigerOracleDaoImpl.java | 1,772 | /**
* Verwijder een reiziger.
* @param reiziger
* @return boolean
*/ | block_comment | nl | import javax.swing.plaf.nimbus.State;
import javax.xml.transform.Result;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ReizigerOracleDaoImpl extends OracleBaseDao implements ReizigerDao {
/**
* Returned alle reizigers.
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findAll() {
try {
Statement stmt = getConnection().createStatement();
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM FROM REIZIGER";
ResultSet rs = stmt.executeQuery(query);
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while(rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public Reiziger findById(int id) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
return buildreizigerobject(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Returned alle reizigers met specifieke geboortedatum.
* @param GBdatum
* @return ArrayList<Reiziger>
*/
public List<Reiziger> findByGBdatum(Date GBdatum) {
try {
String query = "SELECT REIZIGERID, VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM " +
"FROM REIZIGER WHERE GEBOORTEDATUM = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setDate(1, GBdatum);
ResultSet rs = stmt.executeQuery();
ArrayList<Reiziger> reizigers = new ArrayList<Reiziger>();
while (rs.next()) {
reizigers.add(buildreizigerobject(rs));
}
return reizigers;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Slaat een reiziger op.
* @param reiziger
* @return
*/
public Reiziger save(Reiziger reiziger) {
try {
String query = "INSERT INTO REIZIGER" +
"(VOORLETTERS, TUSSENVOEGSEL, ACHTERNAAM, GEBOORTEDATUM) VALUES " +
"(?, ?, ?, ?)";
String generatedColumns[] = { "REIZIGERID" };
PreparedStatement stmt = getConnection().prepareStatement(query, generatedColumns);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
if(rs.next()) {
return findById(rs.getInt(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Past een opgeslagen reiziger aan.
* @param reiziger
* @return Reiziger
*/
public Reiziger update(Reiziger reiziger) {
try {
String query =
"UPDATE REIZIGER SET " +
"VOORLETTERS = ?, TUSSENVOEGSEL = ?, ACHTERNAAM = ?, GEBOORTEDATUM = ? " +
"WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setString(1, reiziger.getVoorletters());
stmt.setString(2, reiziger.getTussenveogsel());
stmt.setString(3, reiziger.getAchternaam());
stmt.setDate(4, reiziger.getGeboortedatum());
stmt.setInt(5, reiziger.getId());
ResultSet rs = stmt.executeQuery();
if (rs.rowUpdated()) {
return findById(reiziger.getId());
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* Verwijder een reiziger.<SUF>*/
public boolean delete(Reiziger reiziger) {
try {
String query = "DELETE FROM REIZIGER WHERE REIZIGERID = ?";
PreparedStatement stmt = getConnection().prepareStatement(query);
stmt.setInt(1, reiziger.getId());
int rs = stmt.executeUpdate();
return rs > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
private Reiziger buildreizigerobject(ResultSet rs) throws SQLException {
int id = rs.getInt("REIZIGERID");
Reiziger reiziger = new Reiziger();
reiziger.setId(id);
reiziger.setVoorletters(rs.getString("VOORLETTERS"));
reiziger.setTussenveogsel(rs.getString("TUSSENVOEGSEL"));
reiziger.setAchternaam(rs.getString("ACHTERNAAM"));
reiziger.setGeboortedatum(rs.getDate("GEBOORTEDATUM"));
OVChipkaartDaoImpl ovdao = new OVChipkaartDaoImpl();
reiziger.setKaarten(ovdao.findByReiziger(id));
AdresDaoImpl adao = new AdresDaoImpl();
reiziger.setAdressen(adao.findByReiziger(id));
return reiziger;
}
}
| True |
3,923 | 140953_15 | package de.andlabs.teleporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import de.andlabs.teleporter.plugin.ITeleporterPlugIn;
public class QueryMultiplexer {
private static final String TAG = "Multiplexer";
private Place orig;
private Place dest;
public ArrayList<Ride> rides;
public ArrayList<ITeleporterPlugIn> plugIns;
private ArrayList<Ride> nextRides;
private Map<String, Integer> priorities;
private long mLastSearchTimestamp;
private BroadcastReceiver mPluginResponseReceiver;
private final Context ctx;
private Handler mUpdateHandler;
private Thread worker;
public QueryMultiplexer(Context ctx, Place o, Place d) {
this.ctx = ctx;
orig = o;
dest = d;
nextRides = new ArrayList<Ride>();
rides = new ArrayList<Ride>() {
@Override
public boolean add(Ride object) {
if(!contains(object))
return super.add(object);
else
return false;
}
@Override
public boolean addAll(Collection<? extends Ride> collection) {
for(Ride r : collection)
if(!contains(r))
super.add(r);
return true;
}
@Override
public void add(int index, Ride object) {
if(!contains(object))
super.add(index, object);
}
};
plugIns = new ArrayList<ITeleporterPlugIn>();
SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE);
try {
for (String p : plugInSettings.getAll().keySet()) {
Log.d(TAG, "plugin "+p);
if (plugInSettings.getBoolean(p, false)){
Log.d(TAG, "add plugin "+p);
plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance());
}
}
} catch (Exception e) {
Log.e(TAG, "Schade!");
e.printStackTrace();
}
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
this.mUpdateHandler = new Handler();
this.mPluginResponseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Plugin Response Received.");
final int duration = intent.getIntExtra("dur", -1);
final Ride ride = new Ride();
ride.duration = duration;
ride.orig = orig;
ride.dest = dest;
ride.mode = Ride.MODE_DRIVE;
ride.fun = 1;
ride.eco = 1;
ride.fast = 5;
ride.social = 1;
ride.green = 1;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
nextRides.add(ride);
}
});
}
};
this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE"));
}
public boolean searchLater() {
// TODO just query just plugins that ...
// TODO use ThreadPoolExecutor ...
if (worker != null && worker.isAlive())
return false;
worker = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (ITeleporterPlugIn p : plugIns) {
Log.d(TAG, "query plugin "+p);
final long requestTimestamp;
if(mLastSearchTimestamp == 0 ) {
requestTimestamp = System.currentTimeMillis();
} else {
requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes
}
nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp)));
mLastSearchTimestamp = requestTimestamp;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
rides.addAll(nextRides);
nextRides.clear();
((RidesActivity)ctx).datasetChanged();
}
});
}
Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST");
requestIntent.putExtra("origLatitude", orig.lat);
requestIntent.putExtra("origLongitude", orig.lon);
requestIntent.putExtra("destLatitude", dest.lat);
requestIntent.putExtra("destLongitude", dest.lon);
ctx.sendBroadcast(requestIntent);
}
});
worker.start();
return true;
}
public void sort() {
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
// Collections.sort(rides, new Comparator<Ride>() {
//
// @Override
// public int compare(Ride r1, Ride r2) {
// // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt)
// // TODO Faktoren normalisieren
// int score1= r1.fun * priorities.get("fun") +
// r1.eco * priorities.get("eco") +
// r1.fast * priorities.get("fast") +
// r1.green * priorities.get("green") +
// r1.social * priorities.get("social");
// int score2= r2.fun * priorities.get("fun") +
// r2.eco * priorities.get("eco") +
// r2.fast * priorities.get("fast") +
// r2.green * priorities.get("green") +
// r2.social * priorities.get("social");
// // Log.d("aha", "score1: "+score1 + ", score2: "+score2);
// if (score1 < score2)
// return 1;
// else if (score1 > score2)
// return -1;
// else {
// if (r1.dep.after(r2.dep))
// return 1;
// if (r1.dep.before(r2.dep))
// return -1;
// return 0;
// }
// }
// });
}
}
| orangeman/teleportr | src/de/andlabs/teleporter/QueryMultiplexer.java | 1,965 | // r2.green * priorities.get("green") + | line_comment | nl | package de.andlabs.teleporter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.Parcelable;
import android.util.Log;
import de.andlabs.teleporter.plugin.ITeleporterPlugIn;
public class QueryMultiplexer {
private static final String TAG = "Multiplexer";
private Place orig;
private Place dest;
public ArrayList<Ride> rides;
public ArrayList<ITeleporterPlugIn> plugIns;
private ArrayList<Ride> nextRides;
private Map<String, Integer> priorities;
private long mLastSearchTimestamp;
private BroadcastReceiver mPluginResponseReceiver;
private final Context ctx;
private Handler mUpdateHandler;
private Thread worker;
public QueryMultiplexer(Context ctx, Place o, Place d) {
this.ctx = ctx;
orig = o;
dest = d;
nextRides = new ArrayList<Ride>();
rides = new ArrayList<Ride>() {
@Override
public boolean add(Ride object) {
if(!contains(object))
return super.add(object);
else
return false;
}
@Override
public boolean addAll(Collection<? extends Ride> collection) {
for(Ride r : collection)
if(!contains(r))
super.add(r);
return true;
}
@Override
public void add(int index, Ride object) {
if(!contains(object))
super.add(index, object);
}
};
plugIns = new ArrayList<ITeleporterPlugIn>();
SharedPreferences plugInSettings = ctx.getSharedPreferences("plugIns", ctx.MODE_PRIVATE);
try {
for (String p : plugInSettings.getAll().keySet()) {
Log.d(TAG, "plugin "+p);
if (plugInSettings.getBoolean(p, false)){
Log.d(TAG, "add plugin "+p);
plugIns.add((ITeleporterPlugIn) Class.forName("de.andlabs.teleporter.plugin."+p).newInstance());
}
}
} catch (Exception e) {
Log.e(TAG, "Schade!");
e.printStackTrace();
}
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
this.mUpdateHandler = new Handler();
this.mPluginResponseReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "Plugin Response Received.");
final int duration = intent.getIntExtra("dur", -1);
final Ride ride = new Ride();
ride.duration = duration;
ride.orig = orig;
ride.dest = dest;
ride.mode = Ride.MODE_DRIVE;
ride.fun = 1;
ride.eco = 1;
ride.fast = 5;
ride.social = 1;
ride.green = 1;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
nextRides.add(ride);
}
});
}
};
this.ctx.registerReceiver(this.mPluginResponseReceiver, new IntentFilter("org.teleporter.intent.action.RECEIVE_RESPONSE"));
}
public boolean searchLater() {
// TODO just query just plugins that ...
// TODO use ThreadPoolExecutor ...
if (worker != null && worker.isAlive())
return false;
worker = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (ITeleporterPlugIn p : plugIns) {
Log.d(TAG, "query plugin "+p);
final long requestTimestamp;
if(mLastSearchTimestamp == 0 ) {
requestTimestamp = System.currentTimeMillis();
} else {
requestTimestamp = mLastSearchTimestamp + 300000; // 5 Minutes
}
nextRides.addAll(p.find(orig, dest, new Date(requestTimestamp)));
mLastSearchTimestamp = requestTimestamp;
mUpdateHandler.post(new Runnable() {
@Override
public void run() {
rides.addAll(nextRides);
nextRides.clear();
((RidesActivity)ctx).datasetChanged();
}
});
}
Intent requestIntent = new Intent("org.teleporter.intent.action.RECEIVE_REQUEST");
requestIntent.putExtra("origLatitude", orig.lat);
requestIntent.putExtra("origLongitude", orig.lon);
requestIntent.putExtra("destLatitude", dest.lat);
requestIntent.putExtra("destLongitude", dest.lon);
ctx.sendBroadcast(requestIntent);
}
});
worker.start();
return true;
}
public void sort() {
priorities = (Map<String, Integer>) ctx.getSharedPreferences("priorities", ctx.MODE_PRIVATE).getAll();
// Collections.sort(rides, new Comparator<Ride>() {
//
// @Override
// public int compare(Ride r1, Ride r2) {
// // TODO Neue Faktor für Score: "Quickness" (Abfahrtszeit minus Jetzt)
// // TODO Faktoren normalisieren
// int score1= r1.fun * priorities.get("fun") +
// r1.eco * priorities.get("eco") +
// r1.fast * priorities.get("fast") +
// r1.green * priorities.get("green") +
// r1.social * priorities.get("social");
// int score2= r2.fun * priorities.get("fun") +
// r2.eco * priorities.get("eco") +
// r2.fast * priorities.get("fast") +
// r2.green *<SUF>
// r2.social * priorities.get("social");
// // Log.d("aha", "score1: "+score1 + ", score2: "+score2);
// if (score1 < score2)
// return 1;
// else if (score1 > score2)
// return -1;
// else {
// if (r1.dep.after(r2.dep))
// return 1;
// if (r1.dep.before(r2.dep))
// return -1;
// return 0;
// }
// }
// });
}
}
| False |
4,290 | 209699_18 | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density parameters
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| sgano/JSatTrak | src/name/gano/astro/Atmosphere.java | 3,164 | // Height, density parameters | line_comment | nl | /*
* Static methods dealing with the Atmosphere
* =====================================================================
* This file is part of JSatTrak.
*
* Copyright 2007-2013 Shawn E. Gano
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =====================================================================
*/
package name.gano.astro;
import name.gano.astro.bodies.Sun;
/**
*
* @author sgano
*/
public class Atmosphere
{
/**
* Computes the acceleration due to the atmospheric drag.
* (uses modified Harris-Priester model)
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r Satellite position vector in the inertial system [m]
* @param v Satellite velocity vector in the inertial system [m/s]
* @param T Transformation matrix to true-of-date inertial system
* @param Area Cross-section [m^2]
* @param mass Spacecraft mass [kg]
* @param CD Drag coefficient
* @return Acceleration (a=d^2r/dt^2) [m/s^2]
*/
public static double[] AccelDrag(double Mjd_TT, final double[] r, final double[] v,
final double[][] T, double Area, double mass, double CD)
{
// Constants
// Earth angular velocity vector [rad/s]
final double[] omega = {0.0, 0.0, 7.29212e-5};
// Variables
double v_abs, dens;
double[] r_tod = new double[3];
double[] v_tod = new double[3];
double[] v_rel = new double[3];
double[] a_tod = new double[3];
double[][] T_trp = new double[3][3];
// Transformation matrix to ICRF/EME2000 system
T_trp = MathUtils.transpose(T);
// Position and velocity in true-of-date system
r_tod = MathUtils.mult(T, r);
v_tod = MathUtils.mult(T, v);
// Velocity relative to the Earth's atmosphere
v_rel = MathUtils.sub(v_tod, MathUtils.cross(omega, r_tod));
v_abs = MathUtils.norm(v_rel);
// Atmospheric density due to modified Harris-Priester model
dens = Density_HP(Mjd_TT, r_tod);
// Acceleration
a_tod = MathUtils.scale(v_rel, -0.5 * CD * (Area / mass) * dens * v_abs);
return MathUtils.mult(T_trp, a_tod);
} // accellDrag
/**
* Computes the atmospheric density for the modified Harris-Priester model.
*
* @param Mjd_TT Terrestrial Time (Modified Julian Date)
* @param r_tod Satellite position vector in the inertial system [m]
* @return Density [kg/m^3]
*/
public static double Density_HP(double Mjd_TT, final double[] r_tod)
{
// Constants
final double upper_limit = 1000.0; // Upper height limit [km]
final double lower_limit = 100.0; // Lower height limit [km]
final double ra_lag = 0.523599; // Right ascension lag [rad]
final int n_prm = 3; // Harris-Priester parameter
// 2(6) low(high) inclination
// Harris-Priester atmospheric density model parameters
// Height [km], minimum density, maximum density [gm/km^3]
final int N_Coef = 50;
final double[] h = {
100.0, 120.0, 130.0, 140.0, 150.0, 160.0, 170.0, 180.0, 190.0, 200.0,
210.0, 220.0, 230.0, 240.0, 250.0, 260.0, 270.0, 280.0, 290.0, 300.0,
320.0, 340.0, 360.0, 380.0, 400.0, 420.0, 440.0, 460.0, 480.0, 500.0,
520.0, 540.0, 560.0, 580.0, 600.0, 620.0, 640.0, 660.0, 680.0, 700.0,
720.0, 740.0, 760.0, 780.0, 800.0, 840.0, 880.0, 920.0, 960.0, 1000.0
};
final double[] c_min = {
4.974e+05, 2.490e+04, 8.377e+03, 3.899e+03, 2.122e+03, 1.263e+03,
8.008e+02, 5.283e+02, 3.617e+02, 2.557e+02, 1.839e+02, 1.341e+02,
9.949e+01, 7.488e+01, 5.709e+01, 4.403e+01, 3.430e+01, 2.697e+01,
2.139e+01, 1.708e+01, 1.099e+01, 7.214e+00, 4.824e+00, 3.274e+00,
2.249e+00, 1.558e+00, 1.091e+00, 7.701e-01, 5.474e-01, 3.916e-01,
2.819e-01, 2.042e-01, 1.488e-01, 1.092e-01, 8.070e-02, 6.012e-02,
4.519e-02, 3.430e-02, 2.632e-02, 2.043e-02, 1.607e-02, 1.281e-02,
1.036e-02, 8.496e-03, 7.069e-03, 4.680e-03, 3.200e-03, 2.210e-03,
1.560e-03, 1.150e-03
};
final double[] c_max = {
4.974e+05, 2.490e+04, 8.710e+03, 4.059e+03, 2.215e+03, 1.344e+03,
8.758e+02, 6.010e+02, 4.297e+02, 3.162e+02, 2.396e+02, 1.853e+02,
1.455e+02, 1.157e+02, 9.308e+01, 7.555e+01, 6.182e+01, 5.095e+01,
4.226e+01, 3.526e+01, 2.511e+01, 1.819e+01, 1.337e+01, 9.955e+00,
7.492e+00, 5.684e+00, 4.355e+00, 3.362e+00, 2.612e+00, 2.042e+00,
1.605e+00, 1.267e+00, 1.005e+00, 7.997e-01, 6.390e-01, 5.123e-01,
4.121e-01, 3.325e-01, 2.691e-01, 2.185e-01, 1.779e-01, 1.452e-01,
1.190e-01, 9.776e-02, 8.059e-02, 5.741e-02, 4.210e-02, 3.130e-02,
2.360e-02, 1.810e-02
};
// Variables
int i, ih; // Height section variables
double height; // Earth flattening
double dec_Sun, ra_Sun, c_dec; // Sun declination, right asc.
double c_psi2; // Harris-Priester modification
double density, h_min, h_max, d_min, d_max;// Height, density<SUF>
double[] r_Sun = new double[3]; // Sun position
double[] u = new double[3]; // Apex of diurnal bulge
// Satellite height (in km)
height = GeoFunctions.GeodeticLLA(r_tod, Mjd_TT)[2] / 1000.0; //Geodetic(r_tod) / 1000.0; // [km]
// Exit with zero density outside height model limits
if (height >= upper_limit || height <= lower_limit)
{
return 0.0;
}
// Sun right ascension, declination
r_Sun = Sun.calculateSunPositionLowTT(Mjd_TT);
ra_Sun = Math.atan2(r_Sun[1], r_Sun[0]);
dec_Sun = Math.atan2(r_Sun[2], Math.sqrt(Math.pow(r_Sun[0], 2) + Math.pow(r_Sun[1], 2)));
// Unit vector u towards the apex of the diurnal bulge
// in inertial geocentric coordinates
c_dec = Math.cos(dec_Sun);
u[0] = c_dec * Math.cos(ra_Sun + ra_lag);
u[1] = c_dec * Math.sin(ra_Sun + ra_lag);
u[2] = Math.sin(dec_Sun);
// Cosine of half angle between satellite position vector and
// apex of diurnal bulge
c_psi2 = 0.5 + 0.5 * MathUtils.dot(r_tod, u) / MathUtils.norm(r_tod);
// Height index search and exponential density interpolation
ih = 0; // section index reset
for (i = 0; i < N_Coef - 1; i++) // loop over N_Coef height regimes
{
if (height >= h[i] && height < h[i + 1])
{
ih = i; // ih identifies height section
break;
}
}
h_min = (h[ih] - h[ih + 1]) / Math.log(c_min[ih + 1] / c_min[ih]);
h_max = (h[ih] - h[ih + 1]) / Math.log(c_max[ih + 1] / c_max[ih]);
d_min = c_min[ih] * Math.exp((h[ih] - height) / h_min);
d_max = c_max[ih] * Math.exp((h[ih] - height) / h_max);
// Density computation
density = d_min + (d_max - d_min) * Math.pow(c_psi2, n_prm);
return density * 1.0e-12; // [kg/m^3]
} // Density_HP
}
| False |
3,812 | 76776_3 | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange scheduleSelf --");
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
| nicolas-raoul/AnyMemo | src/org/color/ColorDialog.java | 2,476 | // Log.d(TAG, "onLevelChange scheduleSelf --"); | line_comment | nl | package org.color;
import org.liberty.android.fantastischmemo.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.util.StateSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class ColorDialog extends AlertDialog implements OnSeekBarChangeListener, OnClickListener {
public interface OnClickListener {
public void onClick(View view, int color);
}
private SeekBar mHue;
private SeekBar mSaturation;
private SeekBar mValue;
private ColorDialog.OnClickListener mListener;
private int mColor;
private View mView;
private GradientDrawable mPreviewDrawable;
public ColorDialog(Context context, View view, int color, OnClickListener listener) {
super(context);
mView = view;
mListener = listener;
Resources res = context.getResources();
setTitle(res.getText(R.string.color_dialog_title));
setButton(BUTTON_POSITIVE, res.getText(android.R.string.yes), this);
setButton(BUTTON_NEGATIVE, res.getText(android.R.string.cancel), this);
View root = LayoutInflater.from(context).inflate(R.layout.color_picker, null);
setView(root);
View preview = root.findViewById(R.id.preview);
mPreviewDrawable = new GradientDrawable();
// 2 pix more than color_picker_frame's radius
mPreviewDrawable.setCornerRadius(7);
Drawable[] layers = {
mPreviewDrawable,
res.getDrawable(R.drawable.color_picker_frame),
};
preview.setBackgroundDrawable(new LayerDrawable(layers));
mHue = (SeekBar) root.findViewById(R.id.hue);
mSaturation = (SeekBar) root.findViewById(R.id.saturation);
mValue = (SeekBar) root.findViewById(R.id.value);
mColor = color;
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
int h = (int) (hsv[0] * mHue.getMax() / 360);
int s = (int) (hsv[1] * mSaturation.getMax());
int v = (int) (hsv[2] * mValue.getMax());
setupSeekBar(mHue, R.string.color_h, h, res);
setupSeekBar(mSaturation, R.string.color_s, s, res);
setupSeekBar(mValue, R.string.color_v, v, res);
updatePreview(color);
}
private void setupSeekBar(SeekBar seekBar, int id, int value, Resources res) {
seekBar.setProgressDrawable(new TextSeekBarDrawable(res, id, value < seekBar.getMax() / 2));
seekBar.setProgress(value);
seekBar.setOnSeekBarChangeListener(this);
}
private void update() {
float[] hsv = {
360 * mHue.getProgress() / (float) mHue.getMax(),
mSaturation.getProgress() / (float) mSaturation.getMax(),
mValue.getProgress() / (float) mValue.getMax(),
};
mColor = Color.HSVToColor(hsv);
updatePreview(mColor);
}
private void updatePreview(int color) {
mPreviewDrawable.setColor(color);
mPreviewDrawable.invalidateSelf();
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
update();
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onClick(mView, mColor);
}
dismiss();
}
static final int[] STATE_FOCUSED = {android.R.attr.state_focused};
static final int[] STATE_PRESSED = {android.R.attr.state_pressed};
class TextSeekBarDrawable extends Drawable implements Runnable {
private static final String TAG = "TextSeekBarDrawable";
private static final long DELAY = 25;
private String mText;
private Drawable mProgress;
private Paint mPaint;
private Paint mOutlinePaint;
private float mTextWidth;
private boolean mActive;
private float mTextX;
private float mDelta;
public TextSeekBarDrawable(Resources res, int id, boolean labelOnRight) {
mText = res.getString(id);
mProgress = res.getDrawable(android.R.drawable.progress_horizontal);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setTextSize(16);
mPaint.setColor(0xff000000);
mOutlinePaint = new Paint(mPaint);
mOutlinePaint.setStyle(Style.STROKE);
mOutlinePaint.setStrokeWidth(3);
mOutlinePaint.setColor(0xbbffc300);
mOutlinePaint.setMaskFilter(new BlurMaskFilter(1, Blur.NORMAL));
mTextWidth = mOutlinePaint.measureText(mText);
mTextX = labelOnRight? 1 : 0;
}
@Override
protected void onBoundsChange(Rect bounds) {
mProgress.setBounds(bounds);
}
@Override
protected boolean onStateChange(int[] state) {
mActive = StateSet.stateSetMatches(STATE_FOCUSED, state) | StateSet.stateSetMatches(STATE_PRESSED, state);
invalidateSelf();
return false;
}
@Override
public boolean isStateful() {
return true;
}
@Override
protected boolean onLevelChange(int level) {
// Log.d(TAG, "onLevelChange " + level);
if (level < 4000 && mDelta <= 0) {
mDelta = 0.05f;
// Log.d(TAG, "onLevelChange scheduleSelf ++");
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
} else
if (level > 6000 && mDelta >= 0) {
// Log.d(TAG, "onLevelChange<SUF>
mDelta = -0.05f;
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
return mProgress.setLevel(level);
}
@Override
public void draw(Canvas canvas) {
mProgress.draw(canvas);
Rect bounds = getBounds();
float x = 6 + mTextX * (bounds.width() - mTextWidth - 6 - 6);
float y = (bounds.height() + mPaint.getTextSize()) / 2;
mOutlinePaint.setAlpha(mActive? 255 : 255 / 2);
mPaint.setAlpha(mActive? 255 : 255 / 2);
canvas.drawText(mText, x, y, mOutlinePaint);
canvas.drawText(mText, x, y, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
public void run() {
mTextX += mDelta;
if (mTextX >= 1) {
mTextX = 1;
mDelta = 0;
} else
if (mTextX <= 0) {
mTextX = 0;
mDelta = 0;
} else {
scheduleSelf(this, SystemClock.uptimeMillis() + DELAY);
}
invalidateSelf();
// Log.d(TAG, "run " + mTextX + " " + SystemClock.uptimeMillis());
}
}
}
| False |
4,646 | 67131_3 | package KartoffelKanaalPlugin.plugin.kartoffelsystems.PulserSystem;
import KartoffelKanaalPlugin.plugin.AdvancedChat;
import KartoffelKanaalPlugin.plugin.AttribSystem;
import KartoffelKanaalPlugin.plugin.StoreTechnics;
import KartoffelKanaalPlugin.plugin.kartoffelsystems.PlayerSystem.Person;
import org.bukkit.command.CommandSender;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.logging.Logger;
public abstract class PNTechTextProvFormatted extends PNTechTextProv {
protected String[] parameters;
protected PNTechTextProvFormatted(byte[] src) {
super(src);
this.initialize(src);
}
protected PNTechTextProvFormatted(String[] parameters, boolean invisible, int ID, PulserNotifStandard base){
super(invisible, ID, base);
if(parameters == null)parameters = new String[0];
if(parameters.length > 100){
String[] newparams = new String[100];
System.arraycopy(parameters, 0, newparams, 0, 100);
}
this.parameters = parameters;
}
@Override
public String getTypeName(){
return super.getTypeName() + "Formatted";
}
public byte getTextProvType(){return 2;}
public abstract byte getFormattedType();
protected abstract byte getCorrectAmountParameters();
protected abstract boolean isSectionSignFormatAccepted(int index);
protected abstract int getNamedParameterIndex(String key);
protected boolean setParameter(int index, String value){
if(index < 0 || index >= this.parameters.length)return false;
parameters[index] = value;
this.notifyChange();
this.onParametersChanged();
return true;
}
protected boolean setNamedParameter(String key, String value){
int index = this.getNamedParameterIndex(key);
return this.setParameter(index, value);
}
protected abstract void onParametersChanged();
protected abstract byte getParameterViewAccessLevel();
protected abstract byte getParameterChangeAccessLevel(int paramID);
protected abstract String[] getPossibleKeys();
public String[] copyParameters(){
if(this.parameters == null)return new String[this.getCorrectAmountParameters()];
String[] s = new String[this.parameters.length];
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] != null)s[i] = new String(this.parameters[i]);
}
return s;
}
@Override
public int getEstimatedSize(){
if(this.parameters == null)return PNTechTextProvFormatted.generalInfoLength();
int l = this.parameters.length * 2;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)continue;
l += this.parameters[i].length();
}
return PNTechTextProvFormatted.generalInfoLength() + l;
}
protected static PNTechTextProvFormatted loadFromBytes(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return null;
byte t = src[PNTechTextProv.generalInfoLength()];//De hoogste bit hoeft er niet afgehaald te worden aangezien die geen functie heeft en dus niet gebruikt zo mogen worden. Als de hoogste bit dus voor verwarring zorgt, betekent dat dat er iets fout is.
if(t == 1){
return new PNTechTextProvFormattedVideo(src);
}
//System.out.println(" PNTechTextProvFormatted.loadFromBytes: PNTechTextProv geladen, onbekend TextProvType: " + t);
return null;
}
protected void initialize(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return;
byte[][] a = StoreTechnics.loadArrayShort(src, 100, (short) 5000, PNTechTextProvFormatted.generalInfoLength());
this.parameters = new String[a.length];
ByteArrayOutputStream b = new ByteArrayOutputStream();
for(int i = 0; i < a.length; i++){
if(a[i].length == 0)return;
try {
b.write(a[i]);
} catch (IOException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Een byte-array kon niet naar een ByteArrayOutputStream geschreven worden om het te converteren naar een String bij een PNTechTextProvFormatted: " + e.getMessage());
}
try {
this.parameters[i] = b.toString("UTF8");
} catch (UnsupportedEncodingException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De Encoding \"UTF8\" wordt niet herkend (PNTechTextProvFormatted): " + e.getMessage());
}
b.reset();
}
try {
b.close();
} catch (IOException e) {}
}
@Override
protected byte[] saveTech(){//Dit is zonder de eerste byte van type
/*byte[] paramsarray;
{
int paramssize = 2 * parameters.length;
byte[][] params = new byte[this.parameters.length][];
int alength = 0;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)this.parameters[i] = "";
if(this.parameters[i].length() > 2500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is een parameters geskipt omdat die te lang was");
params[i] = new byte[0];
continue;
}
alength += this.parameters[i].length();
if(alength > 4500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er gestopt met bewaren vanwege een te lange totale lengte van parmaeters");
for(; i < this.parameters.length; i++){
params[i] = new byte[0];
}
break;
}
paramssize += this.parameters[i].length();
try {
params[i] = this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er een UnsuportedException opgedoken: " + e.getMessage());
}
}
paramsarray = new byte[paramssize];
int pos = 0;
for(int i = 0; i < params.length; i++){
paramsarray[pos++] = (byte) ((params[i].length >>> 8) & 0xFF);
paramsarray[pos++] = (byte) (params[i].length & 0xFF);
System.arraycopy(params[i], 0, paramsarray, pos, params[i].length);
pos += params[i].length;
}
}
byte[] array = new byte[6 + paramsarray.length];
array[0] = 1;
array[1] = format;
array[2] = (byte)((paramsarray.length >>> 24) & 0xFF);
array[3] = (byte)((paramsarray.length >>> 16) & 0xFF);
array[4] = (byte)((paramsarray.length >>> 8) & 0xFF);
array[5] = (byte)( paramsarray.length & 0xFF);
*/
byte[] params;
if(this.parameters == null){
params = new byte[0];
}else{
int l = this.parameters.length;
if(l > 100)l = 100;
byte[][] paramdata = new byte[l][];
for(int i = 0; i < l; i++){
try {
paramdata[i] = (this.parameters[i] == null)?new byte[0]:this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KKP] De Encoding \"UTF8\" is niet herkend bij een PNTechTextProvFormatted");;
paramdata[i] = new byte[0];
}
}
params = StoreTechnics.saveArrayShort(paramdata, 100);
}
byte[] ans = new byte[PNTechTextProvFormatted.generalInfoLength() + params.length];
System.arraycopy(params, 0, ans, PNTechTextProvFormatted.generalInfoLength(), params.length);
this.saveGeneralInfo(ans);
return ans;
}
//protected abstract void changeParameter(byte index, String value);//Hier hoort een validation bij betrokken te zijn of bepaalde parameters niet te lang zijn bv.
protected static int generalInfoLength(){return PNTechTextProv.generalInfoLength() + 1;}
protected boolean saveGeneralInfo(byte[] ans){
if(ans == null || ans.length < PNTechTextProv.generalInfoLength() + 1)return false;
super.saveGeneralInfo(ans);
ans[PNTechTextProv.generalInfoLength()] = this.getFormattedType();
return true;
}
@Override
public boolean handleObjectCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception {
if(super.handleObjectCommand(executor, a, attribSys, args))return true;
if(args.length < 1){
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §c<parameter> <...>");
return true;
}
if(executor.getSpelerOptions().getOpStatus() < 2){
a.sendMessage("§4Je hebt geen toegang tot dit commando");
return true;
}
args[0] = args[0].toLowerCase();
if(args[0].equals("parameter")){
if(this.notificationBase == null){
throw new Exception("ERROR: De notificationBase is null");
}
if(args.length == 2){
this.notificationBase.checkPermission(this, a, executor, this.getParameterViewAccessLevel());
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
a.sendMessage("§eDe parameter (#" + index + ") \"" + args[1] + "\" is " + ((this.parameters[index] == null || this.parameters[index].length() == 0)?("leeg"):("\"" + this.parameters[index] + "\"")));
}else if(args.length >= 3){
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
this.notificationBase.checkPermission(this, a, executor, this.getParameterChangeAccessLevel(index));
if(args.length == 3 && args[2].equals("leeg")){
if(this.setParameter(index, "")){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar een lege status");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar een lege status");
}
}else{
StringBuilder sb = new StringBuilder();
for(int i = 2; i < args.length - 1; i++){
sb.append(args[i]);
sb.append(' ');
}
sb.append(args[args.length - 1]);
String v = sb.toString();
if(attribSys.hasAttrib("verkleur")){
if(isSectionSignFormatAccepted(index)){
v = AdvancedChat.verkleurUitgebreid(v);
a.sendMessage("§eSectionSign-format is uitgevoerd");
}else{
a.sendMessage("§4SectionSign-format is niet geaccepteerd voor de parameter op index " + index);
}
}
if(this.setParameter(index, v)){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar \"§r§f" + v + "§r§e\"");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar \"§r§f" + v + "§r§4\"");
}
}
}else{
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §cparameter <parameterNaam> [nieuwe waarde]");
}
}else{
return false;
}
return true;
}
@Override
public ArrayList<String> autoCompleteObjectCommand(String[] args, ArrayList<String> a) throws Exception{
a = super.autoCompleteObjectCommand(args, a);
String label = args[0].toLowerCase();
if(args.length == 1){
if("parameter".startsWith(label))a.add("parameter");
}
return a;
}
}
| vkuhlmann/KartoffelKanaalPlugin | plugin/kartoffelsystems/PulserSystem/PNTechTextProvFormatted.java | 3,860 | //Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De Encoding \"UTF8\" wordt niet herkend (PNTechTextProvFormatted): " + e.getMessage()); | line_comment | nl | package KartoffelKanaalPlugin.plugin.kartoffelsystems.PulserSystem;
import KartoffelKanaalPlugin.plugin.AdvancedChat;
import KartoffelKanaalPlugin.plugin.AttribSystem;
import KartoffelKanaalPlugin.plugin.StoreTechnics;
import KartoffelKanaalPlugin.plugin.kartoffelsystems.PlayerSystem.Person;
import org.bukkit.command.CommandSender;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.logging.Logger;
public abstract class PNTechTextProvFormatted extends PNTechTextProv {
protected String[] parameters;
protected PNTechTextProvFormatted(byte[] src) {
super(src);
this.initialize(src);
}
protected PNTechTextProvFormatted(String[] parameters, boolean invisible, int ID, PulserNotifStandard base){
super(invisible, ID, base);
if(parameters == null)parameters = new String[0];
if(parameters.length > 100){
String[] newparams = new String[100];
System.arraycopy(parameters, 0, newparams, 0, 100);
}
this.parameters = parameters;
}
@Override
public String getTypeName(){
return super.getTypeName() + "Formatted";
}
public byte getTextProvType(){return 2;}
public abstract byte getFormattedType();
protected abstract byte getCorrectAmountParameters();
protected abstract boolean isSectionSignFormatAccepted(int index);
protected abstract int getNamedParameterIndex(String key);
protected boolean setParameter(int index, String value){
if(index < 0 || index >= this.parameters.length)return false;
parameters[index] = value;
this.notifyChange();
this.onParametersChanged();
return true;
}
protected boolean setNamedParameter(String key, String value){
int index = this.getNamedParameterIndex(key);
return this.setParameter(index, value);
}
protected abstract void onParametersChanged();
protected abstract byte getParameterViewAccessLevel();
protected abstract byte getParameterChangeAccessLevel(int paramID);
protected abstract String[] getPossibleKeys();
public String[] copyParameters(){
if(this.parameters == null)return new String[this.getCorrectAmountParameters()];
String[] s = new String[this.parameters.length];
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] != null)s[i] = new String(this.parameters[i]);
}
return s;
}
@Override
public int getEstimatedSize(){
if(this.parameters == null)return PNTechTextProvFormatted.generalInfoLength();
int l = this.parameters.length * 2;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)continue;
l += this.parameters[i].length();
}
return PNTechTextProvFormatted.generalInfoLength() + l;
}
protected static PNTechTextProvFormatted loadFromBytes(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return null;
byte t = src[PNTechTextProv.generalInfoLength()];//De hoogste bit hoeft er niet afgehaald te worden aangezien die geen functie heeft en dus niet gebruikt zo mogen worden. Als de hoogste bit dus voor verwarring zorgt, betekent dat dat er iets fout is.
if(t == 1){
return new PNTechTextProvFormattedVideo(src);
}
//System.out.println(" PNTechTextProvFormatted.loadFromBytes: PNTechTextProv geladen, onbekend TextProvType: " + t);
return null;
}
protected void initialize(byte[] src){
if(src == null || src.length < PNTechTextProvFormatted.generalInfoLength())return;
byte[][] a = StoreTechnics.loadArrayShort(src, 100, (short) 5000, PNTechTextProvFormatted.generalInfoLength());
this.parameters = new String[a.length];
ByteArrayOutputStream b = new ByteArrayOutputStream();
for(int i = 0; i < a.length; i++){
if(a[i].length == 0)return;
try {
b.write(a[i]);
} catch (IOException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Een byte-array kon niet naar een ByteArrayOutputStream geschreven worden om het te converteren naar een String bij een PNTechTextProvFormatted: " + e.getMessage());
}
try {
this.parameters[i] = b.toString("UTF8");
} catch (UnsupportedEncodingException e) {
//Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] De<SUF>
}
b.reset();
}
try {
b.close();
} catch (IOException e) {}
}
@Override
protected byte[] saveTech(){//Dit is zonder de eerste byte van type
/*byte[] paramsarray;
{
int paramssize = 2 * parameters.length;
byte[][] params = new byte[this.parameters.length][];
int alength = 0;
for(int i = 0; i < this.parameters.length; i++){
if(this.parameters[i] == null)this.parameters[i] = "";
if(this.parameters[i].length() > 2500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is een parameters geskipt omdat die te lang was");
params[i] = new byte[0];
continue;
}
alength += this.parameters[i].length();
if(alength > 4500){
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er gestopt met bewaren vanwege een te lange totale lengte van parmaeters");
for(; i < this.parameters.length; i++){
params[i] = new byte[0];
}
break;
}
paramssize += this.parameters[i].length();
try {
params[i] = this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KartoffelKanaalPlugin] Bij het bewaren van Parameters van een PulserNotificationMessageFormatted, is er een UnsuportedException opgedoken: " + e.getMessage());
}
}
paramsarray = new byte[paramssize];
int pos = 0;
for(int i = 0; i < params.length; i++){
paramsarray[pos++] = (byte) ((params[i].length >>> 8) & 0xFF);
paramsarray[pos++] = (byte) (params[i].length & 0xFF);
System.arraycopy(params[i], 0, paramsarray, pos, params[i].length);
pos += params[i].length;
}
}
byte[] array = new byte[6 + paramsarray.length];
array[0] = 1;
array[1] = format;
array[2] = (byte)((paramsarray.length >>> 24) & 0xFF);
array[3] = (byte)((paramsarray.length >>> 16) & 0xFF);
array[4] = (byte)((paramsarray.length >>> 8) & 0xFF);
array[5] = (byte)( paramsarray.length & 0xFF);
*/
byte[] params;
if(this.parameters == null){
params = new byte[0];
}else{
int l = this.parameters.length;
if(l > 100)l = 100;
byte[][] paramdata = new byte[l][];
for(int i = 0; i < l; i++){
try {
paramdata[i] = (this.parameters[i] == null)?new byte[0]:this.parameters[i].getBytes("UTF8");
} catch (UnsupportedEncodingException e) {
Logger.getLogger("Minecraft").warning("[KKP] De Encoding \"UTF8\" is niet herkend bij een PNTechTextProvFormatted");;
paramdata[i] = new byte[0];
}
}
params = StoreTechnics.saveArrayShort(paramdata, 100);
}
byte[] ans = new byte[PNTechTextProvFormatted.generalInfoLength() + params.length];
System.arraycopy(params, 0, ans, PNTechTextProvFormatted.generalInfoLength(), params.length);
this.saveGeneralInfo(ans);
return ans;
}
//protected abstract void changeParameter(byte index, String value);//Hier hoort een validation bij betrokken te zijn of bepaalde parameters niet te lang zijn bv.
protected static int generalInfoLength(){return PNTechTextProv.generalInfoLength() + 1;}
protected boolean saveGeneralInfo(byte[] ans){
if(ans == null || ans.length < PNTechTextProv.generalInfoLength() + 1)return false;
super.saveGeneralInfo(ans);
ans[PNTechTextProv.generalInfoLength()] = this.getFormattedType();
return true;
}
@Override
public boolean handleObjectCommand(Person executor, CommandSender a, AttribSystem attribSys, String[] args) throws Exception {
if(super.handleObjectCommand(executor, a, attribSys, args))return true;
if(args.length < 1){
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §c<parameter> <...>");
return true;
}
if(executor.getSpelerOptions().getOpStatus() < 2){
a.sendMessage("§4Je hebt geen toegang tot dit commando");
return true;
}
args[0] = args[0].toLowerCase();
if(args[0].equals("parameter")){
if(this.notificationBase == null){
throw new Exception("ERROR: De notificationBase is null");
}
if(args.length == 2){
this.notificationBase.checkPermission(this, a, executor, this.getParameterViewAccessLevel());
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
a.sendMessage("§eDe parameter (#" + index + ") \"" + args[1] + "\" is " + ((this.parameters[index] == null || this.parameters[index].length() == 0)?("leeg"):("\"" + this.parameters[index] + "\"")));
}else if(args.length >= 3){
int index;
if(args[1].startsWith("#")){
try{
index = Integer.parseInt(args[1].substring(1));
}catch(NumberFormatException e){
a.sendMessage("§4Oncorrecte parameterIndex");
return true;
}
}else{
index = this.getNamedParameterIndex(args[1]);
}
if(index < 0 || index >= this.parameters.length){
a.sendMessage("§4Onbekende parameterNaam");
return true;
}
this.notificationBase.checkPermission(this, a, executor, this.getParameterChangeAccessLevel(index));
if(args.length == 3 && args[2].equals("leeg")){
if(this.setParameter(index, "")){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar een lege status");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar een lege status");
}
}else{
StringBuilder sb = new StringBuilder();
for(int i = 2; i < args.length - 1; i++){
sb.append(args[i]);
sb.append(' ');
}
sb.append(args[args.length - 1]);
String v = sb.toString();
if(attribSys.hasAttrib("verkleur")){
if(isSectionSignFormatAccepted(index)){
v = AdvancedChat.verkleurUitgebreid(v);
a.sendMessage("§eSectionSign-format is uitgevoerd");
}else{
a.sendMessage("§4SectionSign-format is niet geaccepteerd voor de parameter op index " + index);
}
}
if(this.setParameter(index, v)){
a.sendMessage("§eDe parameter \"" + args[1] + "\" is veranderd naar \"§r§f" + v + "§r§e\"");
}else{
a.sendMessage("§4De parameter \"" + args[1] + "\" kon niet veranderd worden naar \"§r§f" + v + "§r§4\"");
}
}
}else{
a.sendMessage("§ePNTechTextProvFormatted-deel van het commando: §cparameter <parameterNaam> [nieuwe waarde]");
}
}else{
return false;
}
return true;
}
@Override
public ArrayList<String> autoCompleteObjectCommand(String[] args, ArrayList<String> a) throws Exception{
a = super.autoCompleteObjectCommand(args, a);
String label = args[0].toLowerCase();
if(args.length == 1){
if("parameter".startsWith(label))a.add("parameter");
}
return a;
}
}
| False |
2,027 | 29158_60 | // ----------------------------------------------------------------------------
// Copyright 2007-2016, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = 630;
public static final int ZONE_HEIGHT = 630; // 535;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double (mim meters between events)
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_src[] = new String[] { "javascript.src" , "javascript.include" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
**/
public int getZoneWidth();
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
**/
public int getZoneHeight();
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
| alrf/opengts261_gt02a | src/org/opengts/war/tools/MapProvider.java | 6,343 | // double (mim meters between events) | line_comment | nl | // ----------------------------------------------------------------------------
// Copyright 2007-2016, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
// Change History:
// 2007/01/25 Martin D. Flynn
// -Initial release
// 2007/05/06 Martin D. Flynn
// -Added methods "isAttributeSupported" & "writeMapUpdate"
// 2008/04/11 Martin D. Flynn
// -Added/modified map provider property keys
// -Added auto-update methods.
// -Added name and authorization (service provider key) methods
// 2008/08/20 Martin D. Flynn
// -Added 'isFeatureSupported', removed 'isAttributeSupported'
// 2008/08/24 Martin D. Flynn
// -Added 'getReplayEnabled()' and 'getReplayInterval()' methods.
// 2008/09/19 Martin D. Flynn
// -Added 'getAutoUpdateOnLoad()' method.
// 2009/02/20 Martin D. Flynn
// -Added "map.minProximity" property. This is used to trim redundant events
// (those closely located to each other) from being display on the map.
// 2009/09/23 Martin D. Flynn
// -Added support for customizing the Geozone map width/height
// 2009/11/01 Martin D. Flynn
// -Added 'isFleet' argument to "getMaxPushpins"
// 2009/04/11 Martin D. Flynn
// -Changed "getMaxPushpins" argument to "RequestProperties"
// 2011/10/03 Martin D. Flynn
// -Added "map.showPushpins" property.
// 2012/04/26 Martin D. Flynn
// -Added PROP_info_showOptionalFields, PROP_info_inclBlankOptFields
// ----------------------------------------------------------------------------
package org.opengts.war.tools;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.opengts.util.*;
import org.opengts.dbtools.*;
import org.opengts.db.*;
public interface MapProvider
{
// ------------------------------------------------------------------------
/* these attributes are used during runtime only, they are not cached */
public static final long FEATURE_GEOZONES = 0x00000001L;
public static final long FEATURE_LATLON_DISPLAY = 0x00000002L;
public static final long FEATURE_DISTANCE_RULER = 0x00000004L;
public static final long FEATURE_DETAIL_REPORT = 0x00000008L;
public static final long FEATURE_DETAIL_INFO_BOX = 0x00000010L;
public static final long FEATURE_REPLAY_POINTS = 0x00000020L;
public static final long FEATURE_CENTER_ON_LAST = 0x00000040L;
public static final long FEATURE_CORRIDORS = 0x00000080L;
// ------------------------------------------------------------------------
public static final String ID_DETAIL_TABLE = "trackMapDataTable";
public static final String ID_DETAIL_CONTROL = "trackMapDataControl";
public static final String ID_LAT_LON_DISPLAY = "trackMapLatLonDisplay";
public static final String ID_DISTANCE_DISPLAY = "trackMapDistanceDisplay";
public static final String ID_LATEST_EVENT_DATE = "lastEventDate";
public static final String ID_LATEST_EVENT_TIME = "lastEventTime";
public static final String ID_LATEST_EVENT_TMZ = "lastEventTmz";
public static final String ID_LATEST_BATTERY = "lastBatteryLevel";
public static final String ID_MESSAGE_TEXT = CommonServlet.ID_CONTENT_MESSAGE;
// ------------------------------------------------------------------------
public static final String ID_ZONE_RADIUS_M = "trackMapZoneRadiusM";
public static final String ID_ZONE_LATITUDE_ = "trackMapZoneLatitude_";
public static final String ID_ZONE_LONGITUDE_ = "trackMapZoneLongitude_";
// ------------------------------------------------------------------------
// Preferred/Default map width/height
// Note: 'contentTableFrame' in 'private.xml' should have dimensions based on the map size,
// roughly as follows:
// width : MAP_WIDTH + 164; [680 + 164 = 844]
// height: MAP_HEIGHT + 80; [420 + 80 = 500]
public static final int MAP_WIDTH = 680;
public static final int MAP_HEIGHT = 470;
public static final int ZONE_WIDTH = 630;
public static final int ZONE_HEIGHT = 630; // 535;
// ------------------------------------------------------------------------
/* geozone properties */
public static final String PROP_zone_map_width[] = new String[] { "zone.map.width" }; // int (zone map width)
public static final String PROP_zone_map_height[] = new String[] { "zone.map.height" }; // int (zone map height)
public static final String PROP_zone_map_multipoint[] = new String[] { "zone.map.multipoint", "geozone.multipoint" }; // boolean (supports multiple point-radii)
public static final String PROP_zone_map_polygon[] = new String[] { "zone.map.polygon" }; // boolean (supports polygons)
public static final String PROP_zone_map_corridor[] = new String[] { "zone.map.corridor" }; // boolean (supports swept-point-radius)
/* standard properties */
public static final String PROP_map_width[] = new String[] { "map.width" }; // int (map width)
public static final String PROP_map_height[] = new String[] { "map.height" }; // int (map height)
public static final String PROP_map_fillFrame[] = new String[] { "map.fillFrame" }; // boolean (map fillFrame)
public static final String PROP_maxPushpins_device[] = new String[] { "map.maxPushpins.device" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_fleet[] = new String[] { "map.maxPushpins.fleet" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_maxPushpins_report[] = new String[] { "map.maxPushpins.report" , "map.maxPushpins" }; // int (maximum pushpins)
public static final String PROP_map_pushpins[] = new String[] { "map.showPushpins" , "map.pushpins" }; // boolean (include pushpins)
public static final String PROP_map_maxCreationAge[] = new String[] { "map.maxCreationAge" , "maxCreationAge" }; // int (max creation age, indicated by an alternate pushpin)
public static final String PROP_map_routeLine[] = new String[] { "map.routeLine" }; // boolean (include route line)
public static final String PROP_map_routeLine_color[] = new String[] { "map.routeLine.color" }; // String (route line color)
public static final String PROP_map_routeLine_arrows[] = new String[] { "map.routeLine.arrows" }; // boolean (include route line arrows)
public static final String PROP_map_routeLine_snapToRoad[] = new String[] { "map.routeLine.snapToRoad" }; // boolean (snap route-line to road) Google V2 only
public static final String PROP_map_view[] = new String[] { "map.view" }; // String (road|satellite|hybrid)
public static final String PROP_map_minProximity[] = new String[] { "map.minProximity" /*meters*/ }; // double <SUF>
public static final String PROP_map_includeGeozones[] = new String[] { "map.includeGeozones" , "includeGeozones" }; // boolean (include traversed Geozones)
public static final String PROP_pushpin_zoom[] = new String[] { "pushpin.zoom" }; // dbl/int (default zoom with points)
public static final String PROP_default_zoom[] = new String[] { "default.zoom" }; // dbl/int (default zoom without points)
public static final String PROP_default_latitude[] = new String[] { "default.lat" , "default.latitude" }; // double (default latitude)
public static final String PROP_default_longitude[] = new String[] { "default.lon" , "default.longitude" }; // double (default longitude)
public static final String PROP_info_showSpeed[] = new String[] { "info.showSpeed" }; // boolean (show speed in info bubble)
public static final String PROP_info_showAltitude[] = new String[] { "info.showAltitude" }; // boolean (show altitude in info bubble)
public static final String PROP_info_inclBlankAddress[] = new String[] { "info.inclBlankAddress" }; // boolean (show blank addresses in info bubble)
public static final String PROP_info_showOptionalFields[] = new String[] { "info.showOptionalFields" }; // boolean (show optional-fields in info bubble)
public static final String PROP_info_inclBlankOptFields[] = new String[] { "info.inclBlankOptFields" }; // boolean (show blank optional-fields in info bubble)
public static final String PROP_detail_showSatCount[] = new String[] { "detail.showSatCount" }; // boolean (show satellite in location detail)
/* auto update properties */
public static final String PROP_auto_enable_device[] = new String[] { "auto.enable" , "auto.enable.device" }; // boolean (auto update)
public static final String PROP_auto_onload_device[] = new String[] { "auto.onload" , "auto.onload.device" }; // boolean (auto update onload)
public static final String PROP_auto_interval_device[] = new String[] { "auto.interval" , "auto.interval.device" }; // int (update interval seconds)
public static final String PROP_auto_count_device[] = new String[] { "auto.count" , "auto.count.device" }; // int (update count)
public static final String PROP_auto_radius_device[] = new String[] { "auto.skipRadius" , "auto.skipRadius.device" }; // int (skip radius)
public static final String PROP_auto_enable_fleet[] = new String[] { "auto.enable" , "auto.enable.fleet" }; // boolean (auto update)
public static final String PROP_auto_onload_fleet[] = new String[] { "auto.onload" , "auto.onload.fleet" }; // boolean (auto update onload)
public static final String PROP_auto_interval_fleet[] = new String[] { "auto.interval" , "auto.interval.fleet" }; // int (update interval seconds)
public static final String PROP_auto_count_fleet[] = new String[] { "auto.count" , "auto.count.fleet" }; // int (update count)
public static final String PROP_auto_radius_fleet[] = new String[] { "auto.skipRadius" , "auto.skipRadius.fleet" }; // int (skip radius)
/* replay properties (device map only) */
public static final String PROP_replay_enable[] = new String[] { "replay.enable" }; // boolean (replay)
public static final String PROP_replay_interval[] = new String[] { "replay.interval" }; // int (replay interval milliseconds)
public static final String PROP_replay_singlePushpin[] = new String[] { "replay.singlePushpin" }; // boolean (show single pushpin)
/* detail report */
public static final String PROP_combineSpeedHeading[] = new String[] { "details.combineSpeedHeading" }; // boolean (combine speed/heading columns)
/* icon selector */
public static final String PROP_iconSelector[] = new String[] { "iconSelector" , "iconselector.device" }; // String (default icon selector)
public static final String PROP_iconSelector_legend[] = new String[] { "iconSelector.legend", "iconSelector.device.legend" }; // String (icon selector legend)
public static final String PROP_iconSel_fleet[] = new String[] { "iconSelector.fleet" }; // String (fleet icon selector)
public static final String PROP_iconSel_fleet_legend[] = new String[] { "iconSelector.fleet.legend" }; // String (fleet icon selector legend)
/* JSMap properties */
public static final String PROP_javascript_src[] = new String[] { "javascript.src" , "javascript.include" }; // String (JSMap provider JS)
public static final String PROP_javascript_inline[] = new String[] { "javascript.inline" }; // String (JSMap provider JS)
/* optional properties */
public static final String PROP_scrollWheelZoom[] = new String[] { "scrollWheelZoom" }; // boolean (scroll wheel zoom)
// ------------------------------------------------------------------------
public static final double DEFAULT_LATITUDE = 39.0000;
public static final double DEFAULT_LONGITUDE = -96.5000;
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** Returns the MapProvider name
*** @return The MapProvider name
**/
public String getName();
/**
*** Returns the MapProvider authorization String/Key (passed to the map service provider)
*** @return The MapProvider authorization String/Key.
**/
public String getAuthorization();
// ------------------------------------------------------------------------
/**
*** Sets the properties for this MapProvider.
*** @param props A String representation of the properties to set in this
*** MapProvider. The String must be in the form "key=value key=value ...".
**/
public void setProperties(String props);
/**
*** Returns the properties for this MapProvider
*** @return The properties for this MapProvider
**/
public RTProperties getProperties();
// ------------------------------------------------------------------------
/**
*** Sets the zoom regions
*** @param The zoon regions
**/
/* public void setZoomRegions(Map<String,String> map); */
/**
*** Gets the zoom regions
*** @return The zoon regions
**/
/* public Map<String,String> getZoomRegions(); */
// ------------------------------------------------------------------------
/**
*** Gets the maximum number of allowed pushpins on the map at one time
*** @param reqState The session RequestProperties instance
*** @return The maximum number of allowed pushpins on the map
**/
public long getMaxPushpins(RequestProperties reqState);
/**
*** Gets the pushpin icon map
*** @param reqState The RequestProperties for the current session
*** @return The PushPinIcon map
**/
public OrderedMap<String,PushpinIcon> getPushpinIconMap(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Gets the icon selector for the current map
*** @param reqState The RequestProperties for the current session
*** @return The icon selector String
**/
public String getIconSelector(RequestProperties reqState);
/**
*** Gets the IconSelector legend displayed on the map page to indicate the
*** type of pushpins displayed on the map.
*** @param reqState The RequestProperties for the current session
*** @return The IconSelector legend (in html format)
**/
public String getIconSelectorLegend(RequestProperties reqState);
// ------------------------------------------------------------------------
/**
*** Returns the MapDimension for this MapProvider
*** @return The MapDimension
**/
public MapDimension getDimension();
/**
*** Returns the Width from the MapDimension
*** @return The MapDimension width
**/
public int getWidth();
/**
*** Returns the Height from the MapDimension
*** @return The MapDimension height
**/
public int getHeight();
// ------------------------------------------------------------------------
/**
*** Returns the Geozone MapDimension for this MapProvider
*** @return The Geozone MapDimension
**/
public MapDimension getZoneDimension();
/**
*** Returns the Geozone Width from the MapDimension
*** @return The Geozone MapDimension width
**/
public int getZoneWidth();
/**
*** Returns the Geozone Height from the MapDimension
*** @return The Geozone MapDimension height
**/
public int getZoneHeight();
// ------------------------------------------------------------------------
/**
*** Returns the default map center (when no pushpins are displayed)
*** @param dft The GeoPoint center to return if not otherwised overridden
*** @return The default map center
**/
public GeoPoint getDefaultCenter(GeoPoint dft);
/**
*** Returns the default zoom level
*** @param dft The default zoom level to return
*** @param withPushpins If true, return the default zoom level is at least
*** one pushpin is displayed.
*** @return The default zoom level
**/
public double getDefaultZoom(double dft, boolean withPushpins);
// ------------------------------------------------------------------------
/**
*** Returns true if auto-update is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated is enabled
**/
public boolean getAutoUpdateEnabled(boolean isFleet);
/**
*** Returns true if auto-update on-load is enabled
*** @param isFleet True for fleet map
*** @return True if auto-updated on-load is enabled
**/
public boolean getAutoUpdateOnLoad(boolean isFleet);
/**
*** Returns the auto-update interval in seconds
*** @param isFleet True for fleet map
*** @return The auto-update interval in seconds
**/
public long getAutoUpdateInterval(boolean isFleet);
/**
*** Returns the auto-update count
*** @param isFleet True for fleet map
*** @return The auto-update count (-1 for indefinite)
**/
public long getAutoUpdateCount(boolean isFleet);
/**
*** Returns the auto-update skip-radius
*** @param isFleet True for fleet map
*** @return The auto-update skip-radius (0 for no skip)
**/
public double getAutoUpdateSkipRadius(boolean isFleet);
// ------------------------------------------------------------------------
/**
*** Returns true if replay is enabled
*** @return True if replay is enabled
**/
public boolean getReplayEnabled();
/**
*** Returns the replay interval in seconds
*** @return The replay interval in seconds
**/
public long getReplayInterval();
/**
*** Returns true if only a single pushpin is to be displayed at a time during replay
*** @return True if only a single pushpin is to be displayed at a time during replay
**/
public boolean getReplaySinglePushpin();
// ------------------------------------------------------------------------
/**
*** Writes any required CSS to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeStyle(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes any required JavaScript to the specified PrintWriter. This method is
*** intended to be overridden to provide the required behavior.
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
**/
public void writeJavaScript(PrintWriter out, RequestProperties reqState)
throws IOException;
/**
*** Writes map cell to the specified PrintWriter. This method is intended
*** to be overridden to provide the required behavior for the specific MapProvider
*** @param out The PrintWriter
*** @param reqState The session RequestProperties
*** @param mapDim The MapDimension
**/
public void writeMapCell(PrintWriter out, RequestProperties reqState, MapDimension mapDim)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Updates the points to the current displayed map
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
int mapDataFormat,
RequestProperties reqState)
throws IOException;
/**
*** Updates the points to the current displayed map
*** @param out The output PrintWriter
*** @param indentLvl The indentation level (0 for no indentation)
*** @param reqState The session RequestProperties
**/
public void writeMapUpdate(
PrintWriter out, int indentLvl,
int mapDataFormat, boolean isTopLevelTag,
RequestProperties reqState)
throws IOException;
// ------------------------------------------------------------------------
/**
*** Gets the number of supported Geozone points
*** @param type The Geozone type
*** @return The number of supported points.
**/
public int getGeozoneSupportedPointCount(int type);
/**
*** Returns the localized Geozone instructions
*** @param type The Geozone type
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getGeozoneInstructions(int type, Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns the localized GeoCorridor instructions
*** @param loc The current Locale
*** @return An array of instruction line items
**/
public String[] getCorridorInstructions(Locale loc);
// ------------------------------------------------------------------------
/**
*** Returns true if the specified feature is supported
*** @param featureMask The feature mask to test
*** @return True if the specified feature is supported
**/
public boolean isFeatureSupported(long featureMask);
}
| False |
4,395 | 119508_9 | package com.opentravelsoft.providers.hibernate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.LockMode;
import org.springframework.stereotype.Repository;
import com.opentravelsoft.entity.Booking;
import com.opentravelsoft.entity.Employee;
import com.opentravelsoft.entity.Tourist;
import com.opentravelsoft.entity.finance.Reckoning;
import com.opentravelsoft.entity.finance.ReckoningAcct;
import com.opentravelsoft.entity.finance.ReckoningAcctId;
import com.opentravelsoft.providers.ReckoningDao;
import com.opentravelsoft.util.RowDataUtil;
/**
* 帐单制作
*
* @author <a herf="mailto:zhangsitao@gmail.com">Steven Zhang</a>
*/
@Repository("ReckoningDao")
public class ReckoningDaoHibernate extends
GenericDaoHibernate<Reckoning, Integer> implements ReckoningDao {
public ReckoningDaoHibernate() {
super(Reckoning.class);
}
@SuppressWarnings("unchecked")
public List<Reckoning> getReckoning(String reserveNo) {
StringBuilder sql = new StringBuilder();
sql.append("from Reckoning where bookingNo=? ");
Object[] param = { reserveNo };
List<Reckoning> list = getHibernateTemplate().find(sql.toString(), param);
for (Reckoning reckoning : list) {
reckoning.setVersion(RowDataUtil.getInt(reckoning.getNumber()));
reckoning.setCreateDate(RowDataUtil.getDate(reckoning.getCreated()));
reckoning.setPrintDate(RowDataUtil.getDate(reckoning.getPrinted()));
}
return list;
}
@SuppressWarnings("unchecked")
public Reckoning wholeReckoningMake(Reckoning reckoning) {
StringBuilder sql = new StringBuilder();
String reserveNo = reckoning.getBookingNo();
Reckoning tblReckoning = new Reckoning();
int version = 1;
// 续上版本号
sql.append("from Reckoning where bookingNo=? order by number ");
Object[] param = { reserveNo };
List<Reckoning> list = getHibernateTemplate().find(sql.toString(), param);
if (null == list || list.isEmpty()) {
tblReckoning.setNumber(version);
} else {
for (Reckoning obj : list) {
if (obj.getNumber() > version)
version = obj.getNumber();
}
tblReckoning.setNumber(++version);
}
//
tblReckoning.setBookingNo(reckoning.getBookingNo());
tblReckoning.setTourType(reckoning.getTourType());
tblReckoning.setContact(reckoning.getContact());
tblReckoning.setPhone(reckoning.getPhone());
tblReckoning.setFax(reckoning.getFax());
tblReckoning.setCreatedBy(reckoning.getCreatedBy());
tblReckoning.setPrintedCount(0);
getHibernateTemplate().save(tblReckoning);
// 得到帐单号
sql = new StringBuilder();
sql.append("from Reckoning where bookingNo=? and number=? ");
Object[] params = { reserveNo, version };
List<Reckoning> tblReckonings = getHibernateTemplate().find(sql.toString(),
params);
ReckoningAcct tblReckoningAcct;
ReckoningAcct reckoningAcct;
ReckoningAcctId tblReckoningAcctId;
reckoning.setReckoningId(tblReckonings.get(0).getReckoningId());
reckoning.setVersion(tblReckonings.get(0).getNumber());
if (reckoning.getTourType().equals("1")) {
if (!reckoning.getReckoningAcctList().isEmpty()) {
if (null != tblReckonings && !(tblReckonings.isEmpty())) {
for (int i = 0; i < reckoning.getReckoningAcctList().size(); i++) {
tblReckoningAcct = new ReckoningAcct();
tblReckoningAcctId = new ReckoningAcctId();
reckoningAcct = reckoning.getReckoningAcctList().get(i);
tblReckoningAcctId.setReckoningId(tblReckonings.get(0)
.getReckoningId());
tblReckoningAcctId.setItemId(reckoningAcct.getItemId());
tblReckoningAcct.setId(tblReckoningAcctId);
tblReckoningAcct.setAmount(reckoningAcct.getAmount());
tblReckoningAcct.setUnit(reckoningAcct.getUnit());
tblReckoningAcct.setDescription(reckoningAcct.getDescription());
tblReckoningAcct.setUnitPrice(reckoningAcct.getUnitPrice());
tblReckoningAcct.setCount(reckoningAcct.getCount());
getHibernateTemplate().save(tblReckoningAcct);
}
}
}
}
// 保存应收帐款
Booking tfj006 = (Booking) getHibernateTemplate().get(Booking.class,
reckoning.getBookingNo());
tfj006.setDbamt(reckoning.getAmount());
// --------------------------------------------------------------------
// String enabled = (String) ActionContext.getContext().getApplication()
// .get(EbizCommon.WORKFLOW_ENABLED);
// if (enabled.equals("1"))
// {
// StringBuilder sb = new StringBuilder();
// sb.append("select t ");
// sb.append("from org.jbpm.pvm.internal.task.TaskImpl t ");
// sb.append(",Booking b ");
// sb.append("where t.executionId=b.workflowId and b.nameNo=? ");
// sb.append("and t.name=? ");
// sb.append("and t.state!='" + Task.STATE_COMPLETED + "' ");
// Object[] p = { reckoning.getBookingNo(),
// WorkFlowKeyParams.ORDER_TASK_ACCOUNT };
// List<TaskImpl> taskInstances = getHibernateTemplate().find(
// sb.toString(), p);
//
// for (TaskImpl taskInstance : taskInstances)
// {
// taskInstance.createVariable(WorkFlowKeyParams.WORKFLOW_ACTOR,
// reckoning.getCreatedBy());
// taskService.completeTask(taskInstance.getId());
// }
// }
// --------------------------------------------------------------------
getHibernateTemplate().update(tfj006);
return reckoning;
}
@SuppressWarnings("unchecked")
public Reckoning getReckoningInfo(int reckoningId) {
Reckoning reckoning = (Reckoning) getHibernateTemplate().get(
Reckoning.class, reckoningId);
if (null != reckoning) {
reckoning.setVersion(RowDataUtil.getInt(reckoning.getNumber()));
reckoning.setCreateDate(RowDataUtil.getDate(reckoning.getCreated()));
reckoning.setPrintDate(RowDataUtil.getDate(reckoning.getPrinted()));
StringBuilder sql = new StringBuilder();
sql.append("from Employee where userId=?");
Object[] params = { reckoning.getCreatedBy() };
List<Employee> employees = getHibernateTemplate().find(sql.toString(),
params);
if (null != employees && !(employees.isEmpty()))
reckoning.setCreatedByName(employees.get(0).getUserName());
// 如果为整团,则取出帐单明细
if (reckoning.getTourType().equals("1")) {
sql = new StringBuilder();
sql.append("from ReckoningAcct where id.reckoningId=? ");
Object[] param = { reckoningId };
List<ReckoningAcct> tblReckoningAcctList = getHibernateTemplate().find(
sql.toString(), param);
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
for (ReckoningAcct obj : tblReckoningAcctList) {
obj.getId().setReckoningId(obj.getId().getReckoningId());
obj.setItemId(obj.getId().getItemId());
reckoningAcctList.add(obj);
}
reckoning.setReckoningAcctList(reckoningAcctList);
}
}
return reckoning;
}
@SuppressWarnings("unchecked")
public int wholeReckoningModify(Reckoning reckoning) {
StringBuilder sql = new StringBuilder();
Reckoning tblReckoning = new Reckoning();
tblReckoning = (Reckoning) getHibernateTemplate().get(Reckoning.class,
reckoning.getReckoningId(), LockMode.PESSIMISTIC_WRITE);
if (null != tblReckoning
&& tblReckoning.getReckoningId() == reckoning.getReckoningId()) {
// String str = getReckoningInfo(tblReckoning, reckoning);
tblReckoning.setContact(reckoning.getContact());
tblReckoning.setPhone(reckoning.getPhone());
tblReckoning.setFax(reckoning.getFax());
tblReckoning.setUpdatedBy(reckoning.getUpdatedBy());
getHibernateTemplate().update(tblReckoning);
if (reckoning.getTourType().equals("1")) {
sql = new StringBuilder();
sql.append("from ReckoningAcct where id.reckoningId=? ");
Object[] param2 = { reckoning.getReckoningId() };
List<ReckoningAcct> tblReckoningAcctList = getHibernateTemplate().find(
sql.toString(), param2);
getHibernateTemplate().deleteAll(tblReckoningAcctList);
ReckoningAcct tblReckoningAcct;
ReckoningAcct reckoningAcct;
ReckoningAcctId tblReckoningAcctId;
for (int i = 0; i < reckoning.getReckoningAcctList().size(); i++) {
tblReckoningAcct = new ReckoningAcct();
tblReckoningAcctId = new ReckoningAcctId();
reckoningAcct = reckoning.getReckoningAcctList().get(i);
tblReckoningAcctId.setReckoningId(reckoning.getReckoningId());
tblReckoningAcctId.setItemId(reckoningAcct.getItemId());
tblReckoningAcct.setId(tblReckoningAcctId);
tblReckoningAcct.setAmount(reckoningAcct.getAmount());
tblReckoningAcct.setUnit(reckoningAcct.getUnit());
tblReckoningAcct.setDescription(reckoningAcct.getDescription());
tblReckoningAcct.setUnitPrice(reckoningAcct.getUnitPrice());
tblReckoningAcct.setCount(reckoningAcct.getCount());
getHibernateTemplate().save(tblReckoningAcct);
}
}
// 修改应收帐款
Booking tfj006 = (Booking) getHibernateTemplate().get(Booking.class,
reckoning.getBookingNo());
BigDecimal old_Amount = tfj006.getDbamt();
tfj006.setDbamt(reckoning.getAmount());
getHibernateTemplate().update(tfj006);
String str1 = "账单号," + reckoning.getReckoningId() + ","
+ tblReckoning.getReckoningId() + ",";
if (old_Amount != tfj006.getDbamt()) {
str1 = str1 + "应收账款," + tfj006.getDbamt() + "," + old_Amount + ",";
}
return 0;
} else
return -1;
}
@SuppressWarnings("unchecked")
public List<ReckoningAcct> getCustomerList(String bookingNo) {
StringBuilder sql = new StringBuilder();
sql.append("from Tourist where booking.nameNo=? and del='N' ");
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
ReckoningAcct reckoningAcct;
Object[] params = { bookingNo };
List<Tourist> tourists = getHibernateTemplate()
.find(sql.toString(), params);
int itemId = 1;
for (Tourist obj : tourists) {
reckoningAcct = new ReckoningAcct();
reckoningAcct.setItemId(itemId++);
reckoningAcct.setName(RowDataUtil.getString(obj.getUserName()));
reckoningAcct.setAmount(RowDataUtil.getBigDecimal(obj.getAmt01()));
reckoningAcctList.add(reckoningAcct);
}
return reckoningAcctList;
}
public int setPrint(int reckoningId) {
Date sysdate = getSysdate();
Reckoning tblReckoning = new Reckoning();
tblReckoning = (Reckoning) getHibernateTemplate().get(Reckoning.class,
reckoningId, LockMode.PESSIMISTIC_WRITE);
tblReckoning.setPrintDate(sysdate);
tblReckoning.setPrintedCount(tblReckoning.getPrintedCount() + 1);
getHibernateTemplate().update(tblReckoning);
return 0;
}
@SuppressWarnings("unchecked")
public List<ReckoningAcct> getTourReckoningAcctList(String tourNo) {
StringBuilder sql = new StringBuilder();
sql.append("select b.reckoningId,c.description,c.unitPrice, ");
sql.append("c.count,c.amount,c.unit,b.bookingNo,b.number ");
sql.append("from Booking a, ");
sql.append("Reckoning b, ");
sql.append("ReckoningAcct c ");
sql.append("where a.plan.tourNo=? and a.nameNo=b.bookingNo ");
sql.append("and b.reckoningId=c.id.reckoningId ");
sql.append("order by b.bookingNo ");
Object[] param = { tourNo };
List<Object[]> list = getHibernateTemplate().find(sql.toString(), param);
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
if (!list.isEmpty()) {
ReckoningAcct reckoningAcct;
int size = list.size();
int number = 0;
String bookingNo = new String();
Object[] object1;
Object[] object2;
// 移除订单低版本的帐单
for (int i = 0; i < size; i++) {
if (null != list && i < list.size()) {
object1 = list.get(0);
bookingNo = RowDataUtil.getString(object1[6]);
number = RowDataUtil.getInt(object1[7]);
// 取此订单帐单最高版本号
for (int j = 0; j < list.size(); j++) {
object2 = list.get(j);
if (bookingNo.equals(RowDataUtil.getString(object2[6])))
if (number < RowDataUtil.getInt(object2[7]))
number = RowDataUtil.getInt(object2[7]);
}
// 取此订单帐单最高版本号所对应的帐单明细
for (Object[] obj : list) {
if (RowDataUtil.getString(obj[6]).equals(bookingNo)
&& RowDataUtil.getInt(obj[7]) == number) {
reckoningAcct = new ReckoningAcct();
reckoningAcct.getId().setReckoningId(RowDataUtil.getInt(obj[0]));
reckoningAcct.setDescription(RowDataUtil.getString(obj[1]));
reckoningAcct.setUnitPrice(RowDataUtil.getBigDecimal(obj[2]));
reckoningAcct.setCount(RowDataUtil.getInt(obj[3]));
reckoningAcct.setAmount(RowDataUtil.getBigDecimal(obj[4]));
reckoningAcct.setUnit(RowDataUtil.getString(obj[5]));
reckoningAcct.setBookingNo(RowDataUtil.getString(obj[6]));
reckoningAcctList.add(reckoningAcct);
}
}
int lastSize = list.size();
// 移除已取订单的所有帐单
for (int k = 0; k < lastSize; k++) {
if (k < list.size() && (list.get(k))[6].equals(bookingNo)) {
list.remove(k);
k--;
}
}
}
}
}
return reckoningAcctList;
}
private String getReckoningInfo(Reckoning tblReckoning, Reckoning reckoning) {
String info = "";
if (reckoning != null && tblReckoning != null) {
if (!reckoning.getContact().equals(tblReckoning.getContact())) {
info = info + "联系人," + reckoning.getContact() + ","
+ tblReckoning.getContact() + ",";
}
if (!reckoning.getPhone().equals(tblReckoning.getPhone())) {
info = info + "电话," + reckoning.getPhone() + ","
+ tblReckoning.getPhone() + ",";
}
if (!reckoning.getFax().equals(tblReckoning.getFax())) {
info = info + "传真," + reckoning.getFax() + "," + tblReckoning.getFax()
+ ",";
}
}
return info;
}
}
| stevenzh/tourismwork | src/modules/hibernate/src/main/java/com/opentravelsoft/providers/hibernate/ReckoningDaoHibernate.java | 4,844 | // Object[] p = { reckoning.getBookingNo(), | line_comment | nl | package com.opentravelsoft.providers.hibernate;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.LockMode;
import org.springframework.stereotype.Repository;
import com.opentravelsoft.entity.Booking;
import com.opentravelsoft.entity.Employee;
import com.opentravelsoft.entity.Tourist;
import com.opentravelsoft.entity.finance.Reckoning;
import com.opentravelsoft.entity.finance.ReckoningAcct;
import com.opentravelsoft.entity.finance.ReckoningAcctId;
import com.opentravelsoft.providers.ReckoningDao;
import com.opentravelsoft.util.RowDataUtil;
/**
* 帐单制作
*
* @author <a herf="mailto:zhangsitao@gmail.com">Steven Zhang</a>
*/
@Repository("ReckoningDao")
public class ReckoningDaoHibernate extends
GenericDaoHibernate<Reckoning, Integer> implements ReckoningDao {
public ReckoningDaoHibernate() {
super(Reckoning.class);
}
@SuppressWarnings("unchecked")
public List<Reckoning> getReckoning(String reserveNo) {
StringBuilder sql = new StringBuilder();
sql.append("from Reckoning where bookingNo=? ");
Object[] param = { reserveNo };
List<Reckoning> list = getHibernateTemplate().find(sql.toString(), param);
for (Reckoning reckoning : list) {
reckoning.setVersion(RowDataUtil.getInt(reckoning.getNumber()));
reckoning.setCreateDate(RowDataUtil.getDate(reckoning.getCreated()));
reckoning.setPrintDate(RowDataUtil.getDate(reckoning.getPrinted()));
}
return list;
}
@SuppressWarnings("unchecked")
public Reckoning wholeReckoningMake(Reckoning reckoning) {
StringBuilder sql = new StringBuilder();
String reserveNo = reckoning.getBookingNo();
Reckoning tblReckoning = new Reckoning();
int version = 1;
// 续上版本号
sql.append("from Reckoning where bookingNo=? order by number ");
Object[] param = { reserveNo };
List<Reckoning> list = getHibernateTemplate().find(sql.toString(), param);
if (null == list || list.isEmpty()) {
tblReckoning.setNumber(version);
} else {
for (Reckoning obj : list) {
if (obj.getNumber() > version)
version = obj.getNumber();
}
tblReckoning.setNumber(++version);
}
//
tblReckoning.setBookingNo(reckoning.getBookingNo());
tblReckoning.setTourType(reckoning.getTourType());
tblReckoning.setContact(reckoning.getContact());
tblReckoning.setPhone(reckoning.getPhone());
tblReckoning.setFax(reckoning.getFax());
tblReckoning.setCreatedBy(reckoning.getCreatedBy());
tblReckoning.setPrintedCount(0);
getHibernateTemplate().save(tblReckoning);
// 得到帐单号
sql = new StringBuilder();
sql.append("from Reckoning where bookingNo=? and number=? ");
Object[] params = { reserveNo, version };
List<Reckoning> tblReckonings = getHibernateTemplate().find(sql.toString(),
params);
ReckoningAcct tblReckoningAcct;
ReckoningAcct reckoningAcct;
ReckoningAcctId tblReckoningAcctId;
reckoning.setReckoningId(tblReckonings.get(0).getReckoningId());
reckoning.setVersion(tblReckonings.get(0).getNumber());
if (reckoning.getTourType().equals("1")) {
if (!reckoning.getReckoningAcctList().isEmpty()) {
if (null != tblReckonings && !(tblReckonings.isEmpty())) {
for (int i = 0; i < reckoning.getReckoningAcctList().size(); i++) {
tblReckoningAcct = new ReckoningAcct();
tblReckoningAcctId = new ReckoningAcctId();
reckoningAcct = reckoning.getReckoningAcctList().get(i);
tblReckoningAcctId.setReckoningId(tblReckonings.get(0)
.getReckoningId());
tblReckoningAcctId.setItemId(reckoningAcct.getItemId());
tblReckoningAcct.setId(tblReckoningAcctId);
tblReckoningAcct.setAmount(reckoningAcct.getAmount());
tblReckoningAcct.setUnit(reckoningAcct.getUnit());
tblReckoningAcct.setDescription(reckoningAcct.getDescription());
tblReckoningAcct.setUnitPrice(reckoningAcct.getUnitPrice());
tblReckoningAcct.setCount(reckoningAcct.getCount());
getHibernateTemplate().save(tblReckoningAcct);
}
}
}
}
// 保存应收帐款
Booking tfj006 = (Booking) getHibernateTemplate().get(Booking.class,
reckoning.getBookingNo());
tfj006.setDbamt(reckoning.getAmount());
// --------------------------------------------------------------------
// String enabled = (String) ActionContext.getContext().getApplication()
// .get(EbizCommon.WORKFLOW_ENABLED);
// if (enabled.equals("1"))
// {
// StringBuilder sb = new StringBuilder();
// sb.append("select t ");
// sb.append("from org.jbpm.pvm.internal.task.TaskImpl t ");
// sb.append(",Booking b ");
// sb.append("where t.executionId=b.workflowId and b.nameNo=? ");
// sb.append("and t.name=? ");
// sb.append("and t.state!='" + Task.STATE_COMPLETED + "' ");
// Object[] p<SUF>
// WorkFlowKeyParams.ORDER_TASK_ACCOUNT };
// List<TaskImpl> taskInstances = getHibernateTemplate().find(
// sb.toString(), p);
//
// for (TaskImpl taskInstance : taskInstances)
// {
// taskInstance.createVariable(WorkFlowKeyParams.WORKFLOW_ACTOR,
// reckoning.getCreatedBy());
// taskService.completeTask(taskInstance.getId());
// }
// }
// --------------------------------------------------------------------
getHibernateTemplate().update(tfj006);
return reckoning;
}
@SuppressWarnings("unchecked")
public Reckoning getReckoningInfo(int reckoningId) {
Reckoning reckoning = (Reckoning) getHibernateTemplate().get(
Reckoning.class, reckoningId);
if (null != reckoning) {
reckoning.setVersion(RowDataUtil.getInt(reckoning.getNumber()));
reckoning.setCreateDate(RowDataUtil.getDate(reckoning.getCreated()));
reckoning.setPrintDate(RowDataUtil.getDate(reckoning.getPrinted()));
StringBuilder sql = new StringBuilder();
sql.append("from Employee where userId=?");
Object[] params = { reckoning.getCreatedBy() };
List<Employee> employees = getHibernateTemplate().find(sql.toString(),
params);
if (null != employees && !(employees.isEmpty()))
reckoning.setCreatedByName(employees.get(0).getUserName());
// 如果为整团,则取出帐单明细
if (reckoning.getTourType().equals("1")) {
sql = new StringBuilder();
sql.append("from ReckoningAcct where id.reckoningId=? ");
Object[] param = { reckoningId };
List<ReckoningAcct> tblReckoningAcctList = getHibernateTemplate().find(
sql.toString(), param);
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
for (ReckoningAcct obj : tblReckoningAcctList) {
obj.getId().setReckoningId(obj.getId().getReckoningId());
obj.setItemId(obj.getId().getItemId());
reckoningAcctList.add(obj);
}
reckoning.setReckoningAcctList(reckoningAcctList);
}
}
return reckoning;
}
@SuppressWarnings("unchecked")
public int wholeReckoningModify(Reckoning reckoning) {
StringBuilder sql = new StringBuilder();
Reckoning tblReckoning = new Reckoning();
tblReckoning = (Reckoning) getHibernateTemplate().get(Reckoning.class,
reckoning.getReckoningId(), LockMode.PESSIMISTIC_WRITE);
if (null != tblReckoning
&& tblReckoning.getReckoningId() == reckoning.getReckoningId()) {
// String str = getReckoningInfo(tblReckoning, reckoning);
tblReckoning.setContact(reckoning.getContact());
tblReckoning.setPhone(reckoning.getPhone());
tblReckoning.setFax(reckoning.getFax());
tblReckoning.setUpdatedBy(reckoning.getUpdatedBy());
getHibernateTemplate().update(tblReckoning);
if (reckoning.getTourType().equals("1")) {
sql = new StringBuilder();
sql.append("from ReckoningAcct where id.reckoningId=? ");
Object[] param2 = { reckoning.getReckoningId() };
List<ReckoningAcct> tblReckoningAcctList = getHibernateTemplate().find(
sql.toString(), param2);
getHibernateTemplate().deleteAll(tblReckoningAcctList);
ReckoningAcct tblReckoningAcct;
ReckoningAcct reckoningAcct;
ReckoningAcctId tblReckoningAcctId;
for (int i = 0; i < reckoning.getReckoningAcctList().size(); i++) {
tblReckoningAcct = new ReckoningAcct();
tblReckoningAcctId = new ReckoningAcctId();
reckoningAcct = reckoning.getReckoningAcctList().get(i);
tblReckoningAcctId.setReckoningId(reckoning.getReckoningId());
tblReckoningAcctId.setItemId(reckoningAcct.getItemId());
tblReckoningAcct.setId(tblReckoningAcctId);
tblReckoningAcct.setAmount(reckoningAcct.getAmount());
tblReckoningAcct.setUnit(reckoningAcct.getUnit());
tblReckoningAcct.setDescription(reckoningAcct.getDescription());
tblReckoningAcct.setUnitPrice(reckoningAcct.getUnitPrice());
tblReckoningAcct.setCount(reckoningAcct.getCount());
getHibernateTemplate().save(tblReckoningAcct);
}
}
// 修改应收帐款
Booking tfj006 = (Booking) getHibernateTemplate().get(Booking.class,
reckoning.getBookingNo());
BigDecimal old_Amount = tfj006.getDbamt();
tfj006.setDbamt(reckoning.getAmount());
getHibernateTemplate().update(tfj006);
String str1 = "账单号," + reckoning.getReckoningId() + ","
+ tblReckoning.getReckoningId() + ",";
if (old_Amount != tfj006.getDbamt()) {
str1 = str1 + "应收账款," + tfj006.getDbamt() + "," + old_Amount + ",";
}
return 0;
} else
return -1;
}
@SuppressWarnings("unchecked")
public List<ReckoningAcct> getCustomerList(String bookingNo) {
StringBuilder sql = new StringBuilder();
sql.append("from Tourist where booking.nameNo=? and del='N' ");
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
ReckoningAcct reckoningAcct;
Object[] params = { bookingNo };
List<Tourist> tourists = getHibernateTemplate()
.find(sql.toString(), params);
int itemId = 1;
for (Tourist obj : tourists) {
reckoningAcct = new ReckoningAcct();
reckoningAcct.setItemId(itemId++);
reckoningAcct.setName(RowDataUtil.getString(obj.getUserName()));
reckoningAcct.setAmount(RowDataUtil.getBigDecimal(obj.getAmt01()));
reckoningAcctList.add(reckoningAcct);
}
return reckoningAcctList;
}
public int setPrint(int reckoningId) {
Date sysdate = getSysdate();
Reckoning tblReckoning = new Reckoning();
tblReckoning = (Reckoning) getHibernateTemplate().get(Reckoning.class,
reckoningId, LockMode.PESSIMISTIC_WRITE);
tblReckoning.setPrintDate(sysdate);
tblReckoning.setPrintedCount(tblReckoning.getPrintedCount() + 1);
getHibernateTemplate().update(tblReckoning);
return 0;
}
@SuppressWarnings("unchecked")
public List<ReckoningAcct> getTourReckoningAcctList(String tourNo) {
StringBuilder sql = new StringBuilder();
sql.append("select b.reckoningId,c.description,c.unitPrice, ");
sql.append("c.count,c.amount,c.unit,b.bookingNo,b.number ");
sql.append("from Booking a, ");
sql.append("Reckoning b, ");
sql.append("ReckoningAcct c ");
sql.append("where a.plan.tourNo=? and a.nameNo=b.bookingNo ");
sql.append("and b.reckoningId=c.id.reckoningId ");
sql.append("order by b.bookingNo ");
Object[] param = { tourNo };
List<Object[]> list = getHibernateTemplate().find(sql.toString(), param);
List<ReckoningAcct> reckoningAcctList = new ArrayList<ReckoningAcct>();
if (!list.isEmpty()) {
ReckoningAcct reckoningAcct;
int size = list.size();
int number = 0;
String bookingNo = new String();
Object[] object1;
Object[] object2;
// 移除订单低版本的帐单
for (int i = 0; i < size; i++) {
if (null != list && i < list.size()) {
object1 = list.get(0);
bookingNo = RowDataUtil.getString(object1[6]);
number = RowDataUtil.getInt(object1[7]);
// 取此订单帐单最高版本号
for (int j = 0; j < list.size(); j++) {
object2 = list.get(j);
if (bookingNo.equals(RowDataUtil.getString(object2[6])))
if (number < RowDataUtil.getInt(object2[7]))
number = RowDataUtil.getInt(object2[7]);
}
// 取此订单帐单最高版本号所对应的帐单明细
for (Object[] obj : list) {
if (RowDataUtil.getString(obj[6]).equals(bookingNo)
&& RowDataUtil.getInt(obj[7]) == number) {
reckoningAcct = new ReckoningAcct();
reckoningAcct.getId().setReckoningId(RowDataUtil.getInt(obj[0]));
reckoningAcct.setDescription(RowDataUtil.getString(obj[1]));
reckoningAcct.setUnitPrice(RowDataUtil.getBigDecimal(obj[2]));
reckoningAcct.setCount(RowDataUtil.getInt(obj[3]));
reckoningAcct.setAmount(RowDataUtil.getBigDecimal(obj[4]));
reckoningAcct.setUnit(RowDataUtil.getString(obj[5]));
reckoningAcct.setBookingNo(RowDataUtil.getString(obj[6]));
reckoningAcctList.add(reckoningAcct);
}
}
int lastSize = list.size();
// 移除已取订单的所有帐单
for (int k = 0; k < lastSize; k++) {
if (k < list.size() && (list.get(k))[6].equals(bookingNo)) {
list.remove(k);
k--;
}
}
}
}
}
return reckoningAcctList;
}
private String getReckoningInfo(Reckoning tblReckoning, Reckoning reckoning) {
String info = "";
if (reckoning != null && tblReckoning != null) {
if (!reckoning.getContact().equals(tblReckoning.getContact())) {
info = info + "联系人," + reckoning.getContact() + ","
+ tblReckoning.getContact() + ",";
}
if (!reckoning.getPhone().equals(tblReckoning.getPhone())) {
info = info + "电话," + reckoning.getPhone() + ","
+ tblReckoning.getPhone() + ",";
}
if (!reckoning.getFax().equals(tblReckoning.getFax())) {
info = info + "传真," + reckoning.getFax() + "," + tblReckoning.getFax()
+ ",";
}
}
return info;
}
}
| False |
3,773 | 102037_34 | /**
Copyright © 2016, United States Government, as represented
by the Administrator of the National Aeronautics and Space
Administration. All rights reserved.
The MAV - Modeling, analysis and visualization of ATM concepts
platform is licensed under the Apache License, Version 2.0
(the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific
language governing permissions and limitations under the
License.
**/
package gov.nasa.arc.atc.core;
import gov.nasa.arc.atc.AfoUpdate;
import gov.nasa.arc.atc.ControllerHandOff;
import gov.nasa.arc.atc.FlightPlanUpdate;
import gov.nasa.arc.atc.SimulationManager;
import gov.nasa.arc.atc.algos.dsas.NamedArrivalGap;
import gov.nasa.arc.atc.geography.ATCNode;
import gov.nasa.arc.atc.geography.FlightSegment;
import gov.nasa.arc.atc.geography.Route;
import gov.nasa.arc.atc.simulation.SeparationViolation;
import gov.nasa.arc.atc.utils.Constants;
import java.util.*;
/**
* @author aWallace
* @author ahamon
*/
public class DataModel {
// constructor parameters
private final DataModelInput inputs;
//
private final List<ATCNode> allWaypoints;
// data built on load
private final List<NewPlane> allPlanes;
private final List<NewPlane> departingPlanes;
private final List<NewPlane> arrivingPlanes;
private final List<NewSlot> slots;
private final Map<Integer, List<DepartureInfo>> departuresInfos;
private Map<Integer, List<NamedArrivalGap>> arrivalGaps;
private List<Route> mainRoutes;
private List<Route> allRoutes;
// TO REFACTOR
private final List<String> departureQueue;
private final Map<String, NewPlane> departureMap;
private final Map<String, Integer> planeDepartTime;
private final Map<String, Double> planeETA;
private final Map<String, NewSlot> arrivingSlots;
private final List<Controller> atControllers;
//
private int maxTimeIndex;
private int currentTimeValue = 0;
// current index of timePoint list to set the simTime to
private int timePointsIndex;
private DataModel ghostModel = null;
/**
* @param dataInputs the inputs needed to build the {@link DataModel}
*/
public DataModel(DataModelInput dataInputs) {
inputs = dataInputs;
inputs.lock();
allWaypoints = SimulationManager.getATCGeography().getWaypoints();
//calculations
// setSimulationCalculations(new SimulationCalculations(Collections.unmodifiableMap(inputs.getAllUpdates()), createSectorMap(inputs.getControllerInitializationBlocks())) );
//
allPlanes = new ArrayList<>();
departingPlanes = new ArrayList<>();
arrivingPlanes = new ArrayList<>();
slots = new ArrayList<>();
departuresInfos = new HashMap<>();
//
departureQueue = new ArrayList<>();
departureMap = new HashMap<>();
planeDepartTime = new HashMap<>();
planeETA = new HashMap<>();
arrivingSlots = new HashMap<>();
atControllers = new ArrayList<>();
//
timePointsIndex = 0;
load();
}
private void load() {
// hum....
inputs.getSimulatedElements().forEach(element -> {
if (element instanceof NewPlane) {
NewPlane p = (NewPlane) element;
allPlanes.add(p);
//TODO
System.err.println("TODO::inDataModel isDeparture");
// if (p.isDeparture()) {
// addDepartingPlane(p);
// } else {
// addArrivingPlane(p);
// }
} else if (element instanceof NewSlot) {
NewSlot s = (NewSlot) element;
addSlot(s);
} else if (element instanceof Controller) {
Controller c = (Controller) element;
addController(c);
}
});
//maxSimTime = inputs.getAllTimePoints().last();
maxTimeIndex = inputs.getAllTimePoints().size();
//
buildDepartureQueue();
arrivalGaps = DataCalculationUtilities.calculateArrivalGaps(this);
//
currentTimeValue = inputs.getStartTime();
// build routes
buildRoutes();
buildFlightPlans();
}
//=======================================================
// organize??
// private void setSimulationCalculations(SimulationCalculations calculations) {
//// DisplayViewConfigurations.setSimulationCalculations(calculations);
// //TODO
// }
//TODO: remove if works in simulation calculations
// //note : this only works when a scenario that has controller init blocks is loaded
// private Map<String,String> createSectorMap(List<ControllerInitBlock> controllerInitializationBlocks){
// Map<String,String> controllerToSectorMap = new HashMap<>();
// Map<String,String> waypointToControllerMap = new HashMap<>();
// for(ControllerInitBlock block : controllerInitializationBlocks){
// String controller = block.getControllerName();
// String toWaypoint = block.getHandOffWaypoint();
// waypointToControllerMap.put(toWaypoint,controller);
// }
// for(ATCNode waypoint : allWaypoints){
// if (waypointToControllerMap.get(waypoint.getName()) != null){
// Sector sector = calculateSectorFromCoordinate(waypoint.getLatitude(),waypoint.getLongitude());
// String sectorName;
// if(sector == null){
// sectorName = "outside of sectors";
// }else{
// sectorName = sector.getName();
// }
// controllerToSectorMap.put( waypointToControllerMap.get(waypoint.getName()), sectorName );
// }
// }
// return controllerToSectorMap;
// }
// private Sector calculateSectorFromCoordinate(double latitude, double longitude){
// List<Sector> sectors = SimulationManager.getATCGeography().getSectors();
// for(Sector sectorToCheck : sectors){
// if(sectorToCheck.containsCoordinate(latitude,longitude)){
// return sectorToCheck;
// }
// }
// return null;
// }
//=======================================================
public DataModelInput getInputs() {
return inputs;
}
public List<ATCNode> getAllWaypoints() {
return Collections.unmodifiableList(allWaypoints);
}
/**
* @return all the {@link SimulatedElement} in the {@link DataModel}
*/
public List<SimulatedElement> geSimulatedElements() {
return Collections.unmodifiableList(inputs.getSimulatedElements());
}
public List<NewPlane> getAllPlanes() {
return Collections.unmodifiableList(allPlanes);
}
public List<NewSlot> getSlots() {
return Collections.unmodifiableList(slots);
}
public List<Controller> getATControllers() {
return Collections.unmodifiableList(atControllers);
}
public SortedSet<Integer> getTimePoints() {
return Collections.unmodifiableSortedSet(inputs.getAllTimePoints());
}
// public List<String> getDepartureQueue() {
// return Collections.unmodifiableList(departureQueue);
// }
public Map<Integer, List<SeparationViolation>> getSeparationViolators() {
return Collections.unmodifiableMap(inputs.getAllSeparationViolators());
}
public List<NewPlane> getDepartingPlanes() {
return Collections.unmodifiableList(departingPlanes);
}
public List<NewPlane> getArrivingPlanes() {
return Collections.unmodifiableList(arrivingPlanes);
}
public List<Route> getMainRoutes() {
//already unmodifiable
return mainRoutes;
}
public DepartureQueue getDepartureQueue() {
return inputs.getDepartureQueue();
}
public List<Route> getAllRoutes() {
return Collections.unmodifiableList(allRoutes);
}
public Map<String, Map<Integer, AfoUpdate>> getAllDataUpdates() {
return Collections.unmodifiableMap(inputs.getAllUpdates());
}
public Map<Integer, List<NamedArrivalGap>> getArrivalGaps() {
return Collections.unmodifiableMap(arrivalGaps);
}
public Map<Integer, List<ControllerHandOff>> getHandOffs() {
return Collections.unmodifiableMap(inputs.getHandOffs());
}
public int getSimTime() {
return currentTimeValue;
}
public int getMinSimTime() {
return inputs.getStartTime();
}
public int getMaxSimTime() {
return inputs.getEndTime();
}
public int getSimulationDuration() {
return inputs.getAllTimePoints().last();
}
public int incrementTime() {
if (timePointsIndex < maxTimeIndex) {
timePointsIndex++;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int decrementTime() {
if (timePointsIndex > 0) {
timePointsIndex--;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int setSimTime(int newtime) {
if (inputs.getAllTimePoints().contains(newtime)) {
for (int i = 0; i < maxTimeIndex; i++) {
// hum...
int time = (int) inputs.getAllTimePoints().toArray()[i];
if (time == newtime) {
currentTimeValue = time;
timePointsIndex = i;
updateModel();
return currentTimeValue;
}
}
}
return currentTimeValue;
}
public NewPlane getCorrespondingPlane(NewSlot slot) {
// TODO: use a map
for (NewPlane p : allPlanes) {
if (p.getSimpleName().equals(slot.getSimpleName())) {
return p;
}
}
return null;
}
public List<DepartureInfo> getDeparturesQueue(int time) {
return Collections.unmodifiableList(departuresInfos.get(time));
}
/*
* PRIVATE METHODS
*/
private void buildDepartureQueue() {
// for each simulation tine
inputs.getAllTimePoints().forEach(time -> {
final List<DepartureInfo> departures = new ArrayList<>();
// for each plane
departingPlanes.forEach(plane -> {
// get departure time
AfoUpdate update = inputs.getAllUpdates().get(plane.getFullName()).get(time);
if (update != null) {
int startTime = update.getStartTime();
int status = update.getStatus();
// TODO take care of initial departure time
if (startTime >= time && status == Constants.ON_GROUND) {
departures.add(new DepartureInfo(plane.getSimpleName(), startTime, startTime, departures.size()));
}
}
});
departuresInfos.put(time, departures);
});
//
}
private void addArrivingPlane(NewPlane plane) {
int index = 0;
for (int i = 0; i < arrivingPlanes.size(); i++) {
NewPlane p = arrivingPlanes.get(i);
if (plane.getEta() <= p.getEta()) {
index = i;
break;
} else
index = i + 1;
}
arrivingPlanes.add(index, plane);
planeETA.put(plane.getFullName(), plane.getEta());
}
private void addDepartingPlane(NewPlane plane) {
// TODO Refactor based on departure Time
int index = 0;
for (int i = 0; i < departingPlanes.size(); i++) {
NewPlane p = departingPlanes.get(i);
if (plane.getStartTime() <= p.getStartTime()) {
index = i;
break;
} else
index = i + 1;
}
//
departureMap.put(plane.getFullName(), plane);
departingPlanes.add(index, plane);
planeDepartTime.put(plane.getFullName(), plane.getStartTime());
}
private void addSlot(NewSlot s) {
arrivingSlots.put(s.getFullName(), s);
slots.add(s);
}
private void addController(Controller c) {
atControllers.add(c);
}
private void updateModel() {
getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getSlots().forEach(slot -> slot.update(currentTimeValue));
if (hasGhostModel()) {
getGhostModel().getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getGhostModel().getSlots().forEach(slot -> slot.update(currentTimeValue));
}
}
public void setGhostModel(DataModel ghostDataModel) {
ghostModel = ghostDataModel;
}
public boolean hasGhostModel() {
return ghostModel != null;
}
public Controller getGhostController(Controller c) {
if (hasGhostModel()) {
for (Controller atC : ghostModel.atControllers) {
if (atC.getName().equals(c.getName())) {
return atC;
}
}
}
return null;
}
public NewSlot getGhostSlot(NewSlot s) {
if (hasGhostModel()) {
return ghostModel.arrivingSlots.get(s.getFullName());
}
return null;
}
public NewPlane getGhostPlane(NewPlane p) {
if (hasGhostModel()) {
for (NewPlane plane : ghostModel.allPlanes) {
if (plane.getFullName().equals(p.getFullName())) {
return plane;
}
}
}
return null;
}
public DataModel getGhostModel() {
return ghostModel;
}
public List<FlightPlanUpdate> getFlighPlanUpdates() {
return Collections.unmodifiableList(inputs.getFlightPlanUpdates());
}
/*
Private methods
*/
private void buildRoutes() {
allRoutes = new LinkedList<>();
for (FlightPlanUpdate flightPlanUpdate : inputs.getFlightPlanUpdates()) {
final Route route = createRoute(flightPlanUpdate.getFlightSegments());
if (!allRoutes.contains(route)) {
allRoutes.add(route);
}
}
List<Route> filteredRoutes = new LinkedList<>(allRoutes);
for (Route r1 : allRoutes) {
for (Route r2 : allRoutes) {
if (r1.isContained(r2) && !r1.equals(r2) && filteredRoutes.contains(r1)) {
filteredRoutes.remove(r1);
}
}
}
mainRoutes = Collections.unmodifiableList(filteredRoutes);
}
private Route createRoute(List<FlightSegment> segments) {
Route route = new Route();
// if no segment
if (segments.isEmpty()) {
return route;
}
//not performance optimized?
List<FlightSegment> clone = new LinkedList<>(segments);
List<FlightSegment> orderedSegments = new ArrayList<>();
FlightSegment s0 = segments.get(0);
orderedSegments.add(s0);
clone.remove(s0);
while (!clone.isEmpty()) {
for (int i = 1; i < segments.size(); i++) {
final FlightSegment seg = segments.get(i);
//test at the start
if (orderedSegments.get(0).getFromWaypoint().getName().equals(seg.getToWaypoint().getName())) {
orderedSegments.add(0, seg);
clone.remove(seg);
break;
}
//test at the end
if (orderedSegments.get(orderedSegments.size() - 1).getToWaypoint().getName().equals(seg.getFromWaypoint().getName())) {
orderedSegments.add(seg);
clone.remove(seg);
}
}
}
// creating the route
FlightSegment startSeg = orderedSegments.get(0);
route.addAtStart(startSeg.getFromWaypoint());
route.addAtEnd(startSeg.getToWaypoint());
for (int i = 1; i < segments.size() - 1; i++) {
FlightSegment seg = orderedSegments.get(i);
route.addAtEnd(seg.getToWaypoint());
}
route.addAtEnd(orderedSegments.get(orderedSegments.size() - 1).getToWaypoint());
return route;
}
private void buildFlightPlans() {
inputs.getFlightPlanUpdates().forEach(flightPlanUpdate -> {
System.err.println(flightPlanUpdate);
// fli.get
});
}
}
| nasa/MAV | mas_visualization/viz-core/src/main/java/gov/nasa/arc/atc/core/DataModel.java | 4,815 | // get departure time | line_comment | nl | /**
Copyright © 2016, United States Government, as represented
by the Administrator of the National Aeronautics and Space
Administration. All rights reserved.
The MAV - Modeling, analysis and visualization of ATM concepts
platform is licensed under the Apache License, Version 2.0
(the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific
language governing permissions and limitations under the
License.
**/
package gov.nasa.arc.atc.core;
import gov.nasa.arc.atc.AfoUpdate;
import gov.nasa.arc.atc.ControllerHandOff;
import gov.nasa.arc.atc.FlightPlanUpdate;
import gov.nasa.arc.atc.SimulationManager;
import gov.nasa.arc.atc.algos.dsas.NamedArrivalGap;
import gov.nasa.arc.atc.geography.ATCNode;
import gov.nasa.arc.atc.geography.FlightSegment;
import gov.nasa.arc.atc.geography.Route;
import gov.nasa.arc.atc.simulation.SeparationViolation;
import gov.nasa.arc.atc.utils.Constants;
import java.util.*;
/**
* @author aWallace
* @author ahamon
*/
public class DataModel {
// constructor parameters
private final DataModelInput inputs;
//
private final List<ATCNode> allWaypoints;
// data built on load
private final List<NewPlane> allPlanes;
private final List<NewPlane> departingPlanes;
private final List<NewPlane> arrivingPlanes;
private final List<NewSlot> slots;
private final Map<Integer, List<DepartureInfo>> departuresInfos;
private Map<Integer, List<NamedArrivalGap>> arrivalGaps;
private List<Route> mainRoutes;
private List<Route> allRoutes;
// TO REFACTOR
private final List<String> departureQueue;
private final Map<String, NewPlane> departureMap;
private final Map<String, Integer> planeDepartTime;
private final Map<String, Double> planeETA;
private final Map<String, NewSlot> arrivingSlots;
private final List<Controller> atControllers;
//
private int maxTimeIndex;
private int currentTimeValue = 0;
// current index of timePoint list to set the simTime to
private int timePointsIndex;
private DataModel ghostModel = null;
/**
* @param dataInputs the inputs needed to build the {@link DataModel}
*/
public DataModel(DataModelInput dataInputs) {
inputs = dataInputs;
inputs.lock();
allWaypoints = SimulationManager.getATCGeography().getWaypoints();
//calculations
// setSimulationCalculations(new SimulationCalculations(Collections.unmodifiableMap(inputs.getAllUpdates()), createSectorMap(inputs.getControllerInitializationBlocks())) );
//
allPlanes = new ArrayList<>();
departingPlanes = new ArrayList<>();
arrivingPlanes = new ArrayList<>();
slots = new ArrayList<>();
departuresInfos = new HashMap<>();
//
departureQueue = new ArrayList<>();
departureMap = new HashMap<>();
planeDepartTime = new HashMap<>();
planeETA = new HashMap<>();
arrivingSlots = new HashMap<>();
atControllers = new ArrayList<>();
//
timePointsIndex = 0;
load();
}
private void load() {
// hum....
inputs.getSimulatedElements().forEach(element -> {
if (element instanceof NewPlane) {
NewPlane p = (NewPlane) element;
allPlanes.add(p);
//TODO
System.err.println("TODO::inDataModel isDeparture");
// if (p.isDeparture()) {
// addDepartingPlane(p);
// } else {
// addArrivingPlane(p);
// }
} else if (element instanceof NewSlot) {
NewSlot s = (NewSlot) element;
addSlot(s);
} else if (element instanceof Controller) {
Controller c = (Controller) element;
addController(c);
}
});
//maxSimTime = inputs.getAllTimePoints().last();
maxTimeIndex = inputs.getAllTimePoints().size();
//
buildDepartureQueue();
arrivalGaps = DataCalculationUtilities.calculateArrivalGaps(this);
//
currentTimeValue = inputs.getStartTime();
// build routes
buildRoutes();
buildFlightPlans();
}
//=======================================================
// organize??
// private void setSimulationCalculations(SimulationCalculations calculations) {
//// DisplayViewConfigurations.setSimulationCalculations(calculations);
// //TODO
// }
//TODO: remove if works in simulation calculations
// //note : this only works when a scenario that has controller init blocks is loaded
// private Map<String,String> createSectorMap(List<ControllerInitBlock> controllerInitializationBlocks){
// Map<String,String> controllerToSectorMap = new HashMap<>();
// Map<String,String> waypointToControllerMap = new HashMap<>();
// for(ControllerInitBlock block : controllerInitializationBlocks){
// String controller = block.getControllerName();
// String toWaypoint = block.getHandOffWaypoint();
// waypointToControllerMap.put(toWaypoint,controller);
// }
// for(ATCNode waypoint : allWaypoints){
// if (waypointToControllerMap.get(waypoint.getName()) != null){
// Sector sector = calculateSectorFromCoordinate(waypoint.getLatitude(),waypoint.getLongitude());
// String sectorName;
// if(sector == null){
// sectorName = "outside of sectors";
// }else{
// sectorName = sector.getName();
// }
// controllerToSectorMap.put( waypointToControllerMap.get(waypoint.getName()), sectorName );
// }
// }
// return controllerToSectorMap;
// }
// private Sector calculateSectorFromCoordinate(double latitude, double longitude){
// List<Sector> sectors = SimulationManager.getATCGeography().getSectors();
// for(Sector sectorToCheck : sectors){
// if(sectorToCheck.containsCoordinate(latitude,longitude)){
// return sectorToCheck;
// }
// }
// return null;
// }
//=======================================================
public DataModelInput getInputs() {
return inputs;
}
public List<ATCNode> getAllWaypoints() {
return Collections.unmodifiableList(allWaypoints);
}
/**
* @return all the {@link SimulatedElement} in the {@link DataModel}
*/
public List<SimulatedElement> geSimulatedElements() {
return Collections.unmodifiableList(inputs.getSimulatedElements());
}
public List<NewPlane> getAllPlanes() {
return Collections.unmodifiableList(allPlanes);
}
public List<NewSlot> getSlots() {
return Collections.unmodifiableList(slots);
}
public List<Controller> getATControllers() {
return Collections.unmodifiableList(atControllers);
}
public SortedSet<Integer> getTimePoints() {
return Collections.unmodifiableSortedSet(inputs.getAllTimePoints());
}
// public List<String> getDepartureQueue() {
// return Collections.unmodifiableList(departureQueue);
// }
public Map<Integer, List<SeparationViolation>> getSeparationViolators() {
return Collections.unmodifiableMap(inputs.getAllSeparationViolators());
}
public List<NewPlane> getDepartingPlanes() {
return Collections.unmodifiableList(departingPlanes);
}
public List<NewPlane> getArrivingPlanes() {
return Collections.unmodifiableList(arrivingPlanes);
}
public List<Route> getMainRoutes() {
//already unmodifiable
return mainRoutes;
}
public DepartureQueue getDepartureQueue() {
return inputs.getDepartureQueue();
}
public List<Route> getAllRoutes() {
return Collections.unmodifiableList(allRoutes);
}
public Map<String, Map<Integer, AfoUpdate>> getAllDataUpdates() {
return Collections.unmodifiableMap(inputs.getAllUpdates());
}
public Map<Integer, List<NamedArrivalGap>> getArrivalGaps() {
return Collections.unmodifiableMap(arrivalGaps);
}
public Map<Integer, List<ControllerHandOff>> getHandOffs() {
return Collections.unmodifiableMap(inputs.getHandOffs());
}
public int getSimTime() {
return currentTimeValue;
}
public int getMinSimTime() {
return inputs.getStartTime();
}
public int getMaxSimTime() {
return inputs.getEndTime();
}
public int getSimulationDuration() {
return inputs.getAllTimePoints().last();
}
public int incrementTime() {
if (timePointsIndex < maxTimeIndex) {
timePointsIndex++;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int decrementTime() {
if (timePointsIndex > 0) {
timePointsIndex--;
}
currentTimeValue = (int) inputs.getAllTimePoints().toArray()[timePointsIndex];
updateModel();
return currentTimeValue;
}
public int setSimTime(int newtime) {
if (inputs.getAllTimePoints().contains(newtime)) {
for (int i = 0; i < maxTimeIndex; i++) {
// hum...
int time = (int) inputs.getAllTimePoints().toArray()[i];
if (time == newtime) {
currentTimeValue = time;
timePointsIndex = i;
updateModel();
return currentTimeValue;
}
}
}
return currentTimeValue;
}
public NewPlane getCorrespondingPlane(NewSlot slot) {
// TODO: use a map
for (NewPlane p : allPlanes) {
if (p.getSimpleName().equals(slot.getSimpleName())) {
return p;
}
}
return null;
}
public List<DepartureInfo> getDeparturesQueue(int time) {
return Collections.unmodifiableList(departuresInfos.get(time));
}
/*
* PRIVATE METHODS
*/
private void buildDepartureQueue() {
// for each simulation tine
inputs.getAllTimePoints().forEach(time -> {
final List<DepartureInfo> departures = new ArrayList<>();
// for each plane
departingPlanes.forEach(plane -> {
// get departure<SUF>
AfoUpdate update = inputs.getAllUpdates().get(plane.getFullName()).get(time);
if (update != null) {
int startTime = update.getStartTime();
int status = update.getStatus();
// TODO take care of initial departure time
if (startTime >= time && status == Constants.ON_GROUND) {
departures.add(new DepartureInfo(plane.getSimpleName(), startTime, startTime, departures.size()));
}
}
});
departuresInfos.put(time, departures);
});
//
}
private void addArrivingPlane(NewPlane plane) {
int index = 0;
for (int i = 0; i < arrivingPlanes.size(); i++) {
NewPlane p = arrivingPlanes.get(i);
if (plane.getEta() <= p.getEta()) {
index = i;
break;
} else
index = i + 1;
}
arrivingPlanes.add(index, plane);
planeETA.put(plane.getFullName(), plane.getEta());
}
private void addDepartingPlane(NewPlane plane) {
// TODO Refactor based on departure Time
int index = 0;
for (int i = 0; i < departingPlanes.size(); i++) {
NewPlane p = departingPlanes.get(i);
if (plane.getStartTime() <= p.getStartTime()) {
index = i;
break;
} else
index = i + 1;
}
//
departureMap.put(plane.getFullName(), plane);
departingPlanes.add(index, plane);
planeDepartTime.put(plane.getFullName(), plane.getStartTime());
}
private void addSlot(NewSlot s) {
arrivingSlots.put(s.getFullName(), s);
slots.add(s);
}
private void addController(Controller c) {
atControllers.add(c);
}
private void updateModel() {
getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getSlots().forEach(slot -> slot.update(currentTimeValue));
if (hasGhostModel()) {
getGhostModel().getAllPlanes().forEach(plane -> plane.update(currentTimeValue));
getGhostModel().getSlots().forEach(slot -> slot.update(currentTimeValue));
}
}
public void setGhostModel(DataModel ghostDataModel) {
ghostModel = ghostDataModel;
}
public boolean hasGhostModel() {
return ghostModel != null;
}
public Controller getGhostController(Controller c) {
if (hasGhostModel()) {
for (Controller atC : ghostModel.atControllers) {
if (atC.getName().equals(c.getName())) {
return atC;
}
}
}
return null;
}
public NewSlot getGhostSlot(NewSlot s) {
if (hasGhostModel()) {
return ghostModel.arrivingSlots.get(s.getFullName());
}
return null;
}
public NewPlane getGhostPlane(NewPlane p) {
if (hasGhostModel()) {
for (NewPlane plane : ghostModel.allPlanes) {
if (plane.getFullName().equals(p.getFullName())) {
return plane;
}
}
}
return null;
}
public DataModel getGhostModel() {
return ghostModel;
}
public List<FlightPlanUpdate> getFlighPlanUpdates() {
return Collections.unmodifiableList(inputs.getFlightPlanUpdates());
}
/*
Private methods
*/
private void buildRoutes() {
allRoutes = new LinkedList<>();
for (FlightPlanUpdate flightPlanUpdate : inputs.getFlightPlanUpdates()) {
final Route route = createRoute(flightPlanUpdate.getFlightSegments());
if (!allRoutes.contains(route)) {
allRoutes.add(route);
}
}
List<Route> filteredRoutes = new LinkedList<>(allRoutes);
for (Route r1 : allRoutes) {
for (Route r2 : allRoutes) {
if (r1.isContained(r2) && !r1.equals(r2) && filteredRoutes.contains(r1)) {
filteredRoutes.remove(r1);
}
}
}
mainRoutes = Collections.unmodifiableList(filteredRoutes);
}
private Route createRoute(List<FlightSegment> segments) {
Route route = new Route();
// if no segment
if (segments.isEmpty()) {
return route;
}
//not performance optimized?
List<FlightSegment> clone = new LinkedList<>(segments);
List<FlightSegment> orderedSegments = new ArrayList<>();
FlightSegment s0 = segments.get(0);
orderedSegments.add(s0);
clone.remove(s0);
while (!clone.isEmpty()) {
for (int i = 1; i < segments.size(); i++) {
final FlightSegment seg = segments.get(i);
//test at the start
if (orderedSegments.get(0).getFromWaypoint().getName().equals(seg.getToWaypoint().getName())) {
orderedSegments.add(0, seg);
clone.remove(seg);
break;
}
//test at the end
if (orderedSegments.get(orderedSegments.size() - 1).getToWaypoint().getName().equals(seg.getFromWaypoint().getName())) {
orderedSegments.add(seg);
clone.remove(seg);
}
}
}
// creating the route
FlightSegment startSeg = orderedSegments.get(0);
route.addAtStart(startSeg.getFromWaypoint());
route.addAtEnd(startSeg.getToWaypoint());
for (int i = 1; i < segments.size() - 1; i++) {
FlightSegment seg = orderedSegments.get(i);
route.addAtEnd(seg.getToWaypoint());
}
route.addAtEnd(orderedSegments.get(orderedSegments.size() - 1).getToWaypoint());
return route;
}
private void buildFlightPlans() {
inputs.getFlightPlanUpdates().forEach(flightPlanUpdate -> {
System.err.println(flightPlanUpdate);
// fli.get
});
}
}
| False |
2,068 | 99697_1 | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset aan chart.
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| antonsteenvoorden/Studie-status | app/src/main/java/nl/antonsteenvoorden/ikpmd/ui/StandVanZakenFragment.java | 1,599 | // bind dataset aan chart. | line_comment | nl | package nl.antonsteenvoorden.ikpmd.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import nl.antonsteenvoorden.ikpmd.R;
import nl.antonsteenvoorden.ikpmd.adapter.VakkenAdapter;
import nl.antonsteenvoorden.ikpmd.model.Module;
public class StandVanZakenFragment extends Fragment {
View rootView;
Context context;
ListView listAandacht;
VakkenAdapter vakkenAdapter;
private PieChart standVanZakenChart;
private int maxECTS;
ArrayList<Entry> yValues;
ArrayList<String> xValues;
List<Module> modules;
List<Module> vakkenAandacht;
public StandVanZakenFragment() {
yValues = new ArrayList<>();
xValues = new ArrayList<>();
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static StandVanZakenFragment newInstance() {
StandVanZakenFragment fragment = new StandVanZakenFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_stand_van_zaken, container, false);
listAandacht = (ListView) rootView.findViewById(R.id.stand_van_zaken_list);
vakkenAandacht = new ArrayList<>();
modules = new ArrayList<>();
modules = Module.getAll();
context = rootView.getContext();
calculateECTS();
initChart();
getData();
vakkenAdapter = new VakkenAdapter(context, R.layout.vakken_list_item, vakkenAandacht);
listAandacht.setAdapter(vakkenAdapter);
ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
getData();
standVanZakenChart.animateY(1500);
}
public void initChart() {
standVanZakenChart = (PieChart) rootView.findViewById(R.id.chart);
standVanZakenChart.setDescription("");
standVanZakenChart.setTouchEnabled(false);
standVanZakenChart.setDrawSliceText(true);
standVanZakenChart.setDrawHoleEnabled(true);
standVanZakenChart.setHoleColorTransparent(true);
standVanZakenChart.setHoleRadius(85);
standVanZakenChart.setCenterTextColor(Color.rgb(0,188,186));
standVanZakenChart.setCenterText("0/0 \n Studiepunten behaald");
standVanZakenChart.setCenterTextSize(20);
standVanZakenChart.getLegend().setEnabled(false);
standVanZakenChart.animateY(1500);
}
public void calculateECTS() {
modules.clear();
modules = Module.getAll();
for(Module module : modules) {
this.maxECTS += module.getEcts();
}
}
public void getData() {
int tmpEcts = 0;
modules.clear();
vakkenAandacht.clear();
modules = Module.getAll();
for(Module module : modules) {
double tmpGrade = module.getGrade();
if(tmpGrade >= 5.5) {
tmpEcts += module.getEcts();
}
else if(module.isGradeSet() == 1 && tmpGrade <= 5.4){
vakkenAandacht.add(module);
}
}
setData(tmpEcts);
}
private void setData(int aantal) {
String label = (String) getString(R.string.stand_van_zaken_data);
standVanZakenChart.setCenterText(aantal + " / 60 \n"+ label );
if(xValues.size() >= 2 && yValues.size() >= 2) {
yValues.set(0, new Entry(aantal, 0));
yValues.set(1, new Entry(maxECTS-aantal, 1));
} else {
yValues.add(new Entry(aantal, 0));
yValues.add(new Entry(maxECTS - aantal, 1));
xValues.add("Behaalde ECTS");
xValues.add("Resterende ECTS");
}
ArrayList<Integer> colors = new ArrayList<>();
colors.add(Color.rgb(0 ,188,186)); // blue
colors.add(Color.rgb(35 ,10,78)); // deep purple
PieDataSet dataSet = new PieDataSet(yValues, "ECTS");
dataSet.setColors(colors);
dataSet.setDrawValues(false);
PieData data = new PieData(xValues, dataSet);
data.setDrawValues(false);
data.setValueTextSize(0.0f);
standVanZakenChart.setData(data); // bind dataset<SUF>
standVanZakenChart.invalidate(); // Aanroepen van een redraw
//redraw list view
listAandacht.invalidate();
Log.d("aantal ects ", Integer.toString(aantal));
}
}
| True |
4,451 | 209434_1 | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @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);
}
}
| tbarua1/uy | ServletTest/src/basic/GetParameterValues.java | 417 | /**
* @see HttpServlet#HttpServlet()
*/ | block_comment | nl | package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class GetParameterValues
*/
@WebServlet("/GetParameterValues")
public class GetParameterValues extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
<SUF>*/
public GetParameterValues() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String[] whisky = request.getParameterValues("qualification");
for(int i=0; i<whisky.length; i++){
pw.println("<br>whisky : " + whisky[i]);}
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @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);
}
}
| False |
1,837 | 32101_35 | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package de.verschwiegener.lwjgl3.util.glu.tessellation;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellator;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellatorCallback;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellatorCallbackAdapter;
import static de.verschwiegener.lwjgl3.util.glu.GLU.*;
public class GLUtessellatorImpl implements GLUtessellator {
public static final int TESS_MAX_CACHE = 100;
private int state; /* what begin/end calls have we seen? */
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
the tessellation itself */
/*** state needed for projecting onto the sweep plane ***/
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
/*** state needed for the line sweep ***/
private double relTolerance; /* tolerance for merging features */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
/*** state needed for rendering callbacks (see render.c) ***/
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean boundaryOnly; /* Extract contours, not triangles */
GLUface lonelyTriList;
/* list of triangles which could not be rendered as strips or fans */
/*** state needed to cache single-contour polygons for renderCache() */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
/*** rendering callbacks that also pass polygon data ***/
private Object polygonData; /* client data for current polygon */
private GLUtessellatorCallback callBegin;
private GLUtessellatorCallback callEdgeFlag;
private GLUtessellatorCallback callVertex;
private GLUtessellatorCallback callEnd;
// private GLUtessellatorCallback callMesh;
private GLUtessellatorCallback callError;
private GLUtessellatorCallback callCombine;
private GLUtessellatorCallback callBeginData;
private GLUtessellatorCallback callEdgeFlagData;
private GLUtessellatorCallback callVertexData;
private GLUtessellatorCallback callEndData;
// private GLUtessellatorCallback callMeshData;
private GLUtessellatorCallback callErrorData;
private GLUtessellatorCallback callCombineData;
private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0;
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter();
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
public GLUtessellatorImpl() {
state = TessState.T_DORMANT;
normal[0] = 0;
normal[1] = 0;
normal[2] = 0;
relTolerance = GLU_TESS_DEFAULT_TOLERANCE;
windingRule = GLU_TESS_WINDING_ODD;
flagBoundary = false;
boundaryOnly = false;
callBegin = NULL_CB;
callEdgeFlag = NULL_CB;
callVertex = NULL_CB;
callEnd = NULL_CB;
callError = NULL_CB;
callCombine = NULL_CB;
// callMesh = NULL_CB;
callBeginData = NULL_CB;
callEdgeFlagData = NULL_CB;
callVertexData = NULL_CB;
callEndData = NULL_CB;
callErrorData = NULL_CB;
callCombineData = NULL_CB;
polygonData = null;
for (int i = 0; i < cache.length; i++) {
cache[i] = new CachedVertex();
}
}
public static GLUtessellator gluNewTess()
{
return new GLUtessellatorImpl();
}
private void makeDormant() {
/* Return the tessellator to its original dormant state. */
if (mesh != null) {
Mesh.__gl_meshDeleteMesh(mesh);
}
state = TessState.T_DORMANT;
lastEdge = null;
mesh = null;
}
private void requireState(int newState) {
if (state != newState) gotoState(newState);
}
private void gotoState(int newState) {
while (state != newState) {
/* We change the current state one level at a time, to get to
* the desired state.
*/
if (state < newState) {
if (state == TessState.T_DORMANT) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_POLYGON);
gluTessBeginPolygon(null);
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_CONTOUR);
gluTessBeginContour();
}
} else {
if (state == TessState.T_IN_CONTOUR) {
callErrorOrErrorData(GLU_TESS_MISSING_END_CONTOUR);
gluTessEndContour();
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_END_POLYGON);
/* gluTessEndPolygon( tess ) is too much work! */
makeDormant();
}
}
}
}
public void gluDeleteTess() {
requireState(TessState.T_DORMANT);
}
public void gluTessProperty(int which, double value) {
switch (which) {
case GLU_TESS_TOLERANCE:
if (value < 0.0 || value > 1.0) break;
relTolerance = value;
return;
case GLU_TESS_WINDING_RULE:
int windingRule = (int) value;
if (windingRule != value) break; /* not an integer */
switch (windingRule) {
case GLU_TESS_WINDING_ODD:
case GLU_TESS_WINDING_NONZERO:
case GLU_TESS_WINDING_POSITIVE:
case GLU_TESS_WINDING_NEGATIVE:
case GLU_TESS_WINDING_ABS_GEQ_TWO:
this.windingRule = windingRule;
return;
default:
break;
}
case GLU_TESS_BOUNDARY_ONLY:
boundaryOnly = (value != 0);
return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
callErrorOrErrorData(GLU_INVALID_VALUE);
}
/* Returns tessellator property */
public void gluGetTessProperty(int which, double[] value, int value_offset) {
switch (which) {
case GLU_TESS_TOLERANCE:
/* tolerance should be in range [0..1] */
assert (0.0 <= relTolerance && relTolerance <= 1.0);
value[value_offset] = relTolerance;
break;
case GLU_TESS_WINDING_RULE:
assert (windingRule == GLU_TESS_WINDING_ODD ||
windingRule == GLU_TESS_WINDING_NONZERO ||
windingRule == GLU_TESS_WINDING_POSITIVE ||
windingRule == GLU_TESS_WINDING_NEGATIVE ||
windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
value[value_offset] = windingRule;
break;
case GLU_TESS_BOUNDARY_ONLY:
assert (boundaryOnly == true || boundaryOnly == false);
value[value_offset] = boundaryOnly ? 1 : 0;
break;
default:
value[value_offset] = 0.0;
callErrorOrErrorData(GLU_INVALID_ENUM);
break;
}
} /* gluGetTessProperty() */
public void gluTessNormal(double x, double y, double z) {
normal[0] = x;
normal[1] = y;
normal[2] = z;
}
public void gluTessCallback(int which, GLUtessellatorCallback aCallback) {
switch (which) {
case GLU_TESS_BEGIN:
callBegin = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_BEGIN_DATA:
callBeginData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_EDGE_FLAG:
callEdgeFlag = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = aCallback != null;
return;
case GLU_TESS_EDGE_FLAG_DATA:
callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = (aCallback != null);
return;
case GLU_TESS_VERTEX:
callVertex = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_VERTEX_DATA:
callVertexData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END:
callEnd = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END_DATA:
callEndData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR:
callError = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR_DATA:
callErrorData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE:
callCombine = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE_DATA:
callCombineData = aCallback == null ? NULL_CB : aCallback;
return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
}
private boolean addVertex(double[] coords, Object vertexData) {
GLUhalfEdge e;
e = lastEdge;
if (e == null) {
/* Make a self-loop (one vertex, one edge). */
e = Mesh.__gl_meshMakeEdge(mesh);
if (e == null) return false;
if (!Mesh.__gl_meshSplice(e, e.Sym)) return false;
} else {
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.__gl_meshSplitEdge(e) == null) return false;
e = e.Lnext;
}
/* The new vertex is now e.Org. */
e.Org.data = vertexData;
e.Org.coords[0] = coords[0];
e.Org.coords[1] = coords[1];
e.Org.coords[2] = coords[2];
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.Sym.winding = -1;
lastEdge = e;
return true;
}
private void cacheVertex(double[] coords, Object vertexData) {
if (cache[cacheCount] == null) {
cache[cacheCount] = new CachedVertex();
}
CachedVertex v = cache[cacheCount];
v.data = vertexData;
v.coords[0] = coords[0];
v.coords[1] = coords[1];
v.coords[2] = coords[2];
++cacheCount;
}
private boolean flushCache() {
CachedVertex[] v = cache;
mesh = Mesh.__gl_meshNewMesh();
if (mesh == null) return false;
for (int i = 0; i < cacheCount; i++) {
CachedVertex vertex = v[i];
if (!addVertex(vertex.coords, vertex.data)) return false;
}
cacheCount = 0;
flushCacheOnNextVertex = false;
return true;
}
public void gluTessVertex(double[] coords, int coords_offset, Object vertexData) {
int i;
boolean tooLarge = false;
double x;
double[] clamped = new double[3];
requireState(TessState.T_IN_CONTOUR);
if (flushCacheOnNextVertex) {
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
lastEdge = null;
}
for (i = 0; i < 3; ++i) {
x = coords[i+coords_offset];
if (x < -GLU_TESS_MAX_COORD) {
x = -GLU_TESS_MAX_COORD;
tooLarge = true;
}
if (x > GLU_TESS_MAX_COORD) {
x = GLU_TESS_MAX_COORD;
tooLarge = true;
}
clamped[i] = x;
}
if (tooLarge) {
callErrorOrErrorData(GLU_TESS_COORD_TOO_LARGE);
}
if (mesh == null) {
if (cacheCount < TESS_MAX_CACHE) {
cacheVertex(clamped, vertexData);
return;
}
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
}
if (!addVertex(clamped, vertexData)) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
public void gluTessBeginPolygon(Object data) {
requireState(TessState.T_DORMANT);
state = TessState.T_IN_POLYGON;
cacheCount = 0;
flushCacheOnNextVertex = false;
mesh = null;
polygonData = data;
}
public void gluTessBeginContour() {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_IN_CONTOUR;
lastEdge = null;
if (cacheCount > 0) {
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
flushCacheOnNextVertex = true;
}
}
public void gluTessEndContour() {
requireState(TessState.T_IN_CONTOUR);
state = TessState.T_IN_POLYGON;
}
public void gluTessEndPolygon() {
GLUmesh mesh;
try {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_DORMANT;
if (this.mesh == null) {
if (!flagBoundary /*&& callMesh == NULL_CB*/) {
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (Render.__gl_renderCache(this)) {
polygonData = null;
return;
}
}
if (!flushCache()) throw new RuntimeException(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
Normal.__gl_projectPolygon(this);
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
if (!Sweep.__gl_computeInterior(this)) {
throw new RuntimeException(); /* could've used a label */
}
mesh = this.mesh;
if (!fatalError) {
boolean rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly) {
rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true);
} else {
rc = TessMono.__gl_meshTessellateInterior(mesh);
}
if (!rc) throw new RuntimeException(); /* could've used a label */
Mesh.__gl_meshCheckMesh(mesh);
if (callBegin != NULL_CB || callEnd != NULL_CB
|| callVertex != NULL_CB || callEdgeFlag != NULL_CB
|| callBeginData != NULL_CB
|| callEndData != NULL_CB
|| callVertexData != NULL_CB
|| callEdgeFlagData != NULL_CB) {
if (boundaryOnly) {
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
} else {
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
}
}
// if (callMesh != NULL_CB) {
//
///* Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
}
Mesh.__gl_meshDeleteMesh(mesh);
polygonData = null;
mesh = null;
} catch (Exception e) {
e.printStackTrace();
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
public void gluBeginPolygon() {
gluTessBeginPolygon(null);
gluTessBeginContour();
}
/*ARGSUSED*/
public void gluNextContour(int type) {
gluTessEndContour();
gluTessBeginContour();
}
public void gluEndPolygon() {
gluTessEndContour();
gluTessEndPolygon();
}
void callBeginOrBeginData(int a) {
if (callBeginData != NULL_CB)
callBeginData.beginData(a, polygonData);
else
callBegin.begin(a);
}
void callVertexOrVertexData(Object a) {
if (callVertexData != NULL_CB)
callVertexData.vertexData(a, polygonData);
else
callVertex.vertex(a);
}
void callEdgeFlagOrEdgeFlagData(boolean a) {
if (callEdgeFlagData != NULL_CB)
callEdgeFlagData.edgeFlagData(a, polygonData);
else
callEdgeFlag.edgeFlag(a);
}
void callEndOrEndData() {
if (callEndData != NULL_CB)
callEndData.endData(polygonData);
else
callEnd.end();
}
void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) {
if (callCombineData != NULL_CB)
callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else
callCombine.combine(coords, vertexData, weights, outData);
}
void callErrorOrErrorData(int a) {
if (callErrorData != NULL_CB)
callErrorData.errorData(a, polygonData);
else
callError.error(a);
}
}
| Verschwiegener/MCLWJGL3 | src/de/verschwiegener/lwjgl3/util/glu/tessellation/GLUtessellatorImpl.java | 7,099 | /* not an integer */ | block_comment | nl | /*
* Copyright (c) 2002-2008 LWJGL Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'LWJGL' nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* Portions Copyright (C) 2003-2006 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
** License Applicability. Except to the extent portions of this file are
** made subject to an alternative license as permitted in the SGI Free
** Software License B, Version 1.1 (the "License"), the contents of this
** file are subject only to the provisions of the License. You may not use
** this file except in compliance with the License. You may obtain a copy
** of the License at Silicon Graphics, Inc., attn: Legal Services, 1600
** Amphitheatre Parkway, Mountain View, CA 94043-1351, or at:
**
** http://oss.sgi.com/projects/FreeB
**
** Note that, as provided in the License, the Software is distributed on an
** "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS
** DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND
** CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A
** PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
**
** NOTE: The Original Code (as defined below) has been licensed to Sun
** Microsystems, Inc. ("Sun") under the SGI Free Software License B
** (Version 1.1), shown above ("SGI License"). Pursuant to Section
** 3.2(3) of the SGI License, Sun is distributing the Covered Code to
** you under an alternative license ("Alternative License"). This
** Alternative License includes all of the provisions of the SGI License
** except that Section 2.2 and 11 are omitted. Any differences between
** the Alternative License and the SGI License are offered solely by Sun
** and not by SGI.
**
** Original Code. The Original Code is: OpenGL Sample Implementation,
** Version 1.2.1, released January 26, 2000, developed by Silicon Graphics,
** Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc.
** Copyright in any portions created by third parties is as indicated
** elsewhere herein. All Rights Reserved.
**
** Additional Notice Provisions: The application programming interfaces
** established by SGI in conjunction with the Original Code are The
** OpenGL(R) Graphics System: A Specification (Version 1.2.1), released
** April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version
** 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X
** Window System(R) (Version 1.3), released October 19, 1998. This software
** was created using the OpenGL(R) version 1.2.1 Sample Implementation
** published by SGI, but has not been independently verified as being
** compliant with the OpenGL(R) version 1.2.1 Specification.
**
** Author: Eric Veach, July 1994
** Java Port: Pepijn Van Eeckhoudt, July 2003
** Java Port: Nathan Parker Burg, August 2003
*/
package de.verschwiegener.lwjgl3.util.glu.tessellation;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellator;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellatorCallback;
import de.verschwiegener.lwjgl3.util.glu.GLUtessellatorCallbackAdapter;
import static de.verschwiegener.lwjgl3.util.glu.GLU.*;
public class GLUtessellatorImpl implements GLUtessellator {
public static final int TESS_MAX_CACHE = 100;
private int state; /* what begin/end calls have we seen? */
private GLUhalfEdge lastEdge; /* lastEdge->Org is the most recent vertex */
GLUmesh mesh; /* stores the input contours, and eventually
the tessellation itself */
/*** state needed for projecting onto the sweep plane ***/
double[] normal = new double[3]; /* user-specified normal (if provided) */
double[] sUnit = new double[3]; /* unit vector in s-direction (debugging) */
double[] tUnit = new double[3]; /* unit vector in t-direction (debugging) */
/*** state needed for the line sweep ***/
private double relTolerance; /* tolerance for merging features */
int windingRule; /* rule for determining polygon interior */
boolean fatalError; /* fatal error: needed combine callback */
Dict dict; /* edge dictionary for sweep line */
PriorityQ pq; /* priority queue of vertex events */
GLUvertex event; /* current sweep event being processed */
/*** state needed for rendering callbacks (see render.c) ***/
boolean flagBoundary; /* mark boundary edges (use EdgeFlag) */
boolean boundaryOnly; /* Extract contours, not triangles */
GLUface lonelyTriList;
/* list of triangles which could not be rendered as strips or fans */
/*** state needed to cache single-contour polygons for renderCache() */
private boolean flushCacheOnNextVertex; /* empty cache on next vertex() call */
int cacheCount; /* number of cached vertices */
CachedVertex[] cache = new CachedVertex[TESS_MAX_CACHE]; /* the vertex data */
/*** rendering callbacks that also pass polygon data ***/
private Object polygonData; /* client data for current polygon */
private GLUtessellatorCallback callBegin;
private GLUtessellatorCallback callEdgeFlag;
private GLUtessellatorCallback callVertex;
private GLUtessellatorCallback callEnd;
// private GLUtessellatorCallback callMesh;
private GLUtessellatorCallback callError;
private GLUtessellatorCallback callCombine;
private GLUtessellatorCallback callBeginData;
private GLUtessellatorCallback callEdgeFlagData;
private GLUtessellatorCallback callVertexData;
private GLUtessellatorCallback callEndData;
// private GLUtessellatorCallback callMeshData;
private GLUtessellatorCallback callErrorData;
private GLUtessellatorCallback callCombineData;
private static final double GLU_TESS_DEFAULT_TOLERANCE = 0.0;
// private static final int GLU_TESS_MESH = 100112; /* void (*)(GLUmesh *mesh) */
private static GLUtessellatorCallback NULL_CB = new GLUtessellatorCallbackAdapter();
// #define MAX_FAST_ALLOC (MAX(sizeof(EdgePair), \
// MAX(sizeof(GLUvertex),sizeof(GLUface))))
public GLUtessellatorImpl() {
state = TessState.T_DORMANT;
normal[0] = 0;
normal[1] = 0;
normal[2] = 0;
relTolerance = GLU_TESS_DEFAULT_TOLERANCE;
windingRule = GLU_TESS_WINDING_ODD;
flagBoundary = false;
boundaryOnly = false;
callBegin = NULL_CB;
callEdgeFlag = NULL_CB;
callVertex = NULL_CB;
callEnd = NULL_CB;
callError = NULL_CB;
callCombine = NULL_CB;
// callMesh = NULL_CB;
callBeginData = NULL_CB;
callEdgeFlagData = NULL_CB;
callVertexData = NULL_CB;
callEndData = NULL_CB;
callErrorData = NULL_CB;
callCombineData = NULL_CB;
polygonData = null;
for (int i = 0; i < cache.length; i++) {
cache[i] = new CachedVertex();
}
}
public static GLUtessellator gluNewTess()
{
return new GLUtessellatorImpl();
}
private void makeDormant() {
/* Return the tessellator to its original dormant state. */
if (mesh != null) {
Mesh.__gl_meshDeleteMesh(mesh);
}
state = TessState.T_DORMANT;
lastEdge = null;
mesh = null;
}
private void requireState(int newState) {
if (state != newState) gotoState(newState);
}
private void gotoState(int newState) {
while (state != newState) {
/* We change the current state one level at a time, to get to
* the desired state.
*/
if (state < newState) {
if (state == TessState.T_DORMANT) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_POLYGON);
gluTessBeginPolygon(null);
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_BEGIN_CONTOUR);
gluTessBeginContour();
}
} else {
if (state == TessState.T_IN_CONTOUR) {
callErrorOrErrorData(GLU_TESS_MISSING_END_CONTOUR);
gluTessEndContour();
} else if (state == TessState.T_IN_POLYGON) {
callErrorOrErrorData(GLU_TESS_MISSING_END_POLYGON);
/* gluTessEndPolygon( tess ) is too much work! */
makeDormant();
}
}
}
}
public void gluDeleteTess() {
requireState(TessState.T_DORMANT);
}
public void gluTessProperty(int which, double value) {
switch (which) {
case GLU_TESS_TOLERANCE:
if (value < 0.0 || value > 1.0) break;
relTolerance = value;
return;
case GLU_TESS_WINDING_RULE:
int windingRule = (int) value;
if (windingRule != value) break; /* not an integer<SUF>*/
switch (windingRule) {
case GLU_TESS_WINDING_ODD:
case GLU_TESS_WINDING_NONZERO:
case GLU_TESS_WINDING_POSITIVE:
case GLU_TESS_WINDING_NEGATIVE:
case GLU_TESS_WINDING_ABS_GEQ_TWO:
this.windingRule = windingRule;
return;
default:
break;
}
case GLU_TESS_BOUNDARY_ONLY:
boundaryOnly = (value != 0);
return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
callErrorOrErrorData(GLU_INVALID_VALUE);
}
/* Returns tessellator property */
public void gluGetTessProperty(int which, double[] value, int value_offset) {
switch (which) {
case GLU_TESS_TOLERANCE:
/* tolerance should be in range [0..1] */
assert (0.0 <= relTolerance && relTolerance <= 1.0);
value[value_offset] = relTolerance;
break;
case GLU_TESS_WINDING_RULE:
assert (windingRule == GLU_TESS_WINDING_ODD ||
windingRule == GLU_TESS_WINDING_NONZERO ||
windingRule == GLU_TESS_WINDING_POSITIVE ||
windingRule == GLU_TESS_WINDING_NEGATIVE ||
windingRule == GLU_TESS_WINDING_ABS_GEQ_TWO);
value[value_offset] = windingRule;
break;
case GLU_TESS_BOUNDARY_ONLY:
assert (boundaryOnly == true || boundaryOnly == false);
value[value_offset] = boundaryOnly ? 1 : 0;
break;
default:
value[value_offset] = 0.0;
callErrorOrErrorData(GLU_INVALID_ENUM);
break;
}
} /* gluGetTessProperty() */
public void gluTessNormal(double x, double y, double z) {
normal[0] = x;
normal[1] = y;
normal[2] = z;
}
public void gluTessCallback(int which, GLUtessellatorCallback aCallback) {
switch (which) {
case GLU_TESS_BEGIN:
callBegin = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_BEGIN_DATA:
callBeginData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_EDGE_FLAG:
callEdgeFlag = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = aCallback != null;
return;
case GLU_TESS_EDGE_FLAG_DATA:
callEdgeFlagData = callBegin = aCallback == null ? NULL_CB : aCallback;
/* If the client wants boundary edges to be flagged,
* we render everything as separate triangles (no strips or fans).
*/
flagBoundary = (aCallback != null);
return;
case GLU_TESS_VERTEX:
callVertex = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_VERTEX_DATA:
callVertexData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END:
callEnd = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_END_DATA:
callEndData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR:
callError = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_ERROR_DATA:
callErrorData = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE:
callCombine = aCallback == null ? NULL_CB : aCallback;
return;
case GLU_TESS_COMBINE_DATA:
callCombineData = aCallback == null ? NULL_CB : aCallback;
return;
// case GLU_TESS_MESH:
// callMesh = aCallback == null ? NULL_CB : aCallback;
// return;
default:
callErrorOrErrorData(GLU_INVALID_ENUM);
return;
}
}
private boolean addVertex(double[] coords, Object vertexData) {
GLUhalfEdge e;
e = lastEdge;
if (e == null) {
/* Make a self-loop (one vertex, one edge). */
e = Mesh.__gl_meshMakeEdge(mesh);
if (e == null) return false;
if (!Mesh.__gl_meshSplice(e, e.Sym)) return false;
} else {
/* Create a new vertex and edge which immediately follow e
* in the ordering around the left face.
*/
if (Mesh.__gl_meshSplitEdge(e) == null) return false;
e = e.Lnext;
}
/* The new vertex is now e.Org. */
e.Org.data = vertexData;
e.Org.coords[0] = coords[0];
e.Org.coords[1] = coords[1];
e.Org.coords[2] = coords[2];
/* The winding of an edge says how the winding number changes as we
* cross from the edge''s right face to its left face. We add the
* vertices in such an order that a CCW contour will add +1 to
* the winding number of the region inside the contour.
*/
e.winding = 1;
e.Sym.winding = -1;
lastEdge = e;
return true;
}
private void cacheVertex(double[] coords, Object vertexData) {
if (cache[cacheCount] == null) {
cache[cacheCount] = new CachedVertex();
}
CachedVertex v = cache[cacheCount];
v.data = vertexData;
v.coords[0] = coords[0];
v.coords[1] = coords[1];
v.coords[2] = coords[2];
++cacheCount;
}
private boolean flushCache() {
CachedVertex[] v = cache;
mesh = Mesh.__gl_meshNewMesh();
if (mesh == null) return false;
for (int i = 0; i < cacheCount; i++) {
CachedVertex vertex = v[i];
if (!addVertex(vertex.coords, vertex.data)) return false;
}
cacheCount = 0;
flushCacheOnNextVertex = false;
return true;
}
public void gluTessVertex(double[] coords, int coords_offset, Object vertexData) {
int i;
boolean tooLarge = false;
double x;
double[] clamped = new double[3];
requireState(TessState.T_IN_CONTOUR);
if (flushCacheOnNextVertex) {
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
lastEdge = null;
}
for (i = 0; i < 3; ++i) {
x = coords[i+coords_offset];
if (x < -GLU_TESS_MAX_COORD) {
x = -GLU_TESS_MAX_COORD;
tooLarge = true;
}
if (x > GLU_TESS_MAX_COORD) {
x = GLU_TESS_MAX_COORD;
tooLarge = true;
}
clamped[i] = x;
}
if (tooLarge) {
callErrorOrErrorData(GLU_TESS_COORD_TOO_LARGE);
}
if (mesh == null) {
if (cacheCount < TESS_MAX_CACHE) {
cacheVertex(clamped, vertexData);
return;
}
if (!flushCache()) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
return;
}
}
if (!addVertex(clamped, vertexData)) {
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
public void gluTessBeginPolygon(Object data) {
requireState(TessState.T_DORMANT);
state = TessState.T_IN_POLYGON;
cacheCount = 0;
flushCacheOnNextVertex = false;
mesh = null;
polygonData = data;
}
public void gluTessBeginContour() {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_IN_CONTOUR;
lastEdge = null;
if (cacheCount > 0) {
/* Just set a flag so we don't get confused by empty contours
* -- these can be generated accidentally with the obsolete
* NextContour() interface.
*/
flushCacheOnNextVertex = true;
}
}
public void gluTessEndContour() {
requireState(TessState.T_IN_CONTOUR);
state = TessState.T_IN_POLYGON;
}
public void gluTessEndPolygon() {
GLUmesh mesh;
try {
requireState(TessState.T_IN_POLYGON);
state = TessState.T_DORMANT;
if (this.mesh == null) {
if (!flagBoundary /*&& callMesh == NULL_CB*/) {
/* Try some special code to make the easy cases go quickly
* (eg. convex polygons). This code does NOT handle multiple contours,
* intersections, edge flags, and of course it does not generate
* an explicit mesh either.
*/
if (Render.__gl_renderCache(this)) {
polygonData = null;
return;
}
}
if (!flushCache()) throw new RuntimeException(); /* could've used a label*/
}
/* Determine the polygon normal and project vertices onto the plane
* of the polygon.
*/
Normal.__gl_projectPolygon(this);
/* __gl_computeInterior( tess ) computes the planar arrangement specified
* by the given contours, and further subdivides this arrangement
* into regions. Each region is marked "inside" if it belongs
* to the polygon, according to the rule given by windingRule.
* Each interior region is guaranteed be monotone.
*/
if (!Sweep.__gl_computeInterior(this)) {
throw new RuntimeException(); /* could've used a label */
}
mesh = this.mesh;
if (!fatalError) {
boolean rc = true;
/* If the user wants only the boundary contours, we throw away all edges
* except those which separate the interior from the exterior.
* Otherwise we tessellate all the regions marked "inside".
*/
if (boundaryOnly) {
rc = TessMono.__gl_meshSetWindingNumber(mesh, 1, true);
} else {
rc = TessMono.__gl_meshTessellateInterior(mesh);
}
if (!rc) throw new RuntimeException(); /* could've used a label */
Mesh.__gl_meshCheckMesh(mesh);
if (callBegin != NULL_CB || callEnd != NULL_CB
|| callVertex != NULL_CB || callEdgeFlag != NULL_CB
|| callBeginData != NULL_CB
|| callEndData != NULL_CB
|| callVertexData != NULL_CB
|| callEdgeFlagData != NULL_CB) {
if (boundaryOnly) {
Render.__gl_renderBoundary(this, mesh); /* output boundary contours */
} else {
Render.__gl_renderMesh(this, mesh); /* output strips and fans */
}
}
// if (callMesh != NULL_CB) {
//
///* Throw away the exterior faces, so that all faces are interior.
// * This way the user doesn't have to check the "inside" flag,
// * and we don't need to even reveal its existence. It also leaves
// * the freedom for an implementation to not generate the exterior
// * faces in the first place.
// */
// TessMono.__gl_meshDiscardExterior(mesh);
// callMesh.mesh(mesh); /* user wants the mesh itself */
// mesh = null;
// polygonData = null;
// return;
// }
}
Mesh.__gl_meshDeleteMesh(mesh);
polygonData = null;
mesh = null;
} catch (Exception e) {
e.printStackTrace();
callErrorOrErrorData(GLU_OUT_OF_MEMORY);
}
}
/*******************************************************/
/* Obsolete calls -- for backward compatibility */
public void gluBeginPolygon() {
gluTessBeginPolygon(null);
gluTessBeginContour();
}
/*ARGSUSED*/
public void gluNextContour(int type) {
gluTessEndContour();
gluTessBeginContour();
}
public void gluEndPolygon() {
gluTessEndContour();
gluTessEndPolygon();
}
void callBeginOrBeginData(int a) {
if (callBeginData != NULL_CB)
callBeginData.beginData(a, polygonData);
else
callBegin.begin(a);
}
void callVertexOrVertexData(Object a) {
if (callVertexData != NULL_CB)
callVertexData.vertexData(a, polygonData);
else
callVertex.vertex(a);
}
void callEdgeFlagOrEdgeFlagData(boolean a) {
if (callEdgeFlagData != NULL_CB)
callEdgeFlagData.edgeFlagData(a, polygonData);
else
callEdgeFlag.edgeFlag(a);
}
void callEndOrEndData() {
if (callEndData != NULL_CB)
callEndData.endData(polygonData);
else
callEnd.end();
}
void callCombineOrCombineData(double[] coords, Object[] vertexData, float[] weights, Object[] outData) {
if (callCombineData != NULL_CB)
callCombineData.combineData(coords, vertexData, weights, outData, polygonData);
else
callCombine.combine(coords, vertexData, weights, outData);
}
void callErrorOrErrorData(int a) {
if (callErrorData != NULL_CB)
callErrorData.errorData(a, polygonData);
else
callError.error(a);
}
}
| False |
3,200 | 85648_5 | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| jeffreyvr/spookrijder | src/main/java/nl/han/ica/spookrijder/VerzamelObject.java | 1,032 | /**
* Verkrijg breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De breedte van het object.
* @since 11-05-2018
* @version 1.0
*/ | block_comment | nl | package nl.han.ica.spookrijder;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.Sprite;
import nl.han.ica.OOPDProcessingEngineHAN.Objects.SpriteObject;
import nl.han.ica.OOPDProcessingEngineHAN.Sound.Sound;
public abstract class VerzamelObject extends SpriteObject {
private Spookrijder spookrijder;
private boolean aangeraakt = false;
private int breedte;
private int hoogte;
protected String geluidsnaam; // naam van geluidsbestand
public VerzamelObject(Spookrijder spookrijder, Sprite sprite) {
super(sprite);
this.spookrijder = spookrijder;
setxSpeed(-3);
}
/**
* Update
*
* Zet aangeraakt status en zichtbaarheid op basis van x positie.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
@Override
public void update() {
if (this.getX() < (0 - this.getWidth())) {
this.setX(spookrijder.getWidth() + this.getWidth());
this.setAangeraakt(false);
this.setVisible(true);
}
}
/**
* Zet aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setAangeraakt(boolean aangeraakt) {
this.aangeraakt = aangeraakt;
}
/**
* Verkrijg aangeraakt
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @return Aangeraakt-status van het object.
* @version 1.0
*/
public boolean getAangeraakt() {
return this.aangeraakt;
}
/**
* Verkrijg hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @return De hoogte van het object.
* @since 11-05-2018
* @version 1.0
*/
public float getHeight() {
return this.hoogte;
}
/**
* Verkrijg breedte
<SUF>*/
public float getWidth() {
return this.breedte;
}
/**
* Zet hoogte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setHeight(int hoogte) {
this.hoogte = hoogte;
}
/**
* Zet breedte
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void setWidth(int breedte) {
this.breedte = breedte;
}
/**
* Doe Geluid
*
* Initialiseert een geluidsobject en speelt deze af.
*
* @author Jurrian te Loo, Jeffrey van Rossum
* @since 11-05-2018
* @version 1.0
*/
public void doeGeluid() {
Sound geluid = new Sound(spookrijder,
"src/main/java/nl/han/ica/spookrijder/media/" + this.geluidsnaam + ".mp3");
geluid.play();
}
}
| True |
2,873 | 202578_22 | /*
* Copyright 2023 The original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.morling.onebrc;
import jdk.incubator.vector.*;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import static java.lang.foreign.ValueLayout.*;
/**
* Broad experiments in this implementation:
* - Memory-Map the file with new MemorySegments
* - Use SIMD/vectorized search for the semicolon and new line feeds
* - Use SIMD/vectorized comparison for the 'key'
* <p>
* Absolute stupid things / performance left on the table
* - Single Threaded! Multi threading planned.
* - The hash map/table is super basic.
* - Hash table implementation / hashing has no resizing and is quite basic
* - Zero time spend on profiling =)
* <p>
* <p>
* Cheats used:
* - Only works with Unix line feed \n
* - double parsing is only accepting XX.X and X.X
* - HashMap has no resizing, check, horrible hash etc.
* - Used the double parsing from yemreinci
*/
public class CalculateAverage_gamlerhart {
private static final String FILE = "./measurements.txt";
final static VectorSpecies<Byte> byteVec = ByteVector.SPECIES_PREFERRED;
final static Vector<Byte> zero = byteVec.zero();
final static int vecLen = byteVec.length();
final static Vector<Byte> semiColon = byteVec.broadcast(';');
final static VectorMask<Byte> allTrue = byteVec.maskAll(true);
final static ValueLayout.OfInt INT_UNALIGNED_BIG_ENDIAN = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN);
public static void main(String[] args) throws Exception {
try (var arena = Arena.ofShared();
FileChannel fc = FileChannel.open(Path.of(FILE))) {
long fileSize = fc.size();
MemorySegment fileContent = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, arena);
ArrayList<Section> sections = splitFileIntoSections(fileSize, fileContent);
var loopBound = byteVec.loopBound(fileSize) - vecLen;
var result = sections.stream()
.parallel()
.map(s -> {
return parseSection(s.start, s.end, loopBound, fileContent);
});
var measurements = new TreeMap<String, ResultRow>();
result.forEachOrdered(m -> {
m.fillMerge(fileContent, measurements);
});
System.out.println(measurements);
}
}
private static PrivateHashMap parseSection(long start, long end, long loopBound, MemorySegment fileContent) {
var map = new PrivateHashMap();
for (long i = start; i < end;) {
long nameStart = i;
int simdSearchEnd = 0;
int nameLen = 0;
// Vectorized Search
if (i < loopBound) {
do {
var vec = byteVec.fromMemorySegment(fileContent, i, ByteOrder.BIG_ENDIAN);
var hasSemi = vec.eq(semiColon);
simdSearchEnd = hasSemi.firstTrue();
i += simdSearchEnd;
nameLen += simdSearchEnd;
} while (simdSearchEnd == vecLen && i < loopBound);
}
// Left-over search
while (loopBound <= i && fileContent.get(JAVA_BYTE, i) != ';') {
nameLen++;
i++;
}
i++; // Consume ;
// Copied from yemreinci. I mostly wanted to experiment the vector math, not with parsing =)
double val;
{
boolean negative = false;
if ((fileContent.get(JAVA_BYTE, i)) == '-') {
negative = true;
i++;
}
byte b;
double temp;
if ((b = fileContent.get(JAVA_BYTE, i + 1)) == '.') { // temperature is in either XX.X or X.X form
temp = (fileContent.get(JAVA_BYTE, i) - '0') + (fileContent.get(JAVA_BYTE, i + 2) - '0') / 10.0;
i += 3;
}
else {
temp = (fileContent.get(JAVA_BYTE, i) - '0') * 10 + (b - '0')
+ (fileContent.get(JAVA_BYTE, i + 3) - '0') / 10.0;
i += 4;
}
val = (negative ? -temp : temp);
}
i++; // Consume \n
map.add(fileContent, nameStart, nameLen, val);
}
return map;
}
private static ArrayList<Section> splitFileIntoSections(long fileSize, MemorySegment fileContent) {
var cpuCount = Runtime.getRuntime().availableProcessors();
var roughChunkSize = fileSize / cpuCount;
ArrayList<Section> sections = new ArrayList<>(cpuCount);
for (long sStart = 0; sStart < fileSize;) {
var endGuess = Math.min(sStart + roughChunkSize, fileSize);
for (; endGuess < fileSize && fileContent.get(JAVA_BYTE, endGuess) != '\n'; endGuess++) {
}
sections.add(new Section(sStart, endGuess));
sStart = endGuess + 1;
}
return sections;
}
private static class PrivateHashMap {
private static final int SIZE_SHIFT = 14;
public static final int SIZE = 1 << SIZE_SHIFT;
public static int MASK = 0xFFFFFFFF >>> (32 - SIZE_SHIFT);
public static long SHIFT_POS = 16;
public static long MASK_POS = 0xFFFFFFFFFFFF0000L;
public static long MASK_LEN = 0x000000000000FFFFL;
// Encoding:
// - Key: long
// - 48 bits index, 16 bits length
final long[] keys = new long[SIZE];
final Value[] values = new Value[SIZE];
private class Value {
public Value(double min, double max, double sum, long count) {
this.min = min;
this.max = max;
this.sum = sum;
this.count = count;
}
public double min;
public double max;
public double sum;
public long count;
}
// int debug_size = 0;
// int debug_reprobeMax = 0;
public PrivateHashMap() {
}
public void add(MemorySegment file, long pos, int len, double val) {
int hashCode = calculateHash(file, pos, len);
doAdd(file, hashCode, pos, len, val);
}
private static int calculateHash(MemorySegment file, long pos, int len) {
if (len > 4) {
return file.get(INT_UNALIGNED_BIG_ENDIAN, pos) + 31 * len;
}
else {
int hashCode = len;
int i = 0;
for (; i < len; i++) {
int v = file.get(JAVA_BYTE, pos + i);
hashCode = 31 * hashCode + v;
}
return hashCode;
}
}
private void doAdd(MemorySegment file, int hash, long pos, int len, double val) {
int slot = hash & MASK;
for (var probe = 0; probe < 20000; probe++) {
var iSl = ((slot + probe) & MASK);
var slotEntry = keys[iSl];
var emtpy = slotEntry == 0;
if (emtpy) {
long keyInfo = pos << SHIFT_POS | len;
keys[iSl] = keyInfo;
values[iSl] = new Value(val, val, val, 1);
// debug_size++;
return;
}
else if (isSameEntry(file, slotEntry, pos, len)) {
var vE = values[iSl];
vE.min = Math.min(vE.min, val);
vE.max = Math.max(vE.max, val);
vE.sum = vE.sum + val;
vE.count++;
return;
}
else {
// long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (slotEntry & MASK_LEN);
// System.out.println("Colliding " + new String(file.asSlice(pos,len).toArray(ValueLayout.JAVA_BYTE)) +
// " with key" + new String(file.asSlice(keyPos,keyLen).toArray(ValueLayout.JAVA_BYTE)) +
// " hash " + hash + " slot " + slot + "+" + probe + " at " + iSl);
// debug_reprobeMax = Math.max(debug_reprobeMax, probe);
}
}
throw new IllegalStateException("More than 20000 reprobes");
// throw new IllegalStateException("More than 100 reprobes: At " + debug_size + "");
}
private boolean isSameEntry(MemorySegment file, long slotEntry, long pos, int len) {
long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (slotEntry & MASK_LEN);
var isSame = len == keyLen && isSame(file, keyPos, pos, len);
return isSame;
}
private static boolean isSame(MemorySegment file, long i1, long i2, int len) {
int i = 0;
var i1len = i1 + vecLen;
var i2len = i2 + vecLen;
if (len < vecLen && i1len <= file.byteSize() && i2len <= file.byteSize()) {
var v1 = byteVec.fromMemorySegment(file, i1, ByteOrder.nativeOrder());
var v2 = byteVec.fromMemorySegment(file, i2, ByteOrder.nativeOrder());
var isTrue = v1.compare(VectorOperators.EQ, v2, allTrue.indexInRange(0, len));
return isTrue.trueCount() == len;
}
while (8 < (len - i)) {
var v1 = file.get(JAVA_LONG_UNALIGNED, i1 + i);
var v2 = file.get(JAVA_LONG_UNALIGNED, i2 + i);
if (v1 != v2) {
return false;
}
i += 8;
}
while (i < len) {
var v1 = file.get(JAVA_BYTE, i1 + i);
var v2 = file.get(JAVA_BYTE, i2 + i);
if (v1 != v2) {
return false;
}
i++;
}
return true;
}
public void fillMerge(MemorySegment file, TreeMap<String, ResultRow> treeMap) {
for (int i = 0; i < keys.length; i++) {
var ji = i;
long keyE = keys[ji];
if (keyE != 0) {
long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (keyE & MASK_LEN);
byte[] keyBytes = new byte[keyLen];
MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
var key = new String(keyBytes);
var vE = values[ji];
var min = vE.min;
var max = vE.max;
var sum = vE.sum;
var count = vE.count;
treeMap.compute(key, (k, e) -> {
if (e == null) {
return new ResultRow(min, max, sum, count);
}
else {
return new ResultRow(Math.min(e.min, min), Math.max(e.max, max), e.sum + sum, e.count + count);
}
});
}
}
}
// public String debugPrint(MemorySegment file) {
// StringBuilder b = new StringBuilder();
// for (int i = 0; i < keyValues.length / 5; i++) {
// var ji = i * 5;
// long keyE = keyValues[ji];
// if (keyE != 0) {
// long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (keyE & MASK_LEN);
// byte[] keyBytes = new byte[keyLen];
// MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
// var key = new String(keyBytes);
// var min = longBitsToDouble(keyValues[ji + 1]);
// var max = longBitsToDouble(keyValues[ji + 2]);
// var sum = longBitsToDouble(keyValues[ji + 3]);
// var count = keyValues[ji + 4];
// b.append("{").append(key).append("@").append(ji)
// .append(",").append(min)
// .append(",").append(max)
// .append(",").append(sum)
// .append(",").append(count).append("},");
// }
// }
// return b.toString();
// }
}
record Section(long start, long end) {
}
private static record ResultRow(double min, double max, double sum, long count) {
public String toString() {
return round(min) + "/" + round(((Math.round(sum * 10.0) / 10.0) / count)) + "/" + round(max);
}
private double round(double value) {
return Math.round(value * 10.0) / 10.0;
}
}
;
}
| gunnarmorling/1brc | src/main/java/dev/morling/onebrc/CalculateAverage_gamlerhart.java | 4,059 | // int keyLen = (int) (keyE & MASK_LEN); | line_comment | nl | /*
* Copyright 2023 The original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.morling.onebrc;
import jdk.incubator.vector.*;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import static java.lang.foreign.ValueLayout.*;
/**
* Broad experiments in this implementation:
* - Memory-Map the file with new MemorySegments
* - Use SIMD/vectorized search for the semicolon and new line feeds
* - Use SIMD/vectorized comparison for the 'key'
* <p>
* Absolute stupid things / performance left on the table
* - Single Threaded! Multi threading planned.
* - The hash map/table is super basic.
* - Hash table implementation / hashing has no resizing and is quite basic
* - Zero time spend on profiling =)
* <p>
* <p>
* Cheats used:
* - Only works with Unix line feed \n
* - double parsing is only accepting XX.X and X.X
* - HashMap has no resizing, check, horrible hash etc.
* - Used the double parsing from yemreinci
*/
public class CalculateAverage_gamlerhart {
private static final String FILE = "./measurements.txt";
final static VectorSpecies<Byte> byteVec = ByteVector.SPECIES_PREFERRED;
final static Vector<Byte> zero = byteVec.zero();
final static int vecLen = byteVec.length();
final static Vector<Byte> semiColon = byteVec.broadcast(';');
final static VectorMask<Byte> allTrue = byteVec.maskAll(true);
final static ValueLayout.OfInt INT_UNALIGNED_BIG_ENDIAN = ValueLayout.JAVA_INT_UNALIGNED.withOrder(ByteOrder.BIG_ENDIAN);
public static void main(String[] args) throws Exception {
try (var arena = Arena.ofShared();
FileChannel fc = FileChannel.open(Path.of(FILE))) {
long fileSize = fc.size();
MemorySegment fileContent = fc.map(FileChannel.MapMode.READ_ONLY, 0, fileSize, arena);
ArrayList<Section> sections = splitFileIntoSections(fileSize, fileContent);
var loopBound = byteVec.loopBound(fileSize) - vecLen;
var result = sections.stream()
.parallel()
.map(s -> {
return parseSection(s.start, s.end, loopBound, fileContent);
});
var measurements = new TreeMap<String, ResultRow>();
result.forEachOrdered(m -> {
m.fillMerge(fileContent, measurements);
});
System.out.println(measurements);
}
}
private static PrivateHashMap parseSection(long start, long end, long loopBound, MemorySegment fileContent) {
var map = new PrivateHashMap();
for (long i = start; i < end;) {
long nameStart = i;
int simdSearchEnd = 0;
int nameLen = 0;
// Vectorized Search
if (i < loopBound) {
do {
var vec = byteVec.fromMemorySegment(fileContent, i, ByteOrder.BIG_ENDIAN);
var hasSemi = vec.eq(semiColon);
simdSearchEnd = hasSemi.firstTrue();
i += simdSearchEnd;
nameLen += simdSearchEnd;
} while (simdSearchEnd == vecLen && i < loopBound);
}
// Left-over search
while (loopBound <= i && fileContent.get(JAVA_BYTE, i) != ';') {
nameLen++;
i++;
}
i++; // Consume ;
// Copied from yemreinci. I mostly wanted to experiment the vector math, not with parsing =)
double val;
{
boolean negative = false;
if ((fileContent.get(JAVA_BYTE, i)) == '-') {
negative = true;
i++;
}
byte b;
double temp;
if ((b = fileContent.get(JAVA_BYTE, i + 1)) == '.') { // temperature is in either XX.X or X.X form
temp = (fileContent.get(JAVA_BYTE, i) - '0') + (fileContent.get(JAVA_BYTE, i + 2) - '0') / 10.0;
i += 3;
}
else {
temp = (fileContent.get(JAVA_BYTE, i) - '0') * 10 + (b - '0')
+ (fileContent.get(JAVA_BYTE, i + 3) - '0') / 10.0;
i += 4;
}
val = (negative ? -temp : temp);
}
i++; // Consume \n
map.add(fileContent, nameStart, nameLen, val);
}
return map;
}
private static ArrayList<Section> splitFileIntoSections(long fileSize, MemorySegment fileContent) {
var cpuCount = Runtime.getRuntime().availableProcessors();
var roughChunkSize = fileSize / cpuCount;
ArrayList<Section> sections = new ArrayList<>(cpuCount);
for (long sStart = 0; sStart < fileSize;) {
var endGuess = Math.min(sStart + roughChunkSize, fileSize);
for (; endGuess < fileSize && fileContent.get(JAVA_BYTE, endGuess) != '\n'; endGuess++) {
}
sections.add(new Section(sStart, endGuess));
sStart = endGuess + 1;
}
return sections;
}
private static class PrivateHashMap {
private static final int SIZE_SHIFT = 14;
public static final int SIZE = 1 << SIZE_SHIFT;
public static int MASK = 0xFFFFFFFF >>> (32 - SIZE_SHIFT);
public static long SHIFT_POS = 16;
public static long MASK_POS = 0xFFFFFFFFFFFF0000L;
public static long MASK_LEN = 0x000000000000FFFFL;
// Encoding:
// - Key: long
// - 48 bits index, 16 bits length
final long[] keys = new long[SIZE];
final Value[] values = new Value[SIZE];
private class Value {
public Value(double min, double max, double sum, long count) {
this.min = min;
this.max = max;
this.sum = sum;
this.count = count;
}
public double min;
public double max;
public double sum;
public long count;
}
// int debug_size = 0;
// int debug_reprobeMax = 0;
public PrivateHashMap() {
}
public void add(MemorySegment file, long pos, int len, double val) {
int hashCode = calculateHash(file, pos, len);
doAdd(file, hashCode, pos, len, val);
}
private static int calculateHash(MemorySegment file, long pos, int len) {
if (len > 4) {
return file.get(INT_UNALIGNED_BIG_ENDIAN, pos) + 31 * len;
}
else {
int hashCode = len;
int i = 0;
for (; i < len; i++) {
int v = file.get(JAVA_BYTE, pos + i);
hashCode = 31 * hashCode + v;
}
return hashCode;
}
}
private void doAdd(MemorySegment file, int hash, long pos, int len, double val) {
int slot = hash & MASK;
for (var probe = 0; probe < 20000; probe++) {
var iSl = ((slot + probe) & MASK);
var slotEntry = keys[iSl];
var emtpy = slotEntry == 0;
if (emtpy) {
long keyInfo = pos << SHIFT_POS | len;
keys[iSl] = keyInfo;
values[iSl] = new Value(val, val, val, 1);
// debug_size++;
return;
}
else if (isSameEntry(file, slotEntry, pos, len)) {
var vE = values[iSl];
vE.min = Math.min(vE.min, val);
vE.max = Math.max(vE.max, val);
vE.sum = vE.sum + val;
vE.count++;
return;
}
else {
// long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
// int keyLen = (int) (slotEntry & MASK_LEN);
// System.out.println("Colliding " + new String(file.asSlice(pos,len).toArray(ValueLayout.JAVA_BYTE)) +
// " with key" + new String(file.asSlice(keyPos,keyLen).toArray(ValueLayout.JAVA_BYTE)) +
// " hash " + hash + " slot " + slot + "+" + probe + " at " + iSl);
// debug_reprobeMax = Math.max(debug_reprobeMax, probe);
}
}
throw new IllegalStateException("More than 20000 reprobes");
// throw new IllegalStateException("More than 100 reprobes: At " + debug_size + "");
}
private boolean isSameEntry(MemorySegment file, long slotEntry, long pos, int len) {
long keyPos = (slotEntry & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (slotEntry & MASK_LEN);
var isSame = len == keyLen && isSame(file, keyPos, pos, len);
return isSame;
}
private static boolean isSame(MemorySegment file, long i1, long i2, int len) {
int i = 0;
var i1len = i1 + vecLen;
var i2len = i2 + vecLen;
if (len < vecLen && i1len <= file.byteSize() && i2len <= file.byteSize()) {
var v1 = byteVec.fromMemorySegment(file, i1, ByteOrder.nativeOrder());
var v2 = byteVec.fromMemorySegment(file, i2, ByteOrder.nativeOrder());
var isTrue = v1.compare(VectorOperators.EQ, v2, allTrue.indexInRange(0, len));
return isTrue.trueCount() == len;
}
while (8 < (len - i)) {
var v1 = file.get(JAVA_LONG_UNALIGNED, i1 + i);
var v2 = file.get(JAVA_LONG_UNALIGNED, i2 + i);
if (v1 != v2) {
return false;
}
i += 8;
}
while (i < len) {
var v1 = file.get(JAVA_BYTE, i1 + i);
var v2 = file.get(JAVA_BYTE, i2 + i);
if (v1 != v2) {
return false;
}
i++;
}
return true;
}
public void fillMerge(MemorySegment file, TreeMap<String, ResultRow> treeMap) {
for (int i = 0; i < keys.length; i++) {
var ji = i;
long keyE = keys[ji];
if (keyE != 0) {
long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
int keyLen = (int) (keyE & MASK_LEN);
byte[] keyBytes = new byte[keyLen];
MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
var key = new String(keyBytes);
var vE = values[ji];
var min = vE.min;
var max = vE.max;
var sum = vE.sum;
var count = vE.count;
treeMap.compute(key, (k, e) -> {
if (e == null) {
return new ResultRow(min, max, sum, count);
}
else {
return new ResultRow(Math.min(e.min, min), Math.max(e.max, max), e.sum + sum, e.count + count);
}
});
}
}
}
// public String debugPrint(MemorySegment file) {
// StringBuilder b = new StringBuilder();
// for (int i = 0; i < keyValues.length / 5; i++) {
// var ji = i * 5;
// long keyE = keyValues[ji];
// if (keyE != 0) {
// long keyPos = (keyE & MASK_POS) >> SHIFT_POS;
// int keyLen<SUF>
// byte[] keyBytes = new byte[keyLen];
// MemorySegment.copy(file, JAVA_BYTE, keyPos, keyBytes, 0, keyLen);
// var key = new String(keyBytes);
// var min = longBitsToDouble(keyValues[ji + 1]);
// var max = longBitsToDouble(keyValues[ji + 2]);
// var sum = longBitsToDouble(keyValues[ji + 3]);
// var count = keyValues[ji + 4];
// b.append("{").append(key).append("@").append(ji)
// .append(",").append(min)
// .append(",").append(max)
// .append(",").append(sum)
// .append(",").append(count).append("},");
// }
// }
// return b.toString();
// }
}
record Section(long start, long end) {
}
private static record ResultRow(double min, double max, double sum, long count) {
public String toString() {
return round(min) + "/" + round(((Math.round(sum * 10.0) / 10.0) / count)) + "/" + round(max);
}
private double round(double value) {
return Math.round(value * 10.0) / 10.0;
}
}
;
}
| False |
4,492 | 129008_21 | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
// System.out.println(time/(24*60*60*1000));
}
}
| thinkgem/jeesite | src/main/java/com/thinkgem/jeesite/common/utils/DateUtils.java | 2,060 | // long time = new Date().getTime()-parseDate("2012-11-19").getTime(); | line_comment | nl | /**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.common.utils;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;
/**
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
* @author ThinkGem
* @version 2014-4-15
*/
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
/**
* 得到当前日期字符串 格式(yyyy-MM-dd)
*/
public static String getDate() {
return getDate("yyyy-MM-dd");
}
/**
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String getDate(String pattern) {
return DateFormatUtils.format(new Date(), pattern);
}
/**
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
*/
public static String formatDate(Date date, Object... pattern) {
String formatDate = null;
if (pattern != null && pattern.length > 0) {
formatDate = DateFormatUtils.format(date, pattern[0].toString());
} else {
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
}
return formatDate;
}
/**
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
*/
public static String formatDateTime(Date date) {
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前时间字符串 格式(HH:mm:ss)
*/
public static String getTime() {
return formatDate(new Date(), "HH:mm:ss");
}
/**
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
*/
public static String getDateTime() {
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
}
/**
* 得到当前年份字符串 格式(yyyy)
*/
public static String getYear() {
return formatDate(new Date(), "yyyy");
}
/**
* 得到当前月份字符串 格式(MM)
*/
public static String getMonth() {
return formatDate(new Date(), "MM");
}
/**
* 得到当天字符串 格式(dd)
*/
public static String getDay() {
return formatDate(new Date(), "dd");
}
/**
* 得到当前星期字符串 格式(E)星期几
*/
public static String getWeek() {
return formatDate(new Date(), "E");
}
/**
* 日期型字符串转化为日期 格式
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
*/
public static Date parseDate(Object str) {
if (str == null){
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
/**
* 获取过去的天数
* @param date
* @return
*/
public static long pastDays(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(24*60*60*1000);
}
/**
* 获取过去的小时
* @param date
* @return
*/
public static long pastHour(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*60*1000);
}
/**
* 获取过去的分钟
* @param date
* @return
*/
public static long pastMinutes(Date date) {
long t = new Date().getTime()-date.getTime();
return t/(60*1000);
}
/**
* 转换为时间(天,时:分:秒.毫秒)
* @param timeMillis
* @return
*/
public static String formatDateTime(long timeMillis){
long day = timeMillis/(24*60*60*1000);
long hour = (timeMillis/(60*60*1000)-day*24);
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
}
/**
* 获取两个日期之间的天数
*
* @param before
* @param after
* @return
*/
public static double getDistanceOfTwoDate(Date before, Date after) {
long beforeTime = before.getTime();
long afterTime = after.getTime();
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
}
/**
* 获取过去第几天的日期
*
* @param past
* @return
*/
public static String getPastDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* 获取未来 第 past 天的日期
* @param past
* @return
*/
public static String getFetureDate(int past) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
Date today = calendar.getTime();
String result = formatDate(today, "yyyyMMdd") ;
return result;
}
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// System.out.println(formatDate(parseDate("2010/3/6")));
// System.out.println(getDate("yyyy年MM月dd日 E"));
// long time<SUF>
// System.out.println(time/(24*60*60*1000));
}
}
| False |
3,271 | 71320_87 | package javaBot;_x000D_
_x000D_
//TODO: Check if current robot has a sound sensor_x000D_
//TODO: If sound sensor, show and process graphics window_x000D_
//TODO: Check if robot has a mouse sensor_x000D_
//TODO: If mouse sensor, display image and coordinates_x000D_
//TODO: If sound sensor, check if real or simulated sensor_x000D_
//TODO: Generate sound patterns from simulated sensor_x000D_
//TODO: Simulated sound sensor must read in patterns from file and display_x000D_
//TODO: If ultrasonic sensor, display only first graph_x000D_
//TODO: Define method to select simulated or real sensor_x000D_
//TODO: Include Sampler and FFT in UVM robot_x000D_
//TODO: Use samples and select files in simulator_x000D_
//TODO: If graph is closed, stop collecting data_x000D_
//TODO: Graph display only on request_x000D_
//TODO: Include new sensors in system_x000D_
//TODO: Bij wisseling van agent treden er problemen op_x000D_
//TODO: Implement selection of robot type_x000D_
_x000D_
/**_x000D_
* Ver 0.0 - 11-08-2004 Ver 0.1 - 03-07-2004 - Implemented Servo values_x000D_
* Included DoCommand webservice interfaces (preliminary)_x000D_
*/_x000D_
import java.awt.BorderLayout;_x000D_
import java.awt.Color;_x000D_
import java.awt.FlowLayout;_x000D_
import java.awt.event.ActionEvent;_x000D_
import java.awt.event.ActionListener;_x000D_
import java.awt.event.WindowAdapter;_x000D_
import java.awt.event.WindowEvent;_x000D_
import java.io.BufferedReader;_x000D_
import java.io.BufferedWriter;_x000D_
import java.io.File;_x000D_
import java.io.FileReader;_x000D_
import java.io.FileWriter;_x000D_
_x000D_
import javaBot.sensors.SensorServer;_x000D_
_x000D_
import javax.swing.ImageIcon;_x000D_
import javax.swing.JButton;_x000D_
import javax.swing.JCheckBox;_x000D_
import javax.swing.JFileChooser;_x000D_
import javax.swing.JFrame;_x000D_
import javax.swing.JMenu;_x000D_
import javax.swing.JMenuBar;_x000D_
import javax.swing.JMenuItem;_x000D_
import javax.swing.JOptionPane;_x000D_
import javax.swing.JPanel;_x000D_
import javax.swing.Timer;_x000D_
import javax.swing.WindowConstants;_x000D_
import javax.swing.filechooser.FileFilter;_x000D_
_x000D_
/**_x000D_
* Shows various info items about the status of a robot and allows for_x000D_
* interaction with the robot._x000D_
*/_x000D_
public class GraphGUI implements IGUI_x000D_
{_x000D_
private static final int SAMPLESIZE = 128;_x000D_
_x000D_
//Window title_x000D_
private String WINDOW_TITLE = "RobotGUI";_x000D_
_x000D_
//standard visibility of window_x000D_
private static final boolean GRAPH_DEFAULT_VISIBLE = true;_x000D_
_x000D_
// Actual window_x000D_
private SensorServer theServer;_x000D_
private JFrame graph;_x000D_
_x000D_
// What robot this GUI belong to_x000D_
private Robot robot;_x000D_
_x000D_
// Timer for timed value updates_x000D_
private Timer t;_x000D_
_x000D_
// Five colored leds_x000D_
private JButton[] recStatus = new JButton[5];_x000D_
private String[] chars = {"A", "E", "I", "O", "U"};_x000D_
_x000D_
//Graphs on window_x000D_
private GraphPlot graphOrg = new GraphPlot();_x000D_
private GraphPlot graphFFT = new GraphPlot();_x000D_
_x000D_
// Set sensor simulated or not_x000D_
private JCheckBox sensorSimul = new JCheckBox(_x000D_
"Simulate external sensor", false);_x000D_
_x000D_
//Items voor in het menu_x000D_
private JMenuItem bestand_open = new JMenuItem("Open meting");_x000D_
private JMenuItem bestand_save = new JMenuItem("Save meting");_x000D_
_x000D_
//Knoppen om meting te starten en stoppen_x000D_
private ImageIcon iconStart = new ImageIcon(_x000D_
"./src/javaBot/resources/play.gif");_x000D_
private ImageIcon iconStop = new ImageIcon(_x000D_
"./src/javaBot/resources/pause.gif");_x000D_
private JButton meting_running = new JButton(iconStart);_x000D_
_x000D_
//Boolean die aangeeft of grafieken aan het meten zijn_x000D_
boolean measuring = false;_x000D_
private RobotGUIActionListener robotGUIActionlistener = new RobotGUIActionListener();_x000D_
private RobotGUI robotGUI = null;_x000D_
_x000D_
// Analyser_x000D_
_x000D_
private SpectrumAnalyser analyser = new SpectrumAnalyser();_x000D_
_x000D_
/**_x000D_
* Default constructor_x000D_
*_x000D_
* @param robot The robot to link to this GUI_x000D_
* @param robotGUI Reference to the robotGUI_x000D_
*/_x000D_
public GraphGUI(Robot robot, RobotGUI robotGUI)_x000D_
{_x000D_
super();_x000D_
this.robot = robot;_x000D_
WINDOW_TITLE += (" for " + robot.name);_x000D_
_x000D_
this.robotGUI = robotGUI;_x000D_
_x000D_
//Create and set up window for graphs_x000D_
graph = new JFrame("Audiograph");_x000D_
_x000D_
graph.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);_x000D_
_x000D_
graph.addWindowListener(new WindowAdapter()_x000D_
{_x000D_
public void windowClosing(WindowEvent e)_x000D_
{_x000D_
setVisible(false);_x000D_
}_x000D_
});_x000D_
_x000D_
init();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Created on 20-02-2006_x000D_
* Copyright: (c) 2006_x000D_
* Company: Dancing Bear Software_x000D_
*_x000D_
* @version $Revision$_x000D_
* last changed 20-02-2006_x000D_
*_x000D_
* ActionListener from the GraphGUI. Listens to the generated events_x000D_
* and handles accordingly._x000D_
*/_x000D_
private class RobotGUIActionListener implements ActionListener_x000D_
{_x000D_
/**_x000D_
* actionPerformed method_x000D_
*_x000D_
* @param arg0 ActionEvent that generated by the window_x000D_
*/_x000D_
public void actionPerformed(ActionEvent arg0)_x000D_
{_x000D_
//if RobotGUI is closed, then the grapGUI also needs to be closed_x000D_
if( !robotGUI.isVisible() && !robotGUI.isVisibleInLeftFrame() ) graph.setVisible(false);_x000D_
_x000D_
if (arg0.getSource() == bestand_open)_x000D_
{_x000D_
openMeting();_x000D_
_x000D_
return;_x000D_
}_x000D_
else if (arg0.getSource() == bestand_save)_x000D_
{_x000D_
saveMeting();_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
if (arg0.getSource() == meting_running)_x000D_
{_x000D_
if (measuring)_x000D_
{_x000D_
stopMeasuring();_x000D_
}_x000D_
else_x000D_
{_x000D_
boolean isSensorSimulated = getSensorSimulated();_x000D_
theServer = new SensorServer(isSensorSimulated); // Start server_x000D_
measuring = true;_x000D_
meting_running.setIcon(iconStop);_x000D_
}_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
if (arg0.getActionCommand() == null)_x000D_
{_x000D_
// Refresh timer_x000D_
updateReadings();_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
private void stopMeasuring()_x000D_
{_x000D_
meting_running.setIcon(iconStart);_x000D_
measuring = false;_x000D_
theServer = null;_x000D_
} _x000D_
_x000D_
/* Functie die een meting opent uit een ini-bestand_x000D_
* afkomstig van de harde schijf_x000D_
*/_x000D_
private void openMeting()_x000D_
{_x000D_
//Venster om een bestand te selecteren om te openen_x000D_
JFileChooser fc = new JFileChooser();_x000D_
_x000D_
//Het filter dat ervoor zorgt dat je alleen _x000D_
//ini-files kan selecteren_x000D_
myFileFilter filter = new myFileFilter();_x000D_
_x000D_
//String waarin net gelezen data van de file terechtkomt_x000D_
String line;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int index;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int eindindex;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int metingnr = 0;_x000D_
_x000D_
//Variabelen die bijhoudt heoveel samples dit bestand heeft_x000D_
//Momenteel ondersteunt het echter alleen files met 128 _x000D_
//samples_x000D_
int samples;_x000D_
_x000D_
//Arrays waarin de data wordt opgeslagen_x000D_
//Deze is ter grootte van het aantal samples_x000D_
byte[] meting = new byte[SAMPLESIZE];_x000D_
byte[] metingFFT = new byte[SAMPLESIZE];_x000D_
_x000D_
//Stel de filefilter in op het dialoogvenster _x000D_
//waar de file wordt gekozen_x000D_
fc.setFileFilter(filter);_x000D_
_x000D_
//Haal de geselecteerde file op_x000D_
File selFile = fc.getSelectedFile();_x000D_
_x000D_
try_x000D_
{_x000D_
//Het opzetten van de leesfuncties_x000D_
FileReader fr = new FileReader(selFile);_x000D_
BufferedReader br = new BufferedReader(fr);_x000D_
_x000D_
//Het lezen van de eerste regel van het bestand_x000D_
line = br.readLine();_x000D_
_x000D_
//Eerste regel is een voorgedefineerde header_x000D_
if (!line.equals("[Meting]"))_x000D_
{_x000D_
//Komt deze niet overeen is de file ongeldig_x000D_
JOptionPane.showMessageDialog(null, "Invalid file formaat", "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
_x000D_
//Tweede regel zijn het aantal samplesin het bestand_x000D_
line = br.readLine();_x000D_
_x000D_
//Zoek het '=' teken op. Hierachter staat de waarde van_x000D_
//Het aantal samples_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Zet deze string om in een getal_x000D_
samples = Integer.parseInt(line.substring(index));_x000D_
_x000D_
if (samples != 128)_x000D_
{_x000D_
//Het aantal samples moet momenteel 128 zijn_x000D_
JOptionPane.showMessageDialog(null, "Samplesize doesn't match 128",_x000D_
"Open file failed", JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
_x000D_
//Derde regel zijn de samples van het originele data_x000D_
line = br.readLine();_x000D_
_x000D_
//Zoek eerst het '=' teken_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Hierna begint de data _x000D_
for (eindindex = index; eindindex < line.length(); eindindex++)_x000D_
{_x000D_
//Bij de komma is het getal afgelopen_x000D_
if (line.charAt(eindindex) == ',')_x000D_
{_x000D_
//En kan je de data op zijn plek in de array _x000D_
//zetten_x000D_
meting[metingnr] = Byte.parseByte(line.substring(index, eindindex));_x000D_
index = eindindex + 1;_x000D_
metingnr++;_x000D_
}_x000D_
}_x000D_
_x000D_
//Hierna de data van de FFT. Deze leest op dezelfde wijze _x000D_
//als hiervoor_x000D_
line = br.readLine();_x000D_
metingnr = 0;_x000D_
_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
for (eindindex = index; eindindex < line.length(); eindindex++)_x000D_
{_x000D_
if (line.charAt(eindindex) == ',')_x000D_
{_x000D_
metingFFT[metingnr] = Byte.parseByte(line.substring(index, eindindex));_x000D_
index = eindindex + 1;_x000D_
metingnr++;_x000D_
}_x000D_
}_x000D_
}_x000D_
catch (Exception e)_x000D_
{_x000D_
//Bij een fout moet de procedure worden afgebroken_x000D_
JOptionPane.showMessageDialog(null, e.getMessage(), "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
//Stel de data in op de grafieken_x000D_
graphOrg.setPlotValues(meting);_x000D_
graphFFT.setPlotValues(metingFFT);_x000D_
}_x000D_
_x000D_
/* Functie die de hidige meting opslaat in een ini-file */_x000D_
private void saveMeting()_x000D_
{_x000D_
//Venster om een bestand te selecteren om te openen_x000D_
JFileChooser fc = new JFileChooser();_x000D_
_x000D_
//Het filter dat ervoor zorgt dat je alleen _x000D_
//ini-files kan selecteren_x000D_
myFileFilter filter = new myFileFilter();_x000D_
_x000D_
//Stel filter in op het venster_x000D_
fc.setFileFilter(filter);_x000D_
_x000D_
//Haal de geselecteerde file op_x000D_
File selFile = fc.getSelectedFile();_x000D_
_x000D_
try_x000D_
{_x000D_
//Het opzetten van de leesfuncties_x000D_
FileWriter fr = new FileWriter(selFile);_x000D_
BufferedWriter br = new BufferedWriter(fr);_x000D_
_x000D_
//Schrijf eerste voorgedefinieerde header_x000D_
br.write("[Meting]");_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf het aantal samples, momenteel standaard 128_x000D_
br.write("Samples=" + 128);_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf originele data_x000D_
br.write("Org=" + graphOrg.getData(0));_x000D_
_x000D_
for (int i = 0; i < 128; i++)_x000D_
{_x000D_
br.write("," + graphOrg.getData(i));_x000D_
}_x000D_
_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf FFT data_x000D_
br.write("FFT=" + graphFFT.getData(0));_x000D_
_x000D_
for (int i = 0; i < 128; i++)_x000D_
{_x000D_
br.write("," + graphFFT.getData(i));_x000D_
}_x000D_
_x000D_
br.newLine();_x000D_
_x000D_
//Sluit File_x000D_
br.close();_x000D_
}_x000D_
catch (Exception e)_x000D_
{_x000D_
//Bij storing procedure afbreken_x000D_
JOptionPane.showMessageDialog(null, e.getMessage(), "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Start the GUI_x000D_
*/_x000D_
public void init()_x000D_
{_x000D_
Debug.printInfo("Starting RobotGUI for " + robot.name);_x000D_
_x000D_
//Make panel for our graphs_x000D_
JPanel Graphs = new JPanel();_x000D_
_x000D_
//Make panel for our detectors_x000D_
JPanel Detectors = new JPanel();_x000D_
_x000D_
//Set up graph panel_x000D_
Graphs.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
Graphs.setLayout(new java.awt.GridLayout(1, 2));_x000D_
_x000D_
// Initialize grahps to show_x000D_
_x000D_
graphOrg.setPlotStyle(GraphPlot.SIGNAL);_x000D_
graphOrg.setTracePlot(true);_x000D_
_x000D_
graphFFT.setPlotStyle(GraphPlot.SPECTRUM);_x000D_
graphFFT.setTracePlot(false);_x000D_
_x000D_
//And add Graphs onto it_x000D_
Graphs.add(graphOrg);_x000D_
Graphs.add(graphFFT);_x000D_
Graphs.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
_x000D_
Detectors.setLayout(new java.awt.GridLayout(1, 5));_x000D_
_x000D_
//Maak indicatoren_x000D_
for (int i = 0; i < recStatus.length; i++)_x000D_
{_x000D_
recStatus[i] = new JButton(chars[i]);_x000D_
Detectors.add(recStatus[i]);_x000D_
}_x000D_
_x000D_
//Set up contentPane_x000D_
graph.getContentPane().setLayout(new BorderLayout());_x000D_
graph.getContentPane().add(Graphs, BorderLayout.CENTER);_x000D_
graph.getContentPane().add(Detectors, BorderLayout.SOUTH);_x000D_
_x000D_
JPanel vulling = new JPanel();_x000D_
graph.getContentPane().add(vulling, BorderLayout.NORTH);_x000D_
vulling.setLayout(new FlowLayout(FlowLayout.LEFT));_x000D_
vulling.add(meting_running);_x000D_
meting_running.setIcon(iconStart);_x000D_
_x000D_
//Make menu_x000D_
JMenuBar menu = new JMenuBar();_x000D_
graph.setJMenuBar(menu);_x000D_
_x000D_
JMenu bestand = new JMenu("File");_x000D_
menu.add(bestand);_x000D_
bestand.add(bestand_open);_x000D_
bestand_open.addActionListener(robotGUIActionlistener);_x000D_
bestand.add(bestand_save);_x000D_
bestand_save.addActionListener(robotGUIActionlistener);_x000D_
meting_running.addActionListener(robotGUIActionlistener);_x000D_
_x000D_
// Add checkbox for simulated sensor_x000D_
graph.getContentPane().add(sensorSimul, BorderLayout.SOUTH);_x000D_
// Listen to checkbox_x000D_
sensorSimul.addActionListener(robotGUIActionlistener);_x000D_
_x000D_
//And the SIZE_x000D_
graph.setSize(900, 300);_x000D_
graph.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
_x000D_
// Initialize timer_x000D_
t = new Timer(50, robotGUIActionlistener);_x000D_
t.start();_x000D_
}_x000D_
_x000D_
// Update all the readings_x000D_
private void updateReadings()_x000D_
{_x000D_
// Alleen als je aan het meten bent_x000D_
if (measuring)_x000D_
{_x000D_
updateGraphData();_x000D_
//updateSpraak();_x000D_
}_x000D_
}_x000D_
_x000D_
//Functie die grafieken up to date houdt_x000D_
private void updateGraphData()_x000D_
{_x000D_
byte[] result = new byte[SAMPLESIZE];_x000D_
_x000D_
byte[] originalData;_x000D_
byte[] convertedData;_x000D_
// Needed to resolve signed/unsigned issue_x000D_
originalData = theServer.getSensorData(1);_x000D_
_x000D_
//originalData = new byte[64];_x000D_
// Convert the data_x000D_
convertedData = FastFourierTransform.convertData(originalData);_x000D_
//convertedData = originalData;_x000D_
// Kopieer in nieuwe array_x000D_
for (int i = 0; i < convertedData.length && i < SAMPLESIZE; i++)_x000D_
{_x000D_
result[i] = convertedData[i];_x000D_
}_x000D_
// De rest wordt 0 gemaakt._x000D_
for (int i = originalData.length; i < SAMPLESIZE; i++)_x000D_
{_x000D_
result[i] = 0;_x000D_
}_x000D_
_x000D_
// Set de data in de grafiek_x000D_
graphOrg.setPlotValues(result);_x000D_
_x000D_
FastFourierTransform fft = new FastFourierTransform();_x000D_
_x000D_
_x000D_
/*_x000D_
* Change:_x000D_
* We not read the result into a special variable, so that it_x000D_
* can be passed along to our own module for speech recognition._x000D_
* After that, it is plotted to the screen as normal._x000D_
*/_x000D_
byte[] plotValues = fft.fftMag(result);_x000D_
_x000D_
analyser.update(plotValues);_x000D_
_x000D_
graphFFT.setPlotValues(plotValues);_x000D_
}_x000D_
_x000D_
//Functie die leds aanzet indien er een letter is herkend_x000D_
private void updateSpraak()_x000D_
{_x000D_
//Deze methode is overgenomen van het CVI project en_x000D_
//licht aangepast, commentaar zie aldaar_x000D_
int[] piekenDicht = {1, 1};_x000D_
int[] piekenVer = {45, 45};_x000D_
final double STORING = .5;_x000D_
final double STORING_VER = 0.35;_x000D_
final int WILLEKEUR = 5;_x000D_
_x000D_
recStatus[0].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[1].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[2].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[3].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[4].setBackground(Color.LIGHT_GRAY);_x000D_
_x000D_
byte[] speechData = graphFFT.getData();_x000D_
_x000D_
for (int i = 1; i < 22; i++)_x000D_
{_x000D_
if (speechData[i] > speechData[piekenDicht[0]])_x000D_
{_x000D_
piekenDicht[0] = i;_x000D_
}_x000D_
else if (speechData[i] > speechData[piekenDicht[1]])_x000D_
{_x000D_
piekenDicht[1] = i;_x000D_
}_x000D_
}_x000D_
_x000D_
for (int i = 23; i < 45; i++)_x000D_
{_x000D_
if (speechData[i] > speechData[piekenVer[0]])_x000D_
{_x000D_
piekenVer[0] = i;_x000D_
}_x000D_
else if (speechData[i] > speechData[piekenVer[1]])_x000D_
{_x000D_
piekenVer[1] = i;_x000D_
}_x000D_
}_x000D_
_x000D_
if (piekenVer[0] < STORING)_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (piekenDicht[0] < STORING_VER)_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (((piekenDicht[0] - piekenDicht[1]) > WILLEKEUR) && (piekenDicht[1] > STORING))_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (((piekenVer[0] - piekenVer[1]) > WILLEKEUR) && (piekenVer[1] > STORING_VER))_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if ((piekenDicht[0] >= 10) && (piekenDicht[0] <= 15)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[0].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 5) && (piekenDicht[0] <= 8)_x000D_
&& (speechData[piekenDicht[0]] > STORING) && (piekenVer[0] >= 25)_x000D_
&& (piekenVer[0] <= 35) && (speechData[piekenVer[0]] > STORING_VER))_x000D_
{_x000D_
recStatus[1].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 2) && (piekenDicht[0] <= 4)_x000D_
&& (speechData[piekenDicht[0]] > STORING) && (piekenVer[0] >= 30)_x000D_
&& (piekenVer[0] <= 45) && (speechData[piekenVer[0]] > STORING_VER))_x000D_
{_x000D_
recStatus[2].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 2) && (piekenDicht[0] <= 4)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[4].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 5) && (piekenDicht[0] <= 8)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[3].setBackground(Color.GREEN);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Sets the visibility of this GUI_x000D_
*_x000D_
* @param visible boolean if visible (true) or not (false)_x000D_
*/_x000D_
public void setVisible(boolean visible)_x000D_
{_x000D_
graph.setVisible(visible);_x000D_
if(!visible) _x000D_
{_x000D_
stopMeasuring();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Destroys this frame_x000D_
*/_x000D_
public void destroy()_x000D_
{_x000D_
graph.dispose();_x000D_
t.stop();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Get the status of the "sensor simulated" checkbox in the robotGUI_x000D_
*_x000D_
* @return boolean - true if the checkbox is set (sensorvalues will be generated by simulator)_x000D_
* @see GraphGUI#robotGUIActionlistener_x000D_
*/_x000D_
public boolean getSensorSimulated()_x000D_
{_x000D_
return sensorSimul.isSelected();_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/**_x000D_
* Created on 20-02-2006_x000D_
* Copyright: (c) 2006_x000D_
* Company: Dancing Bear Software_x000D_
*_x000D_
* @version $Revision$_x000D_
* last changed 20-02-2006_x000D_
*_x000D_
* TODO CLASS: DOCUMENT ME! _x000D_
*/_x000D_
_x000D_
class myFileFilter extends FileFilter_x000D_
{_x000D_
/**_x000D_
* TODO METHOD: DOCUMENT ME!_x000D_
*_x000D_
* @param f TODO PARAM: param description_x000D_
*_x000D_
* @return $returnType$ TODO RETURN: return description_x000D_
*/_x000D_
public boolean accept(File f)_x000D_
{_x000D_
if (f.isDirectory())_x000D_
{_x000D_
return true;_x000D_
}_x000D_
_x000D_
String filename = f.getName();_x000D_
_x000D_
return filename.endsWith(".ini");_x000D_
}_x000D_
_x000D_
/**_x000D_
* TODO METHOD: DOCUMENT ME!_x000D_
*_x000D_
* @return String returns description_x000D_
*/_x000D_
public String getDescription()_x000D_
{_x000D_
return "Meting bestanden";_x000D_
}_x000D_
}_x000D_
| joristork/robots | jobotsim26/JobotSim26/src/javaBot/GraphGUI.java | 6,806 | // Alleen als je aan het meten bent_x000D_ | line_comment | nl | package javaBot;_x000D_
_x000D_
//TODO: Check if current robot has a sound sensor_x000D_
//TODO: If sound sensor, show and process graphics window_x000D_
//TODO: Check if robot has a mouse sensor_x000D_
//TODO: If mouse sensor, display image and coordinates_x000D_
//TODO: If sound sensor, check if real or simulated sensor_x000D_
//TODO: Generate sound patterns from simulated sensor_x000D_
//TODO: Simulated sound sensor must read in patterns from file and display_x000D_
//TODO: If ultrasonic sensor, display only first graph_x000D_
//TODO: Define method to select simulated or real sensor_x000D_
//TODO: Include Sampler and FFT in UVM robot_x000D_
//TODO: Use samples and select files in simulator_x000D_
//TODO: If graph is closed, stop collecting data_x000D_
//TODO: Graph display only on request_x000D_
//TODO: Include new sensors in system_x000D_
//TODO: Bij wisseling van agent treden er problemen op_x000D_
//TODO: Implement selection of robot type_x000D_
_x000D_
/**_x000D_
* Ver 0.0 - 11-08-2004 Ver 0.1 - 03-07-2004 - Implemented Servo values_x000D_
* Included DoCommand webservice interfaces (preliminary)_x000D_
*/_x000D_
import java.awt.BorderLayout;_x000D_
import java.awt.Color;_x000D_
import java.awt.FlowLayout;_x000D_
import java.awt.event.ActionEvent;_x000D_
import java.awt.event.ActionListener;_x000D_
import java.awt.event.WindowAdapter;_x000D_
import java.awt.event.WindowEvent;_x000D_
import java.io.BufferedReader;_x000D_
import java.io.BufferedWriter;_x000D_
import java.io.File;_x000D_
import java.io.FileReader;_x000D_
import java.io.FileWriter;_x000D_
_x000D_
import javaBot.sensors.SensorServer;_x000D_
_x000D_
import javax.swing.ImageIcon;_x000D_
import javax.swing.JButton;_x000D_
import javax.swing.JCheckBox;_x000D_
import javax.swing.JFileChooser;_x000D_
import javax.swing.JFrame;_x000D_
import javax.swing.JMenu;_x000D_
import javax.swing.JMenuBar;_x000D_
import javax.swing.JMenuItem;_x000D_
import javax.swing.JOptionPane;_x000D_
import javax.swing.JPanel;_x000D_
import javax.swing.Timer;_x000D_
import javax.swing.WindowConstants;_x000D_
import javax.swing.filechooser.FileFilter;_x000D_
_x000D_
/**_x000D_
* Shows various info items about the status of a robot and allows for_x000D_
* interaction with the robot._x000D_
*/_x000D_
public class GraphGUI implements IGUI_x000D_
{_x000D_
private static final int SAMPLESIZE = 128;_x000D_
_x000D_
//Window title_x000D_
private String WINDOW_TITLE = "RobotGUI";_x000D_
_x000D_
//standard visibility of window_x000D_
private static final boolean GRAPH_DEFAULT_VISIBLE = true;_x000D_
_x000D_
// Actual window_x000D_
private SensorServer theServer;_x000D_
private JFrame graph;_x000D_
_x000D_
// What robot this GUI belong to_x000D_
private Robot robot;_x000D_
_x000D_
// Timer for timed value updates_x000D_
private Timer t;_x000D_
_x000D_
// Five colored leds_x000D_
private JButton[] recStatus = new JButton[5];_x000D_
private String[] chars = {"A", "E", "I", "O", "U"};_x000D_
_x000D_
//Graphs on window_x000D_
private GraphPlot graphOrg = new GraphPlot();_x000D_
private GraphPlot graphFFT = new GraphPlot();_x000D_
_x000D_
// Set sensor simulated or not_x000D_
private JCheckBox sensorSimul = new JCheckBox(_x000D_
"Simulate external sensor", false);_x000D_
_x000D_
//Items voor in het menu_x000D_
private JMenuItem bestand_open = new JMenuItem("Open meting");_x000D_
private JMenuItem bestand_save = new JMenuItem("Save meting");_x000D_
_x000D_
//Knoppen om meting te starten en stoppen_x000D_
private ImageIcon iconStart = new ImageIcon(_x000D_
"./src/javaBot/resources/play.gif");_x000D_
private ImageIcon iconStop = new ImageIcon(_x000D_
"./src/javaBot/resources/pause.gif");_x000D_
private JButton meting_running = new JButton(iconStart);_x000D_
_x000D_
//Boolean die aangeeft of grafieken aan het meten zijn_x000D_
boolean measuring = false;_x000D_
private RobotGUIActionListener robotGUIActionlistener = new RobotGUIActionListener();_x000D_
private RobotGUI robotGUI = null;_x000D_
_x000D_
// Analyser_x000D_
_x000D_
private SpectrumAnalyser analyser = new SpectrumAnalyser();_x000D_
_x000D_
/**_x000D_
* Default constructor_x000D_
*_x000D_
* @param robot The robot to link to this GUI_x000D_
* @param robotGUI Reference to the robotGUI_x000D_
*/_x000D_
public GraphGUI(Robot robot, RobotGUI robotGUI)_x000D_
{_x000D_
super();_x000D_
this.robot = robot;_x000D_
WINDOW_TITLE += (" for " + robot.name);_x000D_
_x000D_
this.robotGUI = robotGUI;_x000D_
_x000D_
//Create and set up window for graphs_x000D_
graph = new JFrame("Audiograph");_x000D_
_x000D_
graph.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);_x000D_
_x000D_
graph.addWindowListener(new WindowAdapter()_x000D_
{_x000D_
public void windowClosing(WindowEvent e)_x000D_
{_x000D_
setVisible(false);_x000D_
}_x000D_
});_x000D_
_x000D_
init();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Created on 20-02-2006_x000D_
* Copyright: (c) 2006_x000D_
* Company: Dancing Bear Software_x000D_
*_x000D_
* @version $Revision$_x000D_
* last changed 20-02-2006_x000D_
*_x000D_
* ActionListener from the GraphGUI. Listens to the generated events_x000D_
* and handles accordingly._x000D_
*/_x000D_
private class RobotGUIActionListener implements ActionListener_x000D_
{_x000D_
/**_x000D_
* actionPerformed method_x000D_
*_x000D_
* @param arg0 ActionEvent that generated by the window_x000D_
*/_x000D_
public void actionPerformed(ActionEvent arg0)_x000D_
{_x000D_
//if RobotGUI is closed, then the grapGUI also needs to be closed_x000D_
if( !robotGUI.isVisible() && !robotGUI.isVisibleInLeftFrame() ) graph.setVisible(false);_x000D_
_x000D_
if (arg0.getSource() == bestand_open)_x000D_
{_x000D_
openMeting();_x000D_
_x000D_
return;_x000D_
}_x000D_
else if (arg0.getSource() == bestand_save)_x000D_
{_x000D_
saveMeting();_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
if (arg0.getSource() == meting_running)_x000D_
{_x000D_
if (measuring)_x000D_
{_x000D_
stopMeasuring();_x000D_
}_x000D_
else_x000D_
{_x000D_
boolean isSensorSimulated = getSensorSimulated();_x000D_
theServer = new SensorServer(isSensorSimulated); // Start server_x000D_
measuring = true;_x000D_
meting_running.setIcon(iconStop);_x000D_
}_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
if (arg0.getActionCommand() == null)_x000D_
{_x000D_
// Refresh timer_x000D_
updateReadings();_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
private void stopMeasuring()_x000D_
{_x000D_
meting_running.setIcon(iconStart);_x000D_
measuring = false;_x000D_
theServer = null;_x000D_
} _x000D_
_x000D_
/* Functie die een meting opent uit een ini-bestand_x000D_
* afkomstig van de harde schijf_x000D_
*/_x000D_
private void openMeting()_x000D_
{_x000D_
//Venster om een bestand te selecteren om te openen_x000D_
JFileChooser fc = new JFileChooser();_x000D_
_x000D_
//Het filter dat ervoor zorgt dat je alleen _x000D_
//ini-files kan selecteren_x000D_
myFileFilter filter = new myFileFilter();_x000D_
_x000D_
//String waarin net gelezen data van de file terechtkomt_x000D_
String line;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int index;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int eindindex;_x000D_
_x000D_
//Variabelen die huidige indexen in de file bijhouden_x000D_
int metingnr = 0;_x000D_
_x000D_
//Variabelen die bijhoudt heoveel samples dit bestand heeft_x000D_
//Momenteel ondersteunt het echter alleen files met 128 _x000D_
//samples_x000D_
int samples;_x000D_
_x000D_
//Arrays waarin de data wordt opgeslagen_x000D_
//Deze is ter grootte van het aantal samples_x000D_
byte[] meting = new byte[SAMPLESIZE];_x000D_
byte[] metingFFT = new byte[SAMPLESIZE];_x000D_
_x000D_
//Stel de filefilter in op het dialoogvenster _x000D_
//waar de file wordt gekozen_x000D_
fc.setFileFilter(filter);_x000D_
_x000D_
//Haal de geselecteerde file op_x000D_
File selFile = fc.getSelectedFile();_x000D_
_x000D_
try_x000D_
{_x000D_
//Het opzetten van de leesfuncties_x000D_
FileReader fr = new FileReader(selFile);_x000D_
BufferedReader br = new BufferedReader(fr);_x000D_
_x000D_
//Het lezen van de eerste regel van het bestand_x000D_
line = br.readLine();_x000D_
_x000D_
//Eerste regel is een voorgedefineerde header_x000D_
if (!line.equals("[Meting]"))_x000D_
{_x000D_
//Komt deze niet overeen is de file ongeldig_x000D_
JOptionPane.showMessageDialog(null, "Invalid file formaat", "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
_x000D_
//Tweede regel zijn het aantal samplesin het bestand_x000D_
line = br.readLine();_x000D_
_x000D_
//Zoek het '=' teken op. Hierachter staat de waarde van_x000D_
//Het aantal samples_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Zet deze string om in een getal_x000D_
samples = Integer.parseInt(line.substring(index));_x000D_
_x000D_
if (samples != 128)_x000D_
{_x000D_
//Het aantal samples moet momenteel 128 zijn_x000D_
JOptionPane.showMessageDialog(null, "Samplesize doesn't match 128",_x000D_
"Open file failed", JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
_x000D_
//Derde regel zijn de samples van het originele data_x000D_
line = br.readLine();_x000D_
_x000D_
//Zoek eerst het '=' teken_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
//Hierna begint de data _x000D_
for (eindindex = index; eindindex < line.length(); eindindex++)_x000D_
{_x000D_
//Bij de komma is het getal afgelopen_x000D_
if (line.charAt(eindindex) == ',')_x000D_
{_x000D_
//En kan je de data op zijn plek in de array _x000D_
//zetten_x000D_
meting[metingnr] = Byte.parseByte(line.substring(index, eindindex));_x000D_
index = eindindex + 1;_x000D_
metingnr++;_x000D_
}_x000D_
}_x000D_
_x000D_
//Hierna de data van de FFT. Deze leest op dezelfde wijze _x000D_
//als hiervoor_x000D_
line = br.readLine();_x000D_
metingnr = 0;_x000D_
_x000D_
for (index = 0; index < line.length(); index++)_x000D_
{_x000D_
if (line.charAt(index) == '=')_x000D_
{_x000D_
index++;_x000D_
_x000D_
break;_x000D_
}_x000D_
}_x000D_
_x000D_
for (eindindex = index; eindindex < line.length(); eindindex++)_x000D_
{_x000D_
if (line.charAt(eindindex) == ',')_x000D_
{_x000D_
metingFFT[metingnr] = Byte.parseByte(line.substring(index, eindindex));_x000D_
index = eindindex + 1;_x000D_
metingnr++;_x000D_
}_x000D_
}_x000D_
}_x000D_
catch (Exception e)_x000D_
{_x000D_
//Bij een fout moet de procedure worden afgebroken_x000D_
JOptionPane.showMessageDialog(null, e.getMessage(), "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
_x000D_
return;_x000D_
}_x000D_
_x000D_
//Stel de data in op de grafieken_x000D_
graphOrg.setPlotValues(meting);_x000D_
graphFFT.setPlotValues(metingFFT);_x000D_
}_x000D_
_x000D_
/* Functie die de hidige meting opslaat in een ini-file */_x000D_
private void saveMeting()_x000D_
{_x000D_
//Venster om een bestand te selecteren om te openen_x000D_
JFileChooser fc = new JFileChooser();_x000D_
_x000D_
//Het filter dat ervoor zorgt dat je alleen _x000D_
//ini-files kan selecteren_x000D_
myFileFilter filter = new myFileFilter();_x000D_
_x000D_
//Stel filter in op het venster_x000D_
fc.setFileFilter(filter);_x000D_
_x000D_
//Haal de geselecteerde file op_x000D_
File selFile = fc.getSelectedFile();_x000D_
_x000D_
try_x000D_
{_x000D_
//Het opzetten van de leesfuncties_x000D_
FileWriter fr = new FileWriter(selFile);_x000D_
BufferedWriter br = new BufferedWriter(fr);_x000D_
_x000D_
//Schrijf eerste voorgedefinieerde header_x000D_
br.write("[Meting]");_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf het aantal samples, momenteel standaard 128_x000D_
br.write("Samples=" + 128);_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf originele data_x000D_
br.write("Org=" + graphOrg.getData(0));_x000D_
_x000D_
for (int i = 0; i < 128; i++)_x000D_
{_x000D_
br.write("," + graphOrg.getData(i));_x000D_
}_x000D_
_x000D_
br.newLine();_x000D_
_x000D_
//Schrijf FFT data_x000D_
br.write("FFT=" + graphFFT.getData(0));_x000D_
_x000D_
for (int i = 0; i < 128; i++)_x000D_
{_x000D_
br.write("," + graphFFT.getData(i));_x000D_
}_x000D_
_x000D_
br.newLine();_x000D_
_x000D_
//Sluit File_x000D_
br.close();_x000D_
}_x000D_
catch (Exception e)_x000D_
{_x000D_
//Bij storing procedure afbreken_x000D_
JOptionPane.showMessageDialog(null, e.getMessage(), "Open file failed",_x000D_
JOptionPane.ERROR_MESSAGE);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Start the GUI_x000D_
*/_x000D_
public void init()_x000D_
{_x000D_
Debug.printInfo("Starting RobotGUI for " + robot.name);_x000D_
_x000D_
//Make panel for our graphs_x000D_
JPanel Graphs = new JPanel();_x000D_
_x000D_
//Make panel for our detectors_x000D_
JPanel Detectors = new JPanel();_x000D_
_x000D_
//Set up graph panel_x000D_
Graphs.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
Graphs.setLayout(new java.awt.GridLayout(1, 2));_x000D_
_x000D_
// Initialize grahps to show_x000D_
_x000D_
graphOrg.setPlotStyle(GraphPlot.SIGNAL);_x000D_
graphOrg.setTracePlot(true);_x000D_
_x000D_
graphFFT.setPlotStyle(GraphPlot.SPECTRUM);_x000D_
graphFFT.setTracePlot(false);_x000D_
_x000D_
//And add Graphs onto it_x000D_
Graphs.add(graphOrg);_x000D_
Graphs.add(graphFFT);_x000D_
Graphs.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
_x000D_
Detectors.setLayout(new java.awt.GridLayout(1, 5));_x000D_
_x000D_
//Maak indicatoren_x000D_
for (int i = 0; i < recStatus.length; i++)_x000D_
{_x000D_
recStatus[i] = new JButton(chars[i]);_x000D_
Detectors.add(recStatus[i]);_x000D_
}_x000D_
_x000D_
//Set up contentPane_x000D_
graph.getContentPane().setLayout(new BorderLayout());_x000D_
graph.getContentPane().add(Graphs, BorderLayout.CENTER);_x000D_
graph.getContentPane().add(Detectors, BorderLayout.SOUTH);_x000D_
_x000D_
JPanel vulling = new JPanel();_x000D_
graph.getContentPane().add(vulling, BorderLayout.NORTH);_x000D_
vulling.setLayout(new FlowLayout(FlowLayout.LEFT));_x000D_
vulling.add(meting_running);_x000D_
meting_running.setIcon(iconStart);_x000D_
_x000D_
//Make menu_x000D_
JMenuBar menu = new JMenuBar();_x000D_
graph.setJMenuBar(menu);_x000D_
_x000D_
JMenu bestand = new JMenu("File");_x000D_
menu.add(bestand);_x000D_
bestand.add(bestand_open);_x000D_
bestand_open.addActionListener(robotGUIActionlistener);_x000D_
bestand.add(bestand_save);_x000D_
bestand_save.addActionListener(robotGUIActionlistener);_x000D_
meting_running.addActionListener(robotGUIActionlistener);_x000D_
_x000D_
// Add checkbox for simulated sensor_x000D_
graph.getContentPane().add(sensorSimul, BorderLayout.SOUTH);_x000D_
// Listen to checkbox_x000D_
sensorSimul.addActionListener(robotGUIActionlistener);_x000D_
_x000D_
//And the SIZE_x000D_
graph.setSize(900, 300);_x000D_
graph.setVisible(GRAPH_DEFAULT_VISIBLE);_x000D_
_x000D_
// Initialize timer_x000D_
t = new Timer(50, robotGUIActionlistener);_x000D_
t.start();_x000D_
}_x000D_
_x000D_
// Update all the readings_x000D_
private void updateReadings()_x000D_
{_x000D_
// Alleen als<SUF>
if (measuring)_x000D_
{_x000D_
updateGraphData();_x000D_
//updateSpraak();_x000D_
}_x000D_
}_x000D_
_x000D_
//Functie die grafieken up to date houdt_x000D_
private void updateGraphData()_x000D_
{_x000D_
byte[] result = new byte[SAMPLESIZE];_x000D_
_x000D_
byte[] originalData;_x000D_
byte[] convertedData;_x000D_
// Needed to resolve signed/unsigned issue_x000D_
originalData = theServer.getSensorData(1);_x000D_
_x000D_
//originalData = new byte[64];_x000D_
// Convert the data_x000D_
convertedData = FastFourierTransform.convertData(originalData);_x000D_
//convertedData = originalData;_x000D_
// Kopieer in nieuwe array_x000D_
for (int i = 0; i < convertedData.length && i < SAMPLESIZE; i++)_x000D_
{_x000D_
result[i] = convertedData[i];_x000D_
}_x000D_
// De rest wordt 0 gemaakt._x000D_
for (int i = originalData.length; i < SAMPLESIZE; i++)_x000D_
{_x000D_
result[i] = 0;_x000D_
}_x000D_
_x000D_
// Set de data in de grafiek_x000D_
graphOrg.setPlotValues(result);_x000D_
_x000D_
FastFourierTransform fft = new FastFourierTransform();_x000D_
_x000D_
_x000D_
/*_x000D_
* Change:_x000D_
* We not read the result into a special variable, so that it_x000D_
* can be passed along to our own module for speech recognition._x000D_
* After that, it is plotted to the screen as normal._x000D_
*/_x000D_
byte[] plotValues = fft.fftMag(result);_x000D_
_x000D_
analyser.update(plotValues);_x000D_
_x000D_
graphFFT.setPlotValues(plotValues);_x000D_
}_x000D_
_x000D_
//Functie die leds aanzet indien er een letter is herkend_x000D_
private void updateSpraak()_x000D_
{_x000D_
//Deze methode is overgenomen van het CVI project en_x000D_
//licht aangepast, commentaar zie aldaar_x000D_
int[] piekenDicht = {1, 1};_x000D_
int[] piekenVer = {45, 45};_x000D_
final double STORING = .5;_x000D_
final double STORING_VER = 0.35;_x000D_
final int WILLEKEUR = 5;_x000D_
_x000D_
recStatus[0].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[1].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[2].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[3].setBackground(Color.LIGHT_GRAY);_x000D_
recStatus[4].setBackground(Color.LIGHT_GRAY);_x000D_
_x000D_
byte[] speechData = graphFFT.getData();_x000D_
_x000D_
for (int i = 1; i < 22; i++)_x000D_
{_x000D_
if (speechData[i] > speechData[piekenDicht[0]])_x000D_
{_x000D_
piekenDicht[0] = i;_x000D_
}_x000D_
else if (speechData[i] > speechData[piekenDicht[1]])_x000D_
{_x000D_
piekenDicht[1] = i;_x000D_
}_x000D_
}_x000D_
_x000D_
for (int i = 23; i < 45; i++)_x000D_
{_x000D_
if (speechData[i] > speechData[piekenVer[0]])_x000D_
{_x000D_
piekenVer[0] = i;_x000D_
}_x000D_
else if (speechData[i] > speechData[piekenVer[1]])_x000D_
{_x000D_
piekenVer[1] = i;_x000D_
}_x000D_
}_x000D_
_x000D_
if (piekenVer[0] < STORING)_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (piekenDicht[0] < STORING_VER)_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (((piekenDicht[0] - piekenDicht[1]) > WILLEKEUR) && (piekenDicht[1] > STORING))_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if (((piekenVer[0] - piekenVer[1]) > WILLEKEUR) && (piekenVer[1] > STORING_VER))_x000D_
{_x000D_
//Nothing_x000D_
}_x000D_
else if ((piekenDicht[0] >= 10) && (piekenDicht[0] <= 15)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[0].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 5) && (piekenDicht[0] <= 8)_x000D_
&& (speechData[piekenDicht[0]] > STORING) && (piekenVer[0] >= 25)_x000D_
&& (piekenVer[0] <= 35) && (speechData[piekenVer[0]] > STORING_VER))_x000D_
{_x000D_
recStatus[1].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 2) && (piekenDicht[0] <= 4)_x000D_
&& (speechData[piekenDicht[0]] > STORING) && (piekenVer[0] >= 30)_x000D_
&& (piekenVer[0] <= 45) && (speechData[piekenVer[0]] > STORING_VER))_x000D_
{_x000D_
recStatus[2].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 2) && (piekenDicht[0] <= 4)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[4].setBackground(Color.GREEN);_x000D_
}_x000D_
else if ((piekenDicht[0] >= 5) && (piekenDicht[0] <= 8)_x000D_
&& (speechData[piekenDicht[0]] > STORING))_x000D_
{_x000D_
recStatus[3].setBackground(Color.GREEN);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Sets the visibility of this GUI_x000D_
*_x000D_
* @param visible boolean if visible (true) or not (false)_x000D_
*/_x000D_
public void setVisible(boolean visible)_x000D_
{_x000D_
graph.setVisible(visible);_x000D_
if(!visible) _x000D_
{_x000D_
stopMeasuring();_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Destroys this frame_x000D_
*/_x000D_
public void destroy()_x000D_
{_x000D_
graph.dispose();_x000D_
t.stop();_x000D_
}_x000D_
_x000D_
/**_x000D_
* Get the status of the "sensor simulated" checkbox in the robotGUI_x000D_
*_x000D_
* @return boolean - true if the checkbox is set (sensorvalues will be generated by simulator)_x000D_
* @see GraphGUI#robotGUIActionlistener_x000D_
*/_x000D_
public boolean getSensorSimulated()_x000D_
{_x000D_
return sensorSimul.isSelected();_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/**_x000D_
* Created on 20-02-2006_x000D_
* Copyright: (c) 2006_x000D_
* Company: Dancing Bear Software_x000D_
*_x000D_
* @version $Revision$_x000D_
* last changed 20-02-2006_x000D_
*_x000D_
* TODO CLASS: DOCUMENT ME! _x000D_
*/_x000D_
_x000D_
class myFileFilter extends FileFilter_x000D_
{_x000D_
/**_x000D_
* TODO METHOD: DOCUMENT ME!_x000D_
*_x000D_
* @param f TODO PARAM: param description_x000D_
*_x000D_
* @return $returnType$ TODO RETURN: return description_x000D_
*/_x000D_
public boolean accept(File f)_x000D_
{_x000D_
if (f.isDirectory())_x000D_
{_x000D_
return true;_x000D_
}_x000D_
_x000D_
String filename = f.getName();_x000D_
_x000D_
return filename.endsWith(".ini");_x000D_
}_x000D_
_x000D_
/**_x000D_
* TODO METHOD: DOCUMENT ME!_x000D_
*_x000D_
* @return String returns description_x000D_
*/_x000D_
public String getDescription()_x000D_
{_x000D_
return "Meting bestanden";_x000D_
}_x000D_
}_x000D_
| True |
4,800 | 195998_8 | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de verdieping toren1b
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | zanetworker/bandwidth-on-demand | src/test/java/nl/surfnet/bod/search/PhysicalPortIndexAndSearchTest.java | 1,581 | // Mock_port 2de verdieping toren1b | line_comment | nl | /**
* Copyright (c) 2012, 2013 SURFnet BV
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of the SURFnet BV nor the names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package nl.surfnet.bod.search;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import java.util.List;
import nl.surfnet.bod.domain.UniPort;
import org.apache.lucene.queryParser.ParseException;
import org.junit.Test;
public class PhysicalPortIndexAndSearchTest extends AbstractIndexAndSearch<UniPort> {
public PhysicalPortIndexAndSearchTest() {
super(UniPort.class);
}
@Test
public void testIndexAndSearch() throws Exception {
List<UniPort> physicalPorts = searchFor("gamma");
// (N.A.)
assertThat(physicalPorts, hasSize(0));
physicalPorts = searchFor("ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Ut");
// (UT One, UT Two)
assertThat(physicalPorts, hasSize(2));
physicalPorts = searchFor("Mock");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
physicalPorts = searchFor("ETH-1-13-4");
// (Noc label 4)
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("OME");
// (Mock_Ut002A_OME01_ETH-1-2-4, Mock_Ut001A_OME01_ETH-1-2-1)
assertThat(physicalPorts, hasSize(2));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
physicalPorts = searchFor("ETH-1-");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1");
// (All available (4) PP's)
assertThat(physicalPorts, hasSize(4));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Mock_Ut002A_OME01_ETH-1-2-1"));
assertThat(physicalPorts.get(1).getNocLabel(), equalTo("Mock_Ut001A_OME01_ETH-1-2-2"));
assertThat(physicalPorts.get(2).getNocLabel(), equalTo("Noc 3 label"));
assertThat(physicalPorts.get(3).getNocLabel(), equalTo("Noc 4 label"));
physicalPorts = searchFor("1de");
// Mock_port 1de verdieping toren1a
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 1de verdieping toren1a"));
physicalPorts = searchFor("2de");
// Mock_port 2de<SUF>
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getBodPortId(), equalTo("Mock_port 2de verdieping toren1b"));
}
@Test
public void shouldNotCrashOnColon() throws ParseException {
List<UniPort> physicalPorts = searchFor("nocLabel:\"Noc 3 label\"");
assertThat(physicalPorts, hasSize(1));
assertThat(physicalPorts.get(0).getNocLabel(), equalTo("Noc 3 label"));
}
} | True |
1,444 | 49623_25 | /*
* RED5 Open Source Media Server - https://github.com/Red5/ Copyright 2006-2023 by respective authors (see below). All rights reserved. Licensed under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
* required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package org.red5.server.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generic file utility containing useful file or directory manipulation functions.
*
* @author Paul Gregoire (mondain@gmail.com)
* @author Dominick Accattato (daccattato@gmail.com)
*/
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
public static void copyFile(File source, File dest) throws IOException {
log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile());
FileInputStream fi = new FileInputStream(source);
FileChannel fic = fi.getChannel();
MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length());
fic.close();
fi.close();
fi = null;
// ensure the destination directory exists
if (!dest.exists()) {
String destPath = dest.getPath();
log.debug("Destination path: {}", destPath);
String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar));
log.debug("Destination dir: {}", destDir);
File dir = new File(destDir);
if (!dir.exists()) {
if (dir.mkdirs()) {
log.debug("Directory created");
} else {
log.warn("Directory not created");
}
}
dir = null;
}
FileOutputStream fo = new FileOutputStream(dest);
FileChannel foc = fo.getChannel();
foc.write(mbuf);
foc.close();
fo.close();
fo = null;
mbuf.clear();
mbuf = null;
}
public static void copyFile(String source, String dest) throws IOException {
copyFile(new File(source), new File(dest));
}
public static void moveFile(String source, String dest) throws IOException {
copyFile(source, dest);
File src = new File(source);
if (src.exists() && src.canRead()) {
if (src.delete()) {
log.debug("Source file was deleted");
} else {
log.debug("Source file was not deleted, the file will be deleted on exit");
src.deleteOnExit();
}
} else {
log.warn("Source file could not be accessed for removal");
}
src = null;
}
/**
* Deletes a directory and its contents. This will fail if there are any file locks or if the directory cannot be emptied.
*
* @param directory
* directory to delete
* @throws IOException
* if directory cannot be deleted
* @return true if directory was successfully deleted; false if directory did not exist
*/
public static boolean deleteDirectory(String directory) throws IOException {
return deleteDirectory(directory, false);
}
/**
* Deletes a directory and its contents. This will fail if there are any file locks or if the directory cannot be emptied.
*
* @param directory
* directory to delete
* @param useOSNativeDelete
* flag to signify use of operating system delete function
* @throws IOException
* if directory cannot be deleted
* @return true if directory was successfully deleted; false if directory did not exist
*/
public static boolean deleteDirectory(String directory, boolean useOSNativeDelete) throws IOException {
boolean result = false;
if (!useOSNativeDelete) {
File dir = new File(directory);
// first all files have to be cleared out
for (File file : dir.listFiles()) {
if (file.delete()) {
log.debug("{} was deleted", file.getName());
} else {
log.debug("{} was not deleted", file.getName());
file.deleteOnExit();
}
file = null;
}
// not you may remove the dir
if (dir.delete()) {
log.debug("Directory was deleted");
result = true;
} else {
log.debug("Directory was not deleted, it may be deleted on exit");
dir.deleteOnExit();
}
dir = null;
} else {
Process p = null;
Thread std = null;
try {
Runtime runTime = Runtime.getRuntime();
log.debug("Execute runtime");
//determine file system type
if (File.separatorChar == '\\') {
//we are windows
p = runTime.exec("CMD /D /C \"RMDIR /Q /S " + directory.replace('/', '\\') + "\"");
} else {
//we are unix variant
p = runTime.exec("rm -rf " + directory.replace('\\', File.separatorChar));
}
// observe std out
std = stdOut(p);
// wait for the observer threads to finish
while (std.isAlive()) {
try {
Thread.sleep(250);
} catch (Exception e) {
}
}
log.debug("Process threads wait exited");
result = true;
} catch (Exception e) {
log.error("Error running delete script", e);
} finally {
if (null != p) {
log.debug("Destroying process");
p.destroy();
p = null;
}
std = null;
}
}
return result;
}
/**
* Rename a file natively; using REN on Windows and mv on *nix.
*
* @param from
* old name
* @param to
* new name
*/
public static void rename(String from, String to) {
try {
Files.move(Paths.get(from), Paths.get(to), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
log.error("Error renaming file", e);
}
}
/**
* Special method for capture of StdOut.
*
* @return stdOut thread
*/
private final static Thread stdOut(final Process p) {
final byte[] empty = new byte[128];
for (int b = 0; b < empty.length; b++) {
empty[b] = (byte) 0;
}
Thread std = new Thread() {
public void run() {
StringBuilder sb = new StringBuilder(1024);
byte[] buf = new byte[128];
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
log.debug("Process output:");
try {
while (bis.read(buf) != -1) {
sb.append(new String(buf).trim());
// clear buffer
System.arraycopy(empty, 0, buf, 0, buf.length);
}
log.debug(sb.toString());
bis.close();
} catch (Exception e) {
log.error("{}", e);
}
}
};
std.setDaemon(true);
std.start();
return std;
}
/**
* Create a directory.
*
* @param directory
* directory to make
* @return whether a new directory was made
* @throws IOException
* if directory does not already exist or cannot be made
*/
public static boolean makeDirectory(String directory) throws IOException {
return makeDirectory(directory, false);
}
/**
* Create a directory. The parent directories will be created if <i>createParents</i> is passed as true.
*
* @param directory
* directory
* @param createParents
* whether to create all parents
* @return true if directory was created; false if it already existed
* @throws IOException
* if we cannot create directory
*
*/
public static boolean makeDirectory(String directory, boolean createParents) throws IOException {
boolean created = false;
File dir = new File(directory);
if (createParents) {
created = dir.mkdirs();
if (created) {
log.debug("Directory created: {}", dir.getAbsolutePath());
} else {
log.debug("Directory was not created: {}", dir.getAbsolutePath());
}
} else {
created = dir.mkdir();
if (created) {
log.debug("Directory created: {}", dir.getAbsolutePath());
} else {
log.debug("Directory was not created: {}", dir.getAbsolutePath());
}
}
dir = null;
return created;
}
/**
* Unzips a war file to an application located under the webapps directory
*
* @param compressedFileName
* The String name of the war file
* @param destinationDir
* The destination directory, ie: webapps
*/
public static void unzip(String compressedFileName, String destinationDir) {
//strip everything except the applications name
String dirName = null;
// checks to see if there is a dash "-" in the filename of the war.
String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/"));
int dashIndex = applicationName.indexOf('-');
if (dashIndex != -1) {
//strip everything except the applications name
dirName = compressedFileName.substring(0, dashIndex);
} else {
//grab every char up to the last '.'
dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.'));
}
log.debug("Directory: {}", dirName);
//String tmpDir = System.getProperty("java.io.tmpdir");
File zipDir = new File(compressedFileName);
File parent = zipDir.getParentFile();
log.debug("Parent: {}", (parent != null ? parent.getName() : null));
//File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName);
File tmpDir = new File(destinationDir);
// make the war directory
log.debug("Making directory: {}", tmpDir.mkdirs());
ZipFile zf = null;
try {
zf = new ZipFile(compressedFileName);
Enumeration<?> e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
log.debug("Unzipping {}", ze.getName());
if (ze.isDirectory()) {
log.debug("is a directory");
File dir = new File(tmpDir + "/" + ze.getName());
Boolean tmp = dir.mkdir();
log.debug("{}", tmp);
continue;
}
// checks to see if a zipEntry contains a path
// i.e. ze.getName() == "META-INF/MANIFEST.MF"
// if this case is true, then we create the path first
if (ze.getName().lastIndexOf("/") != -1) {
String zipName = ze.getName();
String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/"));
File completeDirectory = new File(tmpDir + "/" + zipDirStructure);
if (!completeDirectory.exists()) {
if (!completeDirectory.mkdirs()) {
log.error("could not create complete directory structure");
}
}
}
// creates the file
FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName());
InputStream in = zf.getInputStream(ze);
copy(in, fout);
in.close();
fout.close();
}
e = null;
} catch (IOException e) {
log.error("Errored unzipping", e);
//log.warn("Exception {}", e);
} finally {
if (zf != null) {
try {
zf.close();
} catch (IOException e) {
}
}
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1)
break;
out.write(buffer, 0, bytesRead);
}
}
}
}
/**
* Quick-n-dirty directory formatting to support launching in windows, specifically from ant.
*
* @param absWebappsPath
* abs webapps path
* @param contextDirName
* conext directory name
* @return full path
*/
public static String formatPath(String absWebappsPath, String contextDirName) {
StringBuilder path = new StringBuilder(absWebappsPath.length() + contextDirName.length());
path.append(absWebappsPath);
if (log.isTraceEnabled()) {
log.trace("Path start: {}", path.toString());
}
int idx = -1;
if (File.separatorChar != '/') {
while ((idx = path.indexOf(File.separator)) != -1) {
path.deleteCharAt(idx);
path.insert(idx, '/');
}
}
if (log.isTraceEnabled()) {
log.trace("Path step 1: {}", path.toString());
}
//remove any './'
if ((idx = path.indexOf("./")) != -1) {
path.delete(idx, idx + 2);
}
if (log.isTraceEnabled()) {
log.trace("Path step 2: {}", path.toString());
}
//add / to base path if one doesnt exist
if (path.charAt(path.length() - 1) != '/') {
path.append('/');
}
if (log.isTraceEnabled()) {
log.trace("Path step 3: {}", path.toString());
}
//remove the / from the beginning of the context dir
if (contextDirName.charAt(0) == '/' && path.charAt(path.length() - 1) == '/') {
path.append(contextDirName.substring(1));
} else {
path.append(contextDirName);
}
if (log.isTraceEnabled()) {
log.trace("Path step 4: {}", path.toString());
}
return path.toString();
}
/**
* Generates a custom name containing numbers and an underscore ex. 282818_00023. The name contains current seconds and a random number component.
*
* @return custom name
*/
public static String generateCustomName() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
sb.append(PropertyConverter.getCurrentTimeSeconds());
sb.append('_');
int i = random.nextInt(99999);
if (i < 10) {
sb.append("0000");
} else if (i < 100) {
sb.append("000");
} else if (i < 1000) {
sb.append("00");
} else if (i < 10000) {
sb.append('0');
}
sb.append(i);
return sb.toString();
}
/**
* Reads all the bytes of a given file into an array. If the file size exceeds Integer.MAX_VALUE, it will be truncated.
*
* @param localSwfFile
* swf file
* @return file bytes
*/
public static byte[] readAsByteArray(File localSwfFile) {
byte[] fileBytes = new byte[(int) localSwfFile.length()];
byte[] b = new byte[1];
FileInputStream fis = null;
try {
fis = new FileInputStream(localSwfFile);
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (fis.read(b) != -1) {
fileBytes[i] = b[0];
} else {
break;
}
}
} catch (IOException e) {
log.warn("Exception reading file bytes", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
return fileBytes;
}
}
| Red5/red5-server | common/src/main/java/org/red5/server/util/FileUtil.java | 4,580 | // i.e. ze.getName() == "META-INF/MANIFEST.MF" | line_comment | nl | /*
* RED5 Open Source Media Server - https://github.com/Red5/ Copyright 2006-2023 by respective authors (see below). All rights reserved. Licensed under the Apache License, Version
* 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless
* required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
package org.red5.server.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Enumeration;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Generic file utility containing useful file or directory manipulation functions.
*
* @author Paul Gregoire (mondain@gmail.com)
* @author Dominick Accattato (daccattato@gmail.com)
*/
public class FileUtil {
private static Logger log = LoggerFactory.getLogger(FileUtil.class);
public static void copyFile(File source, File dest) throws IOException {
log.debug("Copy from {} to {}", source.getAbsoluteFile(), dest.getAbsoluteFile());
FileInputStream fi = new FileInputStream(source);
FileChannel fic = fi.getChannel();
MappedByteBuffer mbuf = fic.map(FileChannel.MapMode.READ_ONLY, 0, source.length());
fic.close();
fi.close();
fi = null;
// ensure the destination directory exists
if (!dest.exists()) {
String destPath = dest.getPath();
log.debug("Destination path: {}", destPath);
String destDir = destPath.substring(0, destPath.lastIndexOf(File.separatorChar));
log.debug("Destination dir: {}", destDir);
File dir = new File(destDir);
if (!dir.exists()) {
if (dir.mkdirs()) {
log.debug("Directory created");
} else {
log.warn("Directory not created");
}
}
dir = null;
}
FileOutputStream fo = new FileOutputStream(dest);
FileChannel foc = fo.getChannel();
foc.write(mbuf);
foc.close();
fo.close();
fo = null;
mbuf.clear();
mbuf = null;
}
public static void copyFile(String source, String dest) throws IOException {
copyFile(new File(source), new File(dest));
}
public static void moveFile(String source, String dest) throws IOException {
copyFile(source, dest);
File src = new File(source);
if (src.exists() && src.canRead()) {
if (src.delete()) {
log.debug("Source file was deleted");
} else {
log.debug("Source file was not deleted, the file will be deleted on exit");
src.deleteOnExit();
}
} else {
log.warn("Source file could not be accessed for removal");
}
src = null;
}
/**
* Deletes a directory and its contents. This will fail if there are any file locks or if the directory cannot be emptied.
*
* @param directory
* directory to delete
* @throws IOException
* if directory cannot be deleted
* @return true if directory was successfully deleted; false if directory did not exist
*/
public static boolean deleteDirectory(String directory) throws IOException {
return deleteDirectory(directory, false);
}
/**
* Deletes a directory and its contents. This will fail if there are any file locks or if the directory cannot be emptied.
*
* @param directory
* directory to delete
* @param useOSNativeDelete
* flag to signify use of operating system delete function
* @throws IOException
* if directory cannot be deleted
* @return true if directory was successfully deleted; false if directory did not exist
*/
public static boolean deleteDirectory(String directory, boolean useOSNativeDelete) throws IOException {
boolean result = false;
if (!useOSNativeDelete) {
File dir = new File(directory);
// first all files have to be cleared out
for (File file : dir.listFiles()) {
if (file.delete()) {
log.debug("{} was deleted", file.getName());
} else {
log.debug("{} was not deleted", file.getName());
file.deleteOnExit();
}
file = null;
}
// not you may remove the dir
if (dir.delete()) {
log.debug("Directory was deleted");
result = true;
} else {
log.debug("Directory was not deleted, it may be deleted on exit");
dir.deleteOnExit();
}
dir = null;
} else {
Process p = null;
Thread std = null;
try {
Runtime runTime = Runtime.getRuntime();
log.debug("Execute runtime");
//determine file system type
if (File.separatorChar == '\\') {
//we are windows
p = runTime.exec("CMD /D /C \"RMDIR /Q /S " + directory.replace('/', '\\') + "\"");
} else {
//we are unix variant
p = runTime.exec("rm -rf " + directory.replace('\\', File.separatorChar));
}
// observe std out
std = stdOut(p);
// wait for the observer threads to finish
while (std.isAlive()) {
try {
Thread.sleep(250);
} catch (Exception e) {
}
}
log.debug("Process threads wait exited");
result = true;
} catch (Exception e) {
log.error("Error running delete script", e);
} finally {
if (null != p) {
log.debug("Destroying process");
p.destroy();
p = null;
}
std = null;
}
}
return result;
}
/**
* Rename a file natively; using REN on Windows and mv on *nix.
*
* @param from
* old name
* @param to
* new name
*/
public static void rename(String from, String to) {
try {
Files.move(Paths.get(from), Paths.get(to), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
log.error("Error renaming file", e);
}
}
/**
* Special method for capture of StdOut.
*
* @return stdOut thread
*/
private final static Thread stdOut(final Process p) {
final byte[] empty = new byte[128];
for (int b = 0; b < empty.length; b++) {
empty[b] = (byte) 0;
}
Thread std = new Thread() {
public void run() {
StringBuilder sb = new StringBuilder(1024);
byte[] buf = new byte[128];
BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
log.debug("Process output:");
try {
while (bis.read(buf) != -1) {
sb.append(new String(buf).trim());
// clear buffer
System.arraycopy(empty, 0, buf, 0, buf.length);
}
log.debug(sb.toString());
bis.close();
} catch (Exception e) {
log.error("{}", e);
}
}
};
std.setDaemon(true);
std.start();
return std;
}
/**
* Create a directory.
*
* @param directory
* directory to make
* @return whether a new directory was made
* @throws IOException
* if directory does not already exist or cannot be made
*/
public static boolean makeDirectory(String directory) throws IOException {
return makeDirectory(directory, false);
}
/**
* Create a directory. The parent directories will be created if <i>createParents</i> is passed as true.
*
* @param directory
* directory
* @param createParents
* whether to create all parents
* @return true if directory was created; false if it already existed
* @throws IOException
* if we cannot create directory
*
*/
public static boolean makeDirectory(String directory, boolean createParents) throws IOException {
boolean created = false;
File dir = new File(directory);
if (createParents) {
created = dir.mkdirs();
if (created) {
log.debug("Directory created: {}", dir.getAbsolutePath());
} else {
log.debug("Directory was not created: {}", dir.getAbsolutePath());
}
} else {
created = dir.mkdir();
if (created) {
log.debug("Directory created: {}", dir.getAbsolutePath());
} else {
log.debug("Directory was not created: {}", dir.getAbsolutePath());
}
}
dir = null;
return created;
}
/**
* Unzips a war file to an application located under the webapps directory
*
* @param compressedFileName
* The String name of the war file
* @param destinationDir
* The destination directory, ie: webapps
*/
public static void unzip(String compressedFileName, String destinationDir) {
//strip everything except the applications name
String dirName = null;
// checks to see if there is a dash "-" in the filename of the war.
String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/"));
int dashIndex = applicationName.indexOf('-');
if (dashIndex != -1) {
//strip everything except the applications name
dirName = compressedFileName.substring(0, dashIndex);
} else {
//grab every char up to the last '.'
dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.'));
}
log.debug("Directory: {}", dirName);
//String tmpDir = System.getProperty("java.io.tmpdir");
File zipDir = new File(compressedFileName);
File parent = zipDir.getParentFile();
log.debug("Parent: {}", (parent != null ? parent.getName() : null));
//File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName);
File tmpDir = new File(destinationDir);
// make the war directory
log.debug("Making directory: {}", tmpDir.mkdirs());
ZipFile zf = null;
try {
zf = new ZipFile(compressedFileName);
Enumeration<?> e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry) e.nextElement();
log.debug("Unzipping {}", ze.getName());
if (ze.isDirectory()) {
log.debug("is a directory");
File dir = new File(tmpDir + "/" + ze.getName());
Boolean tmp = dir.mkdir();
log.debug("{}", tmp);
continue;
}
// checks to see if a zipEntry contains a path
// i.e. ze.getName()<SUF>
// if this case is true, then we create the path first
if (ze.getName().lastIndexOf("/") != -1) {
String zipName = ze.getName();
String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/"));
File completeDirectory = new File(tmpDir + "/" + zipDirStructure);
if (!completeDirectory.exists()) {
if (!completeDirectory.mkdirs()) {
log.error("could not create complete directory structure");
}
}
}
// creates the file
FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName());
InputStream in = zf.getInputStream(ze);
copy(in, fout);
in.close();
fout.close();
}
e = null;
} catch (IOException e) {
log.error("Errored unzipping", e);
//log.warn("Exception {}", e);
} finally {
if (zf != null) {
try {
zf.close();
} catch (IOException e) {
}
}
}
}
public static void copy(InputStream in, OutputStream out) throws IOException {
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1)
break;
out.write(buffer, 0, bytesRead);
}
}
}
}
/**
* Quick-n-dirty directory formatting to support launching in windows, specifically from ant.
*
* @param absWebappsPath
* abs webapps path
* @param contextDirName
* conext directory name
* @return full path
*/
public static String formatPath(String absWebappsPath, String contextDirName) {
StringBuilder path = new StringBuilder(absWebappsPath.length() + contextDirName.length());
path.append(absWebappsPath);
if (log.isTraceEnabled()) {
log.trace("Path start: {}", path.toString());
}
int idx = -1;
if (File.separatorChar != '/') {
while ((idx = path.indexOf(File.separator)) != -1) {
path.deleteCharAt(idx);
path.insert(idx, '/');
}
}
if (log.isTraceEnabled()) {
log.trace("Path step 1: {}", path.toString());
}
//remove any './'
if ((idx = path.indexOf("./")) != -1) {
path.delete(idx, idx + 2);
}
if (log.isTraceEnabled()) {
log.trace("Path step 2: {}", path.toString());
}
//add / to base path if one doesnt exist
if (path.charAt(path.length() - 1) != '/') {
path.append('/');
}
if (log.isTraceEnabled()) {
log.trace("Path step 3: {}", path.toString());
}
//remove the / from the beginning of the context dir
if (contextDirName.charAt(0) == '/' && path.charAt(path.length() - 1) == '/') {
path.append(contextDirName.substring(1));
} else {
path.append(contextDirName);
}
if (log.isTraceEnabled()) {
log.trace("Path step 4: {}", path.toString());
}
return path.toString();
}
/**
* Generates a custom name containing numbers and an underscore ex. 282818_00023. The name contains current seconds and a random number component.
*
* @return custom name
*/
public static String generateCustomName() {
Random random = new Random();
StringBuilder sb = new StringBuilder();
sb.append(PropertyConverter.getCurrentTimeSeconds());
sb.append('_');
int i = random.nextInt(99999);
if (i < 10) {
sb.append("0000");
} else if (i < 100) {
sb.append("000");
} else if (i < 1000) {
sb.append("00");
} else if (i < 10000) {
sb.append('0');
}
sb.append(i);
return sb.toString();
}
/**
* Reads all the bytes of a given file into an array. If the file size exceeds Integer.MAX_VALUE, it will be truncated.
*
* @param localSwfFile
* swf file
* @return file bytes
*/
public static byte[] readAsByteArray(File localSwfFile) {
byte[] fileBytes = new byte[(int) localSwfFile.length()];
byte[] b = new byte[1];
FileInputStream fis = null;
try {
fis = new FileInputStream(localSwfFile);
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if (fis.read(b) != -1) {
fileBytes[i] = b[0];
} else {
break;
}
}
} catch (IOException e) {
log.warn("Exception reading file bytes", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
}
}
}
return fileBytes;
}
}
| False |
3,643 | 152958_2 | /**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.netatmo.internal.api.data;
import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
import static org.openhab.core.library.CoreItemFactory.*;
import static org.openhab.core.library.unit.MetricPrefix.*;
import java.net.URI;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.measure.Unit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.library.unit.Units;
import org.openhab.core.types.StateDescriptionFragment;
import org.openhab.core.types.StateDescriptionFragmentBuilder;
import org.openhab.core.types.util.UnitUtils;
import com.google.gson.annotations.SerializedName;
/**
* This class holds various definitions and settings provided by the Netatmo
* API documentation
*
* @author Gaël L'hopital - Initial contribution
*/
@NonNullByDefault
public class NetatmoConstants {
public static class Measure {
public final double minValue;
public final double maxValue;
public final int scale;
public final Unit<?> unit;
private Measure(double minValue, double maxValue, double precision, Unit<?> unit) {
this.minValue = minValue;
this.maxValue = maxValue;
this.unit = unit;
String[] splitter = Double.toString(precision).split("\\.");
if (splitter.length > 1) {
int dec = Integer.parseInt(splitter[1]);
this.scale = dec > 0 ? Integer.toString(dec).length() : 0;
} else {
this.scale = 0;
}
}
}
public static class MeasureChannelDetails {
private static final StateDescriptionFragmentBuilder BUILDER = StateDescriptionFragmentBuilder.create();
public final URI configURI;
public final String itemType;
public final StateDescriptionFragment stateDescriptionFragment;
private MeasureChannelDetails(String measureType, String itemType, String pattern) {
this.configURI = URI.create(String.join(":", BINDING_ID, measureType, "config"));
this.itemType = itemType;
this.stateDescriptionFragment = BUILDER.withReadOnly(true).withPattern(pattern).build();
}
}
public enum MeasureClass {
INSIDE_TEMPERATURE(0, 50, 0.3, SIUnits.CELSIUS, "temp", "measure", true),
OUTSIDE_TEMPERATURE(-40, 65, 0.3, SIUnits.CELSIUS, "temp", "measure", true),
HEAT_INDEX(-40, 65, 1, SIUnits.CELSIUS, "", "", false),
PRESSURE(260, 1260, 0.1, HECTO(SIUnits.PASCAL), "pressure", "measure", true),
CO2(0, 5000, 50, Units.PARTS_PER_MILLION, "co2", "measure", true),
NOISE(35, 120, 1, Units.DECIBEL, "noise", "measure", true),
RAIN_QUANTITY(0, Double.MAX_VALUE, 0.1, MILLI(SIUnits.METRE), "sum_rain", "sum_rain", false),
RAIN_INTENSITY(0, 150, 0.1, Units.MILLIMETRE_PER_HOUR, "", "", false),
WIND_SPEED(0, 160, 1.8, SIUnits.KILOMETRE_PER_HOUR, "", "", false),
WIND_ANGLE(0, 360, 5, Units.DEGREE_ANGLE, "", "", false),
HUMIDITY(0, 100, 3, Units.PERCENT, "hum", "measure", true);
public static final EnumSet<MeasureClass> AS_SET = EnumSet.allOf(MeasureClass.class);
public final Measure measureDefinition;
public final String apiDescriptor;
public final Map<String, MeasureChannelDetails> channels = new HashMap<>(2);
MeasureClass(double min, double max, double precision, Unit<?> unit, String apiDescriptor, String confFragment,
boolean canScale) {
this.measureDefinition = new Measure(min, max, precision, unit);
this.apiDescriptor = apiDescriptor;
if (!apiDescriptor.isBlank()) {
String dimension = UnitUtils.getDimensionName(unit);
channels.put(String.join("-", apiDescriptor, "measurement"),
new MeasureChannelDetails(confFragment, String.join(":", NUMBER, dimension),
"%%.%df %s".formatted(measureDefinition.scale, UnitUtils.UNIT_PLACEHOLDER)));
if (canScale) {
channels.put(String.join("-", apiDescriptor, GROUP_TIMESTAMP), new MeasureChannelDetails(
GROUP_TIMESTAMP, DATETIME, "@text/extensible-channel-type.timestamp.pattern"));
}
}
}
}
// Content types
public static final String CONTENT_APP_JSON = "application/json;charset=utf-8";
public static final String CONTENT_APP_FORM = "application/x-www-form-urlencoded;charset=UTF-8";
// Netatmo API urls
public static final String URL_API = "https://api.netatmo.com/";
public static final String PATH_OAUTH = "oauth2";
public static final String SUB_PATH_TOKEN = "token";
public static final String SUB_PATH_AUTHORIZE = "authorize";
public static final String PATH_API = "api";
public static final String PATH_COMMAND = "command";
public static final String PATH_STATE = "setstate";
public static final String SUB_PATH_PERSON_AWAY = "setpersonsaway";
public static final String SUB_PATH_PERSON_HOME = "setpersonshome";
public static final String SUB_PATH_HOMES_DATA = "homesdata";
public static final String SUB_PATH_ADD_WEBHOOK = "addwebhook";
public static final String SUB_PATH_DROP_WEBHOOK = "dropwebhook";
public static final String SUB_PATH_SET_ROOM_THERMPOINT = "setroomthermpoint";
public static final String SUB_PATH_SET_THERM_MODE = "setthermmode";
public static final String SUB_PATH_SWITCH_SCHEDULE = "switchschedule";
public static final String SUB_PATH_GET_STATION = "getstationsdata";
public static final String SUB_PATH_GET_MEASURE = "getmeasure";
public static final String SUB_PATH_HOMESTATUS = "homestatus";
public static final String SUB_PATH_HOMECOACH = "gethomecoachsdata";
public static final String SUB_PATH_GET_EVENTS = "getevents";
public static final String SUB_PATH_PING = "ping";
public static final String SUB_PATH_CHANGESTATUS = "changestatus";
public static final String PARAM_DEVICE_ID = "device_id";
public static final String PARAM_MODULE_ID = "module_id";
public static final String PARAM_HOME_ID = "home_id";
public static final String PARAM_ROOM_ID = "room_id";
public static final String PARAM_PERSON_ID = "person_id";
public static final String PARAM_EVENT_ID = "event_id";
public static final String PARAM_SCHEDULE_ID = "schedule_id";
public static final String PARAM_OFFSET = "offset";
public static final String PARAM_GATEWAY_TYPE = "gateway_types";
public static final String PARAM_MODE = "mode";
public static final String PARAM_URL = "url";
public static final String PARAM_FAVORITES = "get_favorites";
public static final String PARAM_STATUS = "status";
public static final String PARAM_DEVICES_TYPE = "device_types";
// Payloads
public static final String PAYLOAD_FLOODLIGHT = "{\"home\": {\"id\":\"%s\",\"modules\": [ {\"id\":\"%s\",\"floodlight\":\"%s\"} ]}}";
public static final String PAYLOAD_SIREN_PRESENCE = "{\"home\": {\"id\":\"%s\",\"modules\": [ {\"id\":\"%s\",\"siren_status\":\"%s\"} ]}}";
public static final String PAYLOAD_PERSON_AWAY = "{\"home_id\":\"%s\",\"person_id\":\"%s\"}";
public static final String PAYLOAD_PERSON_HOME = "{\"home_id\":\"%s\",\"person_ids\":[\"%s\"]}";
// Autentication process params
public static final String PARAM_ERROR = "error";
// Global variables
public static final int THERM_MAX_SETPOINT = 30;
// Token scopes
public enum Scope {
@SerializedName("read_station")
READ_STATION,
@SerializedName("read_thermostat")
READ_THERMOSTAT,
@SerializedName("write_thermostat")
WRITE_THERMOSTAT,
@SerializedName("read_camera")
READ_CAMERA,
@SerializedName("write_camera")
WRITE_CAMERA,
@SerializedName("access_camera")
ACCESS_CAMERA,
@SerializedName("read_presence")
READ_PRESENCE,
@SerializedName("write_presence")
WRITE_PRESENCE,
@SerializedName("access_presence")
ACCESS_PRESENCE,
@SerializedName("read_smokedetector")
READ_SMOKEDETECTOR,
@SerializedName("read_homecoach")
READ_HOMECOACH,
@SerializedName("read_doorbell")
READ_DOORBELL,
@SerializedName("write_doorbell")
WRITE_DOORBELL,
@SerializedName("access_doorbell")
ACCESS_DOORBELL,
@SerializedName("read_carbonmonoxidedetector")
READ_CARBONMONOXIDEDETECTOR,
UNKNOWN
}
// Topology Changes
public enum TopologyChange {
@SerializedName("home_owner_added")
HOME_OWNER_ADDED,
@SerializedName("device_associated_to_user")
DEVICE_ASSOCIATED_TO_USER,
@SerializedName("device_associated_to_home")
DEVICE_ASSOCIATED_TO_HOME,
@SerializedName("device_updated")
DEVICE_UPDATED,
@SerializedName("device_associated_to_room")
DEVICE_ASSOCIATED_TO_ROOM,
@SerializedName("room_created")
ROOM_CREATED,
UNKNOWN
}
private static final Scope[] SMOKE_SCOPES = { Scope.READ_SMOKEDETECTOR };
private static final Scope[] CARBON_MONOXIDE_SCOPES = { Scope.READ_CARBONMONOXIDEDETECTOR };
private static final Scope[] AIR_CARE_SCOPES = { Scope.READ_HOMECOACH };
private static final Scope[] WEATHER_SCOPES = { Scope.READ_STATION };
private static final Scope[] THERMOSTAT_SCOPES = { Scope.READ_THERMOSTAT, Scope.WRITE_THERMOSTAT };
private static final Scope[] WELCOME_SCOPES = { Scope.READ_CAMERA, Scope.WRITE_CAMERA, Scope.ACCESS_CAMERA };
private static final Scope[] DOORBELL_SCOPES = { Scope.READ_DOORBELL, Scope.WRITE_DOORBELL, Scope.ACCESS_DOORBELL };
private static final Scope[] PRESENCE_SCOPES = { Scope.READ_PRESENCE, Scope.WRITE_PRESENCE, Scope.ACCESS_PRESENCE };
public enum FeatureArea {
AIR_CARE(AIR_CARE_SCOPES),
WEATHER(WEATHER_SCOPES),
ENERGY(THERMOSTAT_SCOPES),
SECURITY(WELCOME_SCOPES, PRESENCE_SCOPES, SMOKE_SCOPES, DOORBELL_SCOPES, CARBON_MONOXIDE_SCOPES),
NONE();
public static String ALL_SCOPES = EnumSet.allOf(FeatureArea.class).stream().map(fa -> fa.scopes)
.flatMap(Set::stream).map(s -> s.name().toLowerCase()).collect(Collectors.joining(" "));
public final Set<Scope> scopes;
FeatureArea(Scope[]... scopeArrays) {
this.scopes = Stream.of(scopeArrays).flatMap(Arrays::stream).collect(Collectors.toSet());
}
}
// Radio signal quality thresholds
static final int[] WIFI_SIGNAL_LEVELS = new int[] { 99, 84, 69, 54 }; // Resp : bad, average, good, full
static final int[] RADIO_SIGNAL_LEVELS = new int[] { 90, 80, 70, 60 }; // Resp : low, medium, high, full
// Thermostat definitions
public enum SetpointMode {
@SerializedName("program")
PROGRAM("program"),
@SerializedName("away")
AWAY("away"),
@SerializedName("hg")
FROST_GUARD("hg"),
@SerializedName("manual")
MANUAL("manual"),
@SerializedName("off")
OFF("off"),
@SerializedName("max")
MAX("max"),
@SerializedName("schedule")
SCHEDULE("schedule"),
HOME("home"),
UNKNOWN("");
public final String apiDescriptor;
SetpointMode(String descriptor) {
this.apiDescriptor = descriptor;
}
}
public enum ThermostatZoneType {
@SerializedName("0")
DAY("0"),
@SerializedName("1")
NIGHT("1"),
@SerializedName("2")
AWAY("2"),
@SerializedName("3")
FROST_GUARD("3"),
@SerializedName("4")
CUSTOM("4"),
@SerializedName("5")
ECO("5"),
@SerializedName("8")
COMFORT("8"),
UNKNOWN("");
public final String zoneId;
private ThermostatZoneType(String id) {
zoneId = id;
}
}
public enum FloodLightMode {
@SerializedName("on")
ON,
@SerializedName("off")
OFF,
@SerializedName("auto")
AUTO,
UNKNOWN
}
public enum EventCategory {
@SerializedName("human")
HUMAN,
@SerializedName("animal")
ANIMAL,
@SerializedName("vehicle")
VEHICLE,
UNKNOWN
}
public enum TrendDescription {
@SerializedName("up")
UP,
@SerializedName("stable")
STABLE,
@SerializedName("down")
DOWN,
UNKNOWN
}
public enum VideoStatus {
@SerializedName("recording")
RECORDING,
@SerializedName("available")
AVAILABLE,
@SerializedName("deleted")
DELETED,
UNKNOWN
}
public enum SdCardStatus {
@SerializedName("1")
SD_CARD_MISSING,
@SerializedName("2")
SD_CARD_INSERTED,
@SerializedName("3")
SD_CARD_FORMATTED,
@SerializedName("4")
SD_CARD_WORKING,
@SerializedName("5")
SD_CARD_DEFECTIVE,
@SerializedName("6")
SD_CARD_INCOMPATIBLE_SPEED,
@SerializedName("7")
SD_CARD_INSUFFICIENT_SPACE,
UNKNOWN
}
public enum AlimentationStatus {
@SerializedName("1")
ALIM_INCORRECT_POWER,
@SerializedName("2")
ALIM_CORRECT_POWER,
UNKNOWN
}
public enum SirenStatus {
SOUND,
NO_SOUND,
UNKNOWN;
public static SirenStatus get(String value) {
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
return UNKNOWN;
}
}
}
public enum BatteryState {
@SerializedName("full")
FULL(100),
@SerializedName("high")
HIGH(80),
@SerializedName("medium")
MEDIUM(50),
@SerializedName("low")
LOW(15),
UNKNOWN(-1);
public final int level;
BatteryState(int i) {
this.level = i;
}
}
public enum ServiceError {
@SerializedName("99")
UNKNOWN,
@SerializedName("-2")
UNKNOWN_ERROR_IN_OAUTH,
@SerializedName("-1")
GRANT_IS_INVALID,
@SerializedName("1")
ACCESS_TOKEN_MISSING,
@SerializedName("2")
INVALID_TOKEN_MISSING,
@SerializedName("3")
ACCESS_TOKEN_EXPIRED,
@SerializedName("5")
APPLICATION_DEACTIVATED,
@SerializedName("7")
NOTHING_TO_MODIFY,
@SerializedName("9")
DEVICE_NOT_FOUND,
@SerializedName("10")
MISSING_ARGUMENTS,
@SerializedName("13")
OPERATION_FORBIDDEN,
@SerializedName("19")
IP_NOT_FOUND,
@SerializedName("21")
INVALID_ARGUMENT,
@SerializedName("22")
APPLICATION_NOT_FOUND,
@SerializedName("23")
USER_NOT_FOUND,
@SerializedName("25")
INVALID_DATE,
@SerializedName("26")
MAXIMUM_USAGE_REACHED,
@SerializedName("30")
INVALID_REFRESH_TOKEN,
@SerializedName("31")
METHOD_NOT_FOUND,
@SerializedName("35")
UNABLE_TO_EXECUTE,
@SerializedName("36")
PROHIBITED_STRING,
@SerializedName("37")
NO_MORE_SPACE_AVAILABLE_ON_THE_CAMERA,
@SerializedName("40")
JSON_GIVEN_HAS_AN_INVALID_ENCODING,
@SerializedName("41")
DEVICE_IS_UNREACHABLE
}
public enum HomeStatusError {
@SerializedName("1")
UNKNOWN_ERROR("homestatus-unknown-error"),
@SerializedName("2")
INTERNAL_ERROR("homestatus-internal-error"),
@SerializedName("3")
PARSER_ERROR("homestatus-parser-error"),
@SerializedName("4")
COMMAND_UNKNOWN_NODE_MODULE_ERROR("homestatus-command-unknown"),
@SerializedName("5")
COMMAND_INVALID_PARAMS("homestatus-invalid-params"),
@SerializedName("6")
UNREACHABLE("device-not-connected"),
UNKNOWN("deserialization-unknown");
// Associated error message that can be found in properties files
public final String message;
HomeStatusError(String message) {
this.message = message;
}
}
}
| mhilbush/openhab-addons | bundles/org.openhab.binding.netatmo/src/main/java/org/openhab/binding/netatmo/internal/api/data/NetatmoConstants.java | 5,465 | // Netatmo API urls | line_comment | nl | /**
* Copyright (c) 2010-2024 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.netatmo.internal.api.data;
import static org.openhab.binding.netatmo.internal.NetatmoBindingConstants.*;
import static org.openhab.core.library.CoreItemFactory.*;
import static org.openhab.core.library.unit.MetricPrefix.*;
import java.net.URI;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.measure.Unit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.library.unit.Units;
import org.openhab.core.types.StateDescriptionFragment;
import org.openhab.core.types.StateDescriptionFragmentBuilder;
import org.openhab.core.types.util.UnitUtils;
import com.google.gson.annotations.SerializedName;
/**
* This class holds various definitions and settings provided by the Netatmo
* API documentation
*
* @author Gaël L'hopital - Initial contribution
*/
@NonNullByDefault
public class NetatmoConstants {
public static class Measure {
public final double minValue;
public final double maxValue;
public final int scale;
public final Unit<?> unit;
private Measure(double minValue, double maxValue, double precision, Unit<?> unit) {
this.minValue = minValue;
this.maxValue = maxValue;
this.unit = unit;
String[] splitter = Double.toString(precision).split("\\.");
if (splitter.length > 1) {
int dec = Integer.parseInt(splitter[1]);
this.scale = dec > 0 ? Integer.toString(dec).length() : 0;
} else {
this.scale = 0;
}
}
}
public static class MeasureChannelDetails {
private static final StateDescriptionFragmentBuilder BUILDER = StateDescriptionFragmentBuilder.create();
public final URI configURI;
public final String itemType;
public final StateDescriptionFragment stateDescriptionFragment;
private MeasureChannelDetails(String measureType, String itemType, String pattern) {
this.configURI = URI.create(String.join(":", BINDING_ID, measureType, "config"));
this.itemType = itemType;
this.stateDescriptionFragment = BUILDER.withReadOnly(true).withPattern(pattern).build();
}
}
public enum MeasureClass {
INSIDE_TEMPERATURE(0, 50, 0.3, SIUnits.CELSIUS, "temp", "measure", true),
OUTSIDE_TEMPERATURE(-40, 65, 0.3, SIUnits.CELSIUS, "temp", "measure", true),
HEAT_INDEX(-40, 65, 1, SIUnits.CELSIUS, "", "", false),
PRESSURE(260, 1260, 0.1, HECTO(SIUnits.PASCAL), "pressure", "measure", true),
CO2(0, 5000, 50, Units.PARTS_PER_MILLION, "co2", "measure", true),
NOISE(35, 120, 1, Units.DECIBEL, "noise", "measure", true),
RAIN_QUANTITY(0, Double.MAX_VALUE, 0.1, MILLI(SIUnits.METRE), "sum_rain", "sum_rain", false),
RAIN_INTENSITY(0, 150, 0.1, Units.MILLIMETRE_PER_HOUR, "", "", false),
WIND_SPEED(0, 160, 1.8, SIUnits.KILOMETRE_PER_HOUR, "", "", false),
WIND_ANGLE(0, 360, 5, Units.DEGREE_ANGLE, "", "", false),
HUMIDITY(0, 100, 3, Units.PERCENT, "hum", "measure", true);
public static final EnumSet<MeasureClass> AS_SET = EnumSet.allOf(MeasureClass.class);
public final Measure measureDefinition;
public final String apiDescriptor;
public final Map<String, MeasureChannelDetails> channels = new HashMap<>(2);
MeasureClass(double min, double max, double precision, Unit<?> unit, String apiDescriptor, String confFragment,
boolean canScale) {
this.measureDefinition = new Measure(min, max, precision, unit);
this.apiDescriptor = apiDescriptor;
if (!apiDescriptor.isBlank()) {
String dimension = UnitUtils.getDimensionName(unit);
channels.put(String.join("-", apiDescriptor, "measurement"),
new MeasureChannelDetails(confFragment, String.join(":", NUMBER, dimension),
"%%.%df %s".formatted(measureDefinition.scale, UnitUtils.UNIT_PLACEHOLDER)));
if (canScale) {
channels.put(String.join("-", apiDescriptor, GROUP_TIMESTAMP), new MeasureChannelDetails(
GROUP_TIMESTAMP, DATETIME, "@text/extensible-channel-type.timestamp.pattern"));
}
}
}
}
// Content types
public static final String CONTENT_APP_JSON = "application/json;charset=utf-8";
public static final String CONTENT_APP_FORM = "application/x-www-form-urlencoded;charset=UTF-8";
// Netatmo API<SUF>
public static final String URL_API = "https://api.netatmo.com/";
public static final String PATH_OAUTH = "oauth2";
public static final String SUB_PATH_TOKEN = "token";
public static final String SUB_PATH_AUTHORIZE = "authorize";
public static final String PATH_API = "api";
public static final String PATH_COMMAND = "command";
public static final String PATH_STATE = "setstate";
public static final String SUB_PATH_PERSON_AWAY = "setpersonsaway";
public static final String SUB_PATH_PERSON_HOME = "setpersonshome";
public static final String SUB_PATH_HOMES_DATA = "homesdata";
public static final String SUB_PATH_ADD_WEBHOOK = "addwebhook";
public static final String SUB_PATH_DROP_WEBHOOK = "dropwebhook";
public static final String SUB_PATH_SET_ROOM_THERMPOINT = "setroomthermpoint";
public static final String SUB_PATH_SET_THERM_MODE = "setthermmode";
public static final String SUB_PATH_SWITCH_SCHEDULE = "switchschedule";
public static final String SUB_PATH_GET_STATION = "getstationsdata";
public static final String SUB_PATH_GET_MEASURE = "getmeasure";
public static final String SUB_PATH_HOMESTATUS = "homestatus";
public static final String SUB_PATH_HOMECOACH = "gethomecoachsdata";
public static final String SUB_PATH_GET_EVENTS = "getevents";
public static final String SUB_PATH_PING = "ping";
public static final String SUB_PATH_CHANGESTATUS = "changestatus";
public static final String PARAM_DEVICE_ID = "device_id";
public static final String PARAM_MODULE_ID = "module_id";
public static final String PARAM_HOME_ID = "home_id";
public static final String PARAM_ROOM_ID = "room_id";
public static final String PARAM_PERSON_ID = "person_id";
public static final String PARAM_EVENT_ID = "event_id";
public static final String PARAM_SCHEDULE_ID = "schedule_id";
public static final String PARAM_OFFSET = "offset";
public static final String PARAM_GATEWAY_TYPE = "gateway_types";
public static final String PARAM_MODE = "mode";
public static final String PARAM_URL = "url";
public static final String PARAM_FAVORITES = "get_favorites";
public static final String PARAM_STATUS = "status";
public static final String PARAM_DEVICES_TYPE = "device_types";
// Payloads
public static final String PAYLOAD_FLOODLIGHT = "{\"home\": {\"id\":\"%s\",\"modules\": [ {\"id\":\"%s\",\"floodlight\":\"%s\"} ]}}";
public static final String PAYLOAD_SIREN_PRESENCE = "{\"home\": {\"id\":\"%s\",\"modules\": [ {\"id\":\"%s\",\"siren_status\":\"%s\"} ]}}";
public static final String PAYLOAD_PERSON_AWAY = "{\"home_id\":\"%s\",\"person_id\":\"%s\"}";
public static final String PAYLOAD_PERSON_HOME = "{\"home_id\":\"%s\",\"person_ids\":[\"%s\"]}";
// Autentication process params
public static final String PARAM_ERROR = "error";
// Global variables
public static final int THERM_MAX_SETPOINT = 30;
// Token scopes
public enum Scope {
@SerializedName("read_station")
READ_STATION,
@SerializedName("read_thermostat")
READ_THERMOSTAT,
@SerializedName("write_thermostat")
WRITE_THERMOSTAT,
@SerializedName("read_camera")
READ_CAMERA,
@SerializedName("write_camera")
WRITE_CAMERA,
@SerializedName("access_camera")
ACCESS_CAMERA,
@SerializedName("read_presence")
READ_PRESENCE,
@SerializedName("write_presence")
WRITE_PRESENCE,
@SerializedName("access_presence")
ACCESS_PRESENCE,
@SerializedName("read_smokedetector")
READ_SMOKEDETECTOR,
@SerializedName("read_homecoach")
READ_HOMECOACH,
@SerializedName("read_doorbell")
READ_DOORBELL,
@SerializedName("write_doorbell")
WRITE_DOORBELL,
@SerializedName("access_doorbell")
ACCESS_DOORBELL,
@SerializedName("read_carbonmonoxidedetector")
READ_CARBONMONOXIDEDETECTOR,
UNKNOWN
}
// Topology Changes
public enum TopologyChange {
@SerializedName("home_owner_added")
HOME_OWNER_ADDED,
@SerializedName("device_associated_to_user")
DEVICE_ASSOCIATED_TO_USER,
@SerializedName("device_associated_to_home")
DEVICE_ASSOCIATED_TO_HOME,
@SerializedName("device_updated")
DEVICE_UPDATED,
@SerializedName("device_associated_to_room")
DEVICE_ASSOCIATED_TO_ROOM,
@SerializedName("room_created")
ROOM_CREATED,
UNKNOWN
}
private static final Scope[] SMOKE_SCOPES = { Scope.READ_SMOKEDETECTOR };
private static final Scope[] CARBON_MONOXIDE_SCOPES = { Scope.READ_CARBONMONOXIDEDETECTOR };
private static final Scope[] AIR_CARE_SCOPES = { Scope.READ_HOMECOACH };
private static final Scope[] WEATHER_SCOPES = { Scope.READ_STATION };
private static final Scope[] THERMOSTAT_SCOPES = { Scope.READ_THERMOSTAT, Scope.WRITE_THERMOSTAT };
private static final Scope[] WELCOME_SCOPES = { Scope.READ_CAMERA, Scope.WRITE_CAMERA, Scope.ACCESS_CAMERA };
private static final Scope[] DOORBELL_SCOPES = { Scope.READ_DOORBELL, Scope.WRITE_DOORBELL, Scope.ACCESS_DOORBELL };
private static final Scope[] PRESENCE_SCOPES = { Scope.READ_PRESENCE, Scope.WRITE_PRESENCE, Scope.ACCESS_PRESENCE };
public enum FeatureArea {
AIR_CARE(AIR_CARE_SCOPES),
WEATHER(WEATHER_SCOPES),
ENERGY(THERMOSTAT_SCOPES),
SECURITY(WELCOME_SCOPES, PRESENCE_SCOPES, SMOKE_SCOPES, DOORBELL_SCOPES, CARBON_MONOXIDE_SCOPES),
NONE();
public static String ALL_SCOPES = EnumSet.allOf(FeatureArea.class).stream().map(fa -> fa.scopes)
.flatMap(Set::stream).map(s -> s.name().toLowerCase()).collect(Collectors.joining(" "));
public final Set<Scope> scopes;
FeatureArea(Scope[]... scopeArrays) {
this.scopes = Stream.of(scopeArrays).flatMap(Arrays::stream).collect(Collectors.toSet());
}
}
// Radio signal quality thresholds
static final int[] WIFI_SIGNAL_LEVELS = new int[] { 99, 84, 69, 54 }; // Resp : bad, average, good, full
static final int[] RADIO_SIGNAL_LEVELS = new int[] { 90, 80, 70, 60 }; // Resp : low, medium, high, full
// Thermostat definitions
public enum SetpointMode {
@SerializedName("program")
PROGRAM("program"),
@SerializedName("away")
AWAY("away"),
@SerializedName("hg")
FROST_GUARD("hg"),
@SerializedName("manual")
MANUAL("manual"),
@SerializedName("off")
OFF("off"),
@SerializedName("max")
MAX("max"),
@SerializedName("schedule")
SCHEDULE("schedule"),
HOME("home"),
UNKNOWN("");
public final String apiDescriptor;
SetpointMode(String descriptor) {
this.apiDescriptor = descriptor;
}
}
public enum ThermostatZoneType {
@SerializedName("0")
DAY("0"),
@SerializedName("1")
NIGHT("1"),
@SerializedName("2")
AWAY("2"),
@SerializedName("3")
FROST_GUARD("3"),
@SerializedName("4")
CUSTOM("4"),
@SerializedName("5")
ECO("5"),
@SerializedName("8")
COMFORT("8"),
UNKNOWN("");
public final String zoneId;
private ThermostatZoneType(String id) {
zoneId = id;
}
}
public enum FloodLightMode {
@SerializedName("on")
ON,
@SerializedName("off")
OFF,
@SerializedName("auto")
AUTO,
UNKNOWN
}
public enum EventCategory {
@SerializedName("human")
HUMAN,
@SerializedName("animal")
ANIMAL,
@SerializedName("vehicle")
VEHICLE,
UNKNOWN
}
public enum TrendDescription {
@SerializedName("up")
UP,
@SerializedName("stable")
STABLE,
@SerializedName("down")
DOWN,
UNKNOWN
}
public enum VideoStatus {
@SerializedName("recording")
RECORDING,
@SerializedName("available")
AVAILABLE,
@SerializedName("deleted")
DELETED,
UNKNOWN
}
public enum SdCardStatus {
@SerializedName("1")
SD_CARD_MISSING,
@SerializedName("2")
SD_CARD_INSERTED,
@SerializedName("3")
SD_CARD_FORMATTED,
@SerializedName("4")
SD_CARD_WORKING,
@SerializedName("5")
SD_CARD_DEFECTIVE,
@SerializedName("6")
SD_CARD_INCOMPATIBLE_SPEED,
@SerializedName("7")
SD_CARD_INSUFFICIENT_SPACE,
UNKNOWN
}
public enum AlimentationStatus {
@SerializedName("1")
ALIM_INCORRECT_POWER,
@SerializedName("2")
ALIM_CORRECT_POWER,
UNKNOWN
}
public enum SirenStatus {
SOUND,
NO_SOUND,
UNKNOWN;
public static SirenStatus get(String value) {
try {
return valueOf(value.toUpperCase());
} catch (IllegalArgumentException e) {
return UNKNOWN;
}
}
}
public enum BatteryState {
@SerializedName("full")
FULL(100),
@SerializedName("high")
HIGH(80),
@SerializedName("medium")
MEDIUM(50),
@SerializedName("low")
LOW(15),
UNKNOWN(-1);
public final int level;
BatteryState(int i) {
this.level = i;
}
}
public enum ServiceError {
@SerializedName("99")
UNKNOWN,
@SerializedName("-2")
UNKNOWN_ERROR_IN_OAUTH,
@SerializedName("-1")
GRANT_IS_INVALID,
@SerializedName("1")
ACCESS_TOKEN_MISSING,
@SerializedName("2")
INVALID_TOKEN_MISSING,
@SerializedName("3")
ACCESS_TOKEN_EXPIRED,
@SerializedName("5")
APPLICATION_DEACTIVATED,
@SerializedName("7")
NOTHING_TO_MODIFY,
@SerializedName("9")
DEVICE_NOT_FOUND,
@SerializedName("10")
MISSING_ARGUMENTS,
@SerializedName("13")
OPERATION_FORBIDDEN,
@SerializedName("19")
IP_NOT_FOUND,
@SerializedName("21")
INVALID_ARGUMENT,
@SerializedName("22")
APPLICATION_NOT_FOUND,
@SerializedName("23")
USER_NOT_FOUND,
@SerializedName("25")
INVALID_DATE,
@SerializedName("26")
MAXIMUM_USAGE_REACHED,
@SerializedName("30")
INVALID_REFRESH_TOKEN,
@SerializedName("31")
METHOD_NOT_FOUND,
@SerializedName("35")
UNABLE_TO_EXECUTE,
@SerializedName("36")
PROHIBITED_STRING,
@SerializedName("37")
NO_MORE_SPACE_AVAILABLE_ON_THE_CAMERA,
@SerializedName("40")
JSON_GIVEN_HAS_AN_INVALID_ENCODING,
@SerializedName("41")
DEVICE_IS_UNREACHABLE
}
public enum HomeStatusError {
@SerializedName("1")
UNKNOWN_ERROR("homestatus-unknown-error"),
@SerializedName("2")
INTERNAL_ERROR("homestatus-internal-error"),
@SerializedName("3")
PARSER_ERROR("homestatus-parser-error"),
@SerializedName("4")
COMMAND_UNKNOWN_NODE_MODULE_ERROR("homestatus-command-unknown"),
@SerializedName("5")
COMMAND_INVALID_PARAMS("homestatus-invalid-params"),
@SerializedName("6")
UNREACHABLE("device-not-connected"),
UNKNOWN("deserialization-unknown");
// Associated error message that can be found in properties files
public final String message;
HomeStatusError(String message) {
this.message = message;
}
}
}
| False |
2,312 | 161599_23 | /*******************************************************************************_x000D_
* Copyright (c) 2008, 2018 SWTChart project._x000D_
*_x000D_
* All rights reserved. This program and the accompanying materials_x000D_
* are made available under the terms of the Eclipse Public License v1.0_x000D_
* which accompanies this distribution, and is available at_x000D_
* http://www.eclipse.org/legal/epl-v10.html_x000D_
* _x000D_
* Contributors:_x000D_
* yoshitaka - initial API and implementation_x000D_
*******************************************************************************/_x000D_
package org.eclipse.swtchart.internal.axis;_x000D_
_x000D_
import java.text.Format;_x000D_
import java.util.List;_x000D_
_x000D_
import org.eclipse.swt.SWT;_x000D_
import org.eclipse.swt.graphics.Color;_x000D_
import org.eclipse.swt.graphics.Font;_x000D_
import org.eclipse.swt.graphics.Rectangle;_x000D_
import org.eclipse.swtchart.Chart;_x000D_
import org.eclipse.swtchart.IAxis.Position;_x000D_
import org.eclipse.swtchart.IAxisTick;_x000D_
_x000D_
/**_x000D_
* An axis tick._x000D_
*/_x000D_
public class AxisTick implements IAxisTick {_x000D_
_x000D_
/** the chart */_x000D_
private Chart chart;_x000D_
/** the axis */_x000D_
private Axis axis;_x000D_
/** the axis tick labels */_x000D_
private AxisTickLabels axisTickLabels;_x000D_
/** the axis tick marks */_x000D_
private AxisTickMarks axisTickMarks;_x000D_
/** true if tick is visible */_x000D_
private boolean isVisible;_x000D_
/** the tick mark step hint */_x000D_
private int tickMarkStepHint;_x000D_
/** the tick label angle in degree */_x000D_
private int tickLabelAngle;_x000D_
/** the default tick mark step hint */_x000D_
private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_
_x000D_
/**_x000D_
* Constructor._x000D_
*_x000D_
* @param chart_x000D_
* the chart_x000D_
* @param axis_x000D_
* the axis_x000D_
*/_x000D_
protected AxisTick(Chart chart, Axis axis) {_x000D_
this.chart = chart;_x000D_
this.axis = axis;_x000D_
axisTickLabels = new AxisTickLabels(chart, axis);_x000D_
axisTickMarks = new AxisTickMarks(chart, axis);_x000D_
isVisible = true;_x000D_
tickLabelAngle = 0;_x000D_
tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick marks._x000D_
*_x000D_
* @return the axis tick marks_x000D_
*/_x000D_
public AxisTickMarks getAxisTickMarks() {_x000D_
_x000D_
return axisTickMarks;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick labels._x000D_
*_x000D_
* @return the axis tick labels_x000D_
*/_x000D_
public AxisTickLabels getAxisTickLabels() {_x000D_
_x000D_
return axisTickLabels;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setForeground(Color)_x000D_
*/_x000D_
public void setForeground(Color color) {_x000D_
_x000D_
if(color != null && color.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickMarks.setForeground(color);_x000D_
axisTickLabels.setForeground(color);_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getForeground()_x000D_
*/_x000D_
public Color getForeground() {_x000D_
_x000D_
return axisTickMarks.getForeground();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFont(Font)_x000D_
*/_x000D_
public void setFont(Font font) {_x000D_
_x000D_
if(font != null && font.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickLabels.setFont(font);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFont()_x000D_
*/_x000D_
public Font getFont() {_x000D_
_x000D_
return axisTickLabels.getFont();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#isVisible()_x000D_
*/_x000D_
public boolean isVisible() {_x000D_
_x000D_
return isVisible;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setVisible(boolean)_x000D_
*/_x000D_
public void setVisible(boolean isVisible) {_x000D_
_x000D_
this.isVisible = isVisible;_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickMarkStepHint()_x000D_
*/_x000D_
public int getTickMarkStepHint() {_x000D_
_x000D_
return tickMarkStepHint;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickMarkStepHint(int)_x000D_
*/_x000D_
public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_
_x000D_
if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_
this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
} else {_x000D_
this.tickMarkStepHint = tickMarkStepHint;_x000D_
}_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelAngle()_x000D_
*/_x000D_
public int getTickLabelAngle() {_x000D_
_x000D_
return tickLabelAngle;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickLabelAngle(int)_x000D_
*/_x000D_
public void setTickLabelAngle(int angle) {_x000D_
_x000D_
if(angle < 0 || 90 < angle) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
if(tickLabelAngle != angle) {_x000D_
tickLabelAngle = angle;_x000D_
chart.updateLayout();_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFormat(Format)_x000D_
*/_x000D_
public void setFormat(Format format) {_x000D_
_x000D_
axisTickLabels.setFormat(format);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFormat()_x000D_
*/_x000D_
public Format getFormat() {_x000D_
_x000D_
return axisTickLabels.getFormat();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getBounds()_x000D_
*/_x000D_
public Rectangle getBounds() {_x000D_
_x000D_
Rectangle r1 = axisTickMarks.getBounds();_x000D_
Rectangle r2 = axisTickLabels.getBounds();_x000D_
Position position = axis.getPosition();_x000D_
if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else {_x000D_
throw new IllegalStateException("unknown axis position");_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelValues()_x000D_
*/_x000D_
public double[] getTickLabelValues() {_x000D_
_x000D_
List<Double> list = axisTickLabels.getTickLabelValues();_x000D_
double[] values = new double[list.size()];_x000D_
for(int i = 0; i < values.length; i++) {_x000D_
values[i] = list.get(i);_x000D_
}_x000D_
return values;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick around per 64 pixel._x000D_
*_x000D_
* @param length_x000D_
* the axis length_x000D_
*/_x000D_
public void updateTick(int length) {_x000D_
_x000D_
if(length <= 0) {_x000D_
axisTickLabels.update(1);_x000D_
} else {_x000D_
axisTickLabels.update(length);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick layout._x000D_
*/_x000D_
protected void updateLayoutData() {_x000D_
_x000D_
axisTickLabels.updateLayoutData();_x000D_
axisTickMarks.updateLayoutData();_x000D_
}_x000D_
}_x000D_
| buchen/swtchart | org.eclipse.swtchart/src/org/eclipse/swtchart/internal/axis/AxisTick.java | 2,198 | /*_x000D_
* @see IAxisTick#getBounds()_x000D_
*/ | block_comment | nl | /*******************************************************************************_x000D_
* Copyright (c) 2008, 2018 SWTChart project._x000D_
*_x000D_
* All rights reserved. This program and the accompanying materials_x000D_
* are made available under the terms of the Eclipse Public License v1.0_x000D_
* which accompanies this distribution, and is available at_x000D_
* http://www.eclipse.org/legal/epl-v10.html_x000D_
* _x000D_
* Contributors:_x000D_
* yoshitaka - initial API and implementation_x000D_
*******************************************************************************/_x000D_
package org.eclipse.swtchart.internal.axis;_x000D_
_x000D_
import java.text.Format;_x000D_
import java.util.List;_x000D_
_x000D_
import org.eclipse.swt.SWT;_x000D_
import org.eclipse.swt.graphics.Color;_x000D_
import org.eclipse.swt.graphics.Font;_x000D_
import org.eclipse.swt.graphics.Rectangle;_x000D_
import org.eclipse.swtchart.Chart;_x000D_
import org.eclipse.swtchart.IAxis.Position;_x000D_
import org.eclipse.swtchart.IAxisTick;_x000D_
_x000D_
/**_x000D_
* An axis tick._x000D_
*/_x000D_
public class AxisTick implements IAxisTick {_x000D_
_x000D_
/** the chart */_x000D_
private Chart chart;_x000D_
/** the axis */_x000D_
private Axis axis;_x000D_
/** the axis tick labels */_x000D_
private AxisTickLabels axisTickLabels;_x000D_
/** the axis tick marks */_x000D_
private AxisTickMarks axisTickMarks;_x000D_
/** true if tick is visible */_x000D_
private boolean isVisible;_x000D_
/** the tick mark step hint */_x000D_
private int tickMarkStepHint;_x000D_
/** the tick label angle in degree */_x000D_
private int tickLabelAngle;_x000D_
/** the default tick mark step hint */_x000D_
private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_
_x000D_
/**_x000D_
* Constructor._x000D_
*_x000D_
* @param chart_x000D_
* the chart_x000D_
* @param axis_x000D_
* the axis_x000D_
*/_x000D_
protected AxisTick(Chart chart, Axis axis) {_x000D_
this.chart = chart;_x000D_
this.axis = axis;_x000D_
axisTickLabels = new AxisTickLabels(chart, axis);_x000D_
axisTickMarks = new AxisTickMarks(chart, axis);_x000D_
isVisible = true;_x000D_
tickLabelAngle = 0;_x000D_
tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick marks._x000D_
*_x000D_
* @return the axis tick marks_x000D_
*/_x000D_
public AxisTickMarks getAxisTickMarks() {_x000D_
_x000D_
return axisTickMarks;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Gets the axis tick labels._x000D_
*_x000D_
* @return the axis tick labels_x000D_
*/_x000D_
public AxisTickLabels getAxisTickLabels() {_x000D_
_x000D_
return axisTickLabels;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setForeground(Color)_x000D_
*/_x000D_
public void setForeground(Color color) {_x000D_
_x000D_
if(color != null && color.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickMarks.setForeground(color);_x000D_
axisTickLabels.setForeground(color);_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getForeground()_x000D_
*/_x000D_
public Color getForeground() {_x000D_
_x000D_
return axisTickMarks.getForeground();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFont(Font)_x000D_
*/_x000D_
public void setFont(Font font) {_x000D_
_x000D_
if(font != null && font.isDisposed()) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
axisTickLabels.setFont(font);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFont()_x000D_
*/_x000D_
public Font getFont() {_x000D_
_x000D_
return axisTickLabels.getFont();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#isVisible()_x000D_
*/_x000D_
public boolean isVisible() {_x000D_
_x000D_
return isVisible;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setVisible(boolean)_x000D_
*/_x000D_
public void setVisible(boolean isVisible) {_x000D_
_x000D_
this.isVisible = isVisible;_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickMarkStepHint()_x000D_
*/_x000D_
public int getTickMarkStepHint() {_x000D_
_x000D_
return tickMarkStepHint;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickMarkStepHint(int)_x000D_
*/_x000D_
public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_
_x000D_
if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_
this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_
} else {_x000D_
this.tickMarkStepHint = tickMarkStepHint;_x000D_
}_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelAngle()_x000D_
*/_x000D_
public int getTickLabelAngle() {_x000D_
_x000D_
return tickLabelAngle;_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setTickLabelAngle(int)_x000D_
*/_x000D_
public void setTickLabelAngle(int angle) {_x000D_
_x000D_
if(angle < 0 || 90 < angle) {_x000D_
SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_
}_x000D_
if(tickLabelAngle != angle) {_x000D_
tickLabelAngle = angle;_x000D_
chart.updateLayout();_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#setFormat(Format)_x000D_
*/_x000D_
public void setFormat(Format format) {_x000D_
_x000D_
axisTickLabels.setFormat(format);_x000D_
chart.updateLayout();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getFormat()_x000D_
*/_x000D_
public Format getFormat() {_x000D_
_x000D_
return axisTickLabels.getFormat();_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getBounds()_x000D_
<SUF>*/_x000D_
public Rectangle getBounds() {_x000D_
_x000D_
Rectangle r1 = axisTickMarks.getBounds();_x000D_
Rectangle r2 = axisTickLabels.getBounds();_x000D_
Position position = axis.getPosition();_x000D_
if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_
} else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_
return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_
} else {_x000D_
throw new IllegalStateException("unknown axis position");_x000D_
}_x000D_
}_x000D_
_x000D_
/*_x000D_
* @see IAxisTick#getTickLabelValues()_x000D_
*/_x000D_
public double[] getTickLabelValues() {_x000D_
_x000D_
List<Double> list = axisTickLabels.getTickLabelValues();_x000D_
double[] values = new double[list.size()];_x000D_
for(int i = 0; i < values.length; i++) {_x000D_
values[i] = list.get(i);_x000D_
}_x000D_
return values;_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick around per 64 pixel._x000D_
*_x000D_
* @param length_x000D_
* the axis length_x000D_
*/_x000D_
public void updateTick(int length) {_x000D_
_x000D_
if(length <= 0) {_x000D_
axisTickLabels.update(1);_x000D_
} else {_x000D_
axisTickLabels.update(length);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Updates the tick layout._x000D_
*/_x000D_
protected void updateLayoutData() {_x000D_
_x000D_
axisTickLabels.updateLayoutData();_x000D_
axisTickMarks.updateLayoutData();_x000D_
}_x000D_
}_x000D_
| False |
3,910 | 189584_1 | package com.rs.utilities;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The container class that contains functions to simplify the modification of a
* number.
* <p>
* <p>
* This class is similar in functionality to {@link AtomicInteger} but does not
* support atomic operations, and therefore should not be used across multiple
* threads.
* @author lare96 <http://github.com/lare96>
*/
public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare code, echt ongelofelijk dit
/**
* The constant serial version UID for serialization.
*/
private static final long serialVersionUID = -7475363158492415879L;
/**
* The value present within this counter.
*/
private int value;
/**
* Creates a new {@link MutableNumber} with {@code value}.
* @param value the value present within this counter.
*/
public MutableNumber(int value) {
this.value = value;
}
/**
* Creates a new {@link MutableNumber} with a value of {@code 0}.
*/
public MutableNumber() {
this(0);
}
@Override
public String toString() {
return Integer.toString(value);
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof MutableNumber))
return false;
MutableNumber other = (MutableNumber) obj;
return value == other.value;
}
@Override
public int compareTo(MutableNumber o) {
return Integer.compare(value, o.value);
}
/**
* {@inheritDoc}
* <p>
* This function equates to the {@link MutableNumber#get()} function.
*/
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return (long) value;
}
@Override
public float floatValue() {
return (float) value;
}
@Override
public double doubleValue() {
return (double) value;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount} to a maximum of {@code maximum}.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount, int maximum) {
int val = value;
value += amount;
if(value > maximum)
value = maximum;
return val;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount}.
* @param amount the amount to increment it by.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount) {
return getAndIncrement(amount, Integer.MAX_VALUE);
}
/**
* Returns the value within this counter and then increments it by an amount
* of {@code 1}.
* @return the value before it is incremented.
*/
public int getAndIncrement() {
return getAndIncrement(1);
}
//guys I have to go, it's me stan
//It's taraweeh time, gonna go pray and come back
//u guys can stay on teamviewer just shut it down when ur done, ill
//tell my mom not to close the laptop
//just dont do stupid stuff please xD ok -at rtnp ty <3
/**
* Increments the value within this counter by {@code amount} to a maximum
* of {@code maximum} and then returns it.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount, int maximum) {
value += amount;
if(value > maximum)
value = maximum;
return value;
}
/**
* Increments the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to increment it by.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount) {
return incrementAndGet(amount, Integer.MAX_VALUE);
}
/**
* Increments the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is incremented.
*/
public int incrementAndGet() {
return incrementAndGet(1);
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount} to a minimum of {@code minimum}.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount, int minimum) {
int val = value;
value -= amount;
if(value < minimum)
value = minimum;
return val;
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount}.
* @param amount the amount to decrement it by.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount) {
return getAndDecrement(amount, Integer.MIN_VALUE);
}
/**
* Returns the value within this counter and then decrements it by an amount
* of {@code 1}.
* @return the value before it is decremented.
*/
public int getAndDecrement() {
return getAndDecrement(1);
}
/**
* Decrements the value within this counter by {@code amount} to a minimum
* of {@code minimum} and then returns it.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount, int minimum) {
value -= amount;
if(value < minimum)
value = minimum;
return value;
}
/**
* Decrements the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to decrement it by.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount) {
return decrementAndGet(amount, Integer.MIN_VALUE);
}
/**
* Decrements the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is decremented.
*/
public int decrementAndGet() {
return decrementAndGet(1);
}
/**
* Gets the value present within this counter. This function equates to the
* inherited {@link MutableNumber#intValue()} function.
* @return the value present.
*/
public int get() {
return value;
}
/**
* Sets the value within this container to {@code value}.
* @param value the new value to set.
*/
public void set(int value) {
this.value = value;
}
}
| openrsx/open633-server | src/com/rs/utilities/MutableNumber.java | 1,978 | // pure lare code, echt ongelofelijk dit | line_comment | nl | package com.rs.utilities;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The container class that contains functions to simplify the modification of a
* number.
* <p>
* <p>
* This class is similar in functionality to {@link AtomicInteger} but does not
* support atomic operations, and therefore should not be used across multiple
* threads.
* @author lare96 <http://github.com/lare96>
*/
public final class MutableNumber extends Number implements Comparable<MutableNumber> { // pure lare<SUF>
/**
* The constant serial version UID for serialization.
*/
private static final long serialVersionUID = -7475363158492415879L;
/**
* The value present within this counter.
*/
private int value;
/**
* Creates a new {@link MutableNumber} with {@code value}.
* @param value the value present within this counter.
*/
public MutableNumber(int value) {
this.value = value;
}
/**
* Creates a new {@link MutableNumber} with a value of {@code 0}.
*/
public MutableNumber() {
this(0);
}
@Override
public String toString() {
return Integer.toString(value);
}
@Override
public int hashCode() {
return Integer.hashCode(value);
}
@Override
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(!(obj instanceof MutableNumber))
return false;
MutableNumber other = (MutableNumber) obj;
return value == other.value;
}
@Override
public int compareTo(MutableNumber o) {
return Integer.compare(value, o.value);
}
/**
* {@inheritDoc}
* <p>
* This function equates to the {@link MutableNumber#get()} function.
*/
@Override
public int intValue() {
return value;
}
@Override
public long longValue() {
return (long) value;
}
@Override
public float floatValue() {
return (float) value;
}
@Override
public double doubleValue() {
return (double) value;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount} to a maximum of {@code maximum}.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount, int maximum) {
int val = value;
value += amount;
if(value > maximum)
value = maximum;
return val;
}
/**
* Returns the value within this counter and then increments it by
* {@code amount}.
* @param amount the amount to increment it by.
* @return the value before it is incremented.
*/
public int getAndIncrement(int amount) {
return getAndIncrement(amount, Integer.MAX_VALUE);
}
/**
* Returns the value within this counter and then increments it by an amount
* of {@code 1}.
* @return the value before it is incremented.
*/
public int getAndIncrement() {
return getAndIncrement(1);
}
//guys I have to go, it's me stan
//It's taraweeh time, gonna go pray and come back
//u guys can stay on teamviewer just shut it down when ur done, ill
//tell my mom not to close the laptop
//just dont do stupid stuff please xD ok -at rtnp ty <3
/**
* Increments the value within this counter by {@code amount} to a maximum
* of {@code maximum} and then returns it.
* @param amount the amount to increment it by.
* @param maximum the maximum amount it will be incremented to.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount, int maximum) {
value += amount;
if(value > maximum)
value = maximum;
return value;
}
/**
* Increments the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to increment it by.
* @return the value after it is incremented.
*/
public int incrementAndGet(int amount) {
return incrementAndGet(amount, Integer.MAX_VALUE);
}
/**
* Increments the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is incremented.
*/
public int incrementAndGet() {
return incrementAndGet(1);
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount} to a minimum of {@code minimum}.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount, int minimum) {
int val = value;
value -= amount;
if(value < minimum)
value = minimum;
return val;
}
/**
* Returns the value within this counter and then decrements it by
* {@code amount}.
* @param amount the amount to decrement it by.
* @return the value before it is decremented.
*/
public int getAndDecrement(int amount) {
return getAndDecrement(amount, Integer.MIN_VALUE);
}
/**
* Returns the value within this counter and then decrements it by an amount
* of {@code 1}.
* @return the value before it is decremented.
*/
public int getAndDecrement() {
return getAndDecrement(1);
}
/**
* Decrements the value within this counter by {@code amount} to a minimum
* of {@code minimum} and then returns it.
* @param amount the amount to decrement it by.
* @param minimum the minimum amount it will be decremented to.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount, int minimum) {
value -= amount;
if(value < minimum)
value = minimum;
return value;
}
/**
* Decrements the value within this counter by {@code amount} and then
* returns it.
* @param amount the amount to decrement it by.
* @return the value after it is decremented.
*/
public int decrementAndGet(int amount) {
return decrementAndGet(amount, Integer.MIN_VALUE);
}
/**
* Decrements the value within this counter by {@code 1} and then returns
* it.
* @return the value after it is decremented.
*/
public int decrementAndGet() {
return decrementAndGet(1);
}
/**
* Gets the value present within this counter. This function equates to the
* inherited {@link MutableNumber#intValue()} function.
* @return the value present.
*/
public int get() {
return value;
}
/**
* Sets the value within this container to {@code value}.
* @param value the new value to set.
*/
public void set(int value) {
this.value = value;
}
}
| False |
1,381 | 164975_11 |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class LevelSaturn extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class LevelSaturn.
*
*/
public LevelSaturn() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("CaveBG.png");
int[][] map = {
{572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,510,587,587,587,587,587,5,5,5,5,5,5,5,5,5,586,587,587,587,587,587,587,587,587,587,587,587,587,587,587,576,-1,-1,-1,-1,572},
{572,576,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,510,582,572,572,572,572,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,576,-1,574,582,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,579,581,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,574,576,-1,572,-1,574,576,-1,572,-1,-1,-1,-1,-1,-1,-1,587,587,587,587,587,587,587,587,587,576,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,581,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,576,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,578,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,578,-1,-1,-1,-1,-1,572,581,-1,-1,579,572,581,-1,-1,579,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,574,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,587,587,587,587,472,587,587,572,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,579,581,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,574,576,-1,572,-1,574,576,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,574,587,587,587,587,572,-1,-1,-1,-1,-1,572},
{572,-1,579,580,581,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,579,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,581,-1,-1,579,572,581,-1,-1,579,572,587,587,587,587,587,587,587,587,587,587,587,587,587,587,587,572,587,587,587,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,579,580,581,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,580,580,580,580,581,-1,-1,-1,572,587,587,587,587,587,587,587,587,587,587,588,-1,-1,-1,572,-1,-1,-1,-1,-1,509,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,510,587,587,587,587,587,587,587,587,587,587,587,587,587,587,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,510,582,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,587,587,587,587,587,587,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,587,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,572,572,572,572,572,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,572,572,572,572,572,572,-1,-1,-1,-1,-1,572,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,510,587,-1,-1,-1,587,511,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,587,587,587,572,572,572,572,572,572,587,587,587,587,587,572,572,587,587,587,587,587,587,587,587,587,587,587,587,587,587,587,582,572,572,572,572,572,583,587,587,587,587,587,587,587,587,587,587,572},
{572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 155, 1630);
addObject(new Enemy(), 1020, 515);
// Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen.
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| ROCMondriaanTIN/project-greenfoot-game-Keesvdk | LevelSaturn.java | 3,625 | // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. | line_comment | nl |
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
*
* @author R. Springer
*/
public class LevelSaturn extends World {
private CollisionEngine ce;
/**
* Constructor for objects of class LevelSaturn.
*
*/
public LevelSaturn() {
// Create a new world with 600x400 cells with a cell size of 1x1 pixels.
super(1000, 800, 1, false);
this.setBackground("CaveBG.png");
int[][] map = {
{572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,510,587,587,587,587,587,5,5,5,5,5,5,5,5,5,586,587,587,587,587,587,587,587,587,587,587,587,587,587,587,576,-1,-1,-1,-1,572},
{572,576,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,510,582,572,572,572,572,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,576,-1,574,582,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,579,581,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,574,576,-1,572,-1,574,576,-1,572,-1,-1,-1,-1,-1,-1,-1,587,587,587,587,587,587,587,587,587,576,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,581,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,576,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,578,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,578,-1,-1,-1,-1,-1,572,581,-1,-1,579,572,581,-1,-1,579,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,574,572,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,587,587,587,587,472,587,587,572,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,579,581,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,574,576,-1,572,-1,574,576,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,574,587,587,587,587,572,-1,-1,-1,-1,-1,572},
{572,-1,579,580,581,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,579,572,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,471,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,581,-1,-1,579,572,581,-1,-1,579,572,587,587,587,587,587,587,587,587,587,587,587,587,587,587,587,572,587,587,587,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,579,580,581,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,574,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,580,580,580,580,581,-1,-1,-1,572,587,587,587,587,587,587,587,587,587,587,588,-1,-1,-1,572,-1,-1,-1,-1,-1,509,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,-1,510,587,587,587,587,587,587,587,587,587,587,587,587,587,587,572,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,572,-1,-1,510,582,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,587,587,587,587,587,587,-1,-1,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,587,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,572,572,572,572,572,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,-1,-1,-1,572,572,572,572,572,572,-1,-1,-1,-1,-1,572,572,-1,-1,-1,-1,-1,-1,572,-1,-1,-1,-1,-1,-1,-1,-1,510,587,-1,-1,-1,587,511,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,572},
{572,587,587,587,572,572,572,572,572,572,587,587,587,587,587,572,572,587,587,587,587,587,587,587,587,587,587,587,587,587,587,587,582,572,572,572,572,572,583,587,587,587,587,587,587,587,587,587,587,572},
{572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572,572},
};
// Declareren en initialiseren van de TileEngine klasse om de map aan de world toe te voegen
TileEngine te = new TileEngine(this, 60, 60, map);
// Declarenre en initialiseren van de camera klasse met de TileEngine klasse
// zodat de camera weet welke tiles allemaal moeten meebewegen met de camera
Camera camera = new Camera(te);
// Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse
// moet de klasse Mover extenden voor de camera om te werken
Hero hero = new Hero();
// Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan.
camera.follow(hero);
// Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies
addObject(camera, 0, 0);
addObject(hero, 155, 1630);
addObject(new Enemy(), 1020, 515);
// Initialiseren van<SUF>
// De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan.
ce = new CollisionEngine(te, camera);
// Toevoegen van de mover instantie of een extentie hiervan
ce.addCollidingMover(hero);
}
@Override
public void act() {
ce.update();
}
}
| True |
1,669 | 30811_1 | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface)
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| SweerenK/sjoelclub | src/main/java/nl/sjoelclub/competitie/score/ScoreService.java | 221 | //Verbinding tussen repository en service. Zorgt ervoor dat je een object van Repository tot beschikking hebt (eigenlijk interface) | line_comment | nl | package nl.sjoelclub.competitie.score;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@Transactional //Mag operaties op de database doen.
public class ScoreService {
@Autowired //Verbinding tussen<SUF>
private ScoreRepository scoreRepository;
public Score save(Score score) {
return scoreRepository.save(score);
}
public Iterable<Score> findAll() { //Iterable is een verzameling op het hoogste niveau. Doorheenloopbaar.
Iterable<Score> result = scoreRepository.findAll();
return result;
}
}
| True |
4,124 | 37735_6 | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume game als er al een game in het spel is!_x000D_
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| rayzorg/regenworm | src/gui/Startscherm.java | 1,569 | // Enkel resume game als er al een game in het spel is!_x000D_ | line_comment | nl | /*_x000D_
* To change this license header, choose License Headers in Project Properties._x000D_
* To change this template file, choose Tools | Templates_x000D_
* and open the template in the editor._x000D_
*/_x000D_
package gui;_x000D_
_x000D_
import domein.DomeinController;_x000D_
import javafx.event.ActionEvent;_x000D_
import javafx.event.EventHandler;_x000D_
import javafx.geometry.Insets;_x000D_
import javafx.geometry.Pos;_x000D_
import javafx.scene.Scene;_x000D_
import javafx.scene.control.Button;_x000D_
import javafx.scene.layout.BorderPane;_x000D_
import javafx.scene.layout.GridPane;_x000D_
import javafx.stage.Stage;_x000D_
_x000D_
_x000D_
/**_x000D_
*_x000D_
* @author bjorn_x000D_
*/_x000D_
public class Startscherm extends BorderPane {_x000D_
_x000D_
private final DomeinController dc;_x000D_
_x000D_
public Startscherm(DomeinController dc) {_x000D_
this.dc = dc;_x000D_
buildGui();_x000D_
}_x000D_
_x000D_
private void buildGui(){_x000D_
_x000D_
_x000D_
_x000D_
//Panes/Boxes/CSS ********************************************************************* _x000D_
getStylesheets().add("/css/startscherm.css");_x000D_
GridPane gpane = new GridPane();_x000D_
//setCancelDefault fzoiets vr via escape terug naar vorig scherm_x000D_
_x000D_
//Start button ************************************************************************ _x000D_
_x000D_
Button btnStart = new Button();_x000D_
btnStart.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnStartOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnStart.setId("btnStart");_x000D_
btnStart.setPrefSize(200, 50);_x000D_
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Resume button ************************************************************************ _x000D_
// Enkel resume<SUF>
Button btnResume = new Button();_x000D_
btnResume.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnResumeOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnResume.setDisable(true);_x000D_
btnResume.setId("btnResume");_x000D_
btnResume.setPrefSize(200, 50);_x000D_
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Highscores button ************************************************************************ _x000D_
Button btnHighScores = new Button();_x000D_
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnHighscoresOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnHighScores.setId("btnHighScores");_x000D_
btnHighScores.setPrefSize(200, 50);_x000D_
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
_x000D_
//Rules button ************************************************************************ _x000D_
Button btnGameRules = new Button();_x000D_
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {_x000D_
@Override_x000D_
public void handle(ActionEvent ae) {_x000D_
btnGameRulesOnAction(ae);_x000D_
}_x000D_
});_x000D_
_x000D_
btnGameRules.setId("btnGameRules");_x000D_
btnGameRules.setPrefSize(200, 50);_x000D_
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));_x000D_
_x000D_
//Centering van de Gridpane ***************************************************************_x000D_
_x000D_
gpane.add(btnStart, 0, 0);_x000D_
gpane.add(btnResume, 0, 1);_x000D_
gpane.add(btnHighScores, 0, 2);_x000D_
gpane.add(btnGameRules, 0, 3);_x000D_
gpane.setAlignment(Pos.CENTER);_x000D_
gpane.setPadding(new Insets(50,5,5,5));_x000D_
gpane.setHgap(1);_x000D_
gpane.setVgap(1);_x000D_
setCenter(gpane);_x000D_
_x000D_
}_x000D_
_x000D_
private void btnStartOnAction(ActionEvent event)_x000D_
{_x000D_
//dc.deleteData() = mogelijke methode om nieuw spel te starten_x000D_
SpelersSettings ss = new SpelersSettings(this, dc);_x000D_
Scene scene = new Scene(ss, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
private void btnHighscoresOnAction(ActionEvent event)_x000D_
{_x000D_
HighscoreScherm hs = new HighscoreScherm(this, dc);_x000D_
Scene scene = new Scene(hs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
private void btnResumeOnAction(ActionEvent event)_x000D_
{/*_x000D_
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken_x000D_
dc.vulDomein();_x000D_
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);_x000D_
Scene scene = new Scene(overzichtscherm,1250,700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
*/_x000D_
}_x000D_
_x000D_
private void btnGameRulesOnAction(ActionEvent event)_x000D_
{_x000D_
GameRulesScherm grs = new GameRulesScherm(this, dc);_x000D_
Scene scene = new Scene(grs, 1250, 700);_x000D_
Stage stage = (Stage) this.getScene().getWindow();_x000D_
stage.setScene(scene);_x000D_
stage.show(); _x000D_
}_x000D_
}_x000D_
| True |
4,778 | 109270_2 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.deals;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int Detail_horizontal_margin=0x7f050004;
public static final int Detail_vertical_margin=0x7f050005;
/**
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f05000d;
public static final int coupon_horizontal_margin=0x7f050002;
public static final int coupon_vertical_margin=0x7f050003;
public static final int favor_vertical_margin=0x7f050007;
public static final int fbtwitter_horizontal_margin=0x7f050009;
public static final int fbtwitter_vertical_margin=0x7f05000a;
public static final int messagebox_horizontal_margin=0x7f05000b;
public static final int messagebox_vertical_margin=0x7f05000c;
public static final int redeem_text_vertical_margin=0x7f050008;
public static final int redeem_vertical_margin=0x7f050006;
/** Default screen margins, per the Android Design guidelines.
*/
public static final int tiles_horizontal_margin=0x7f050000;
public static final int tiles_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int back=0x7f020000;
public static final int background=0x7f020001;
public static final int box=0x7f020002;
public static final int box_signin_email=0x7f020003;
public static final int btn_fb=0x7f020004;
public static final int btn_fb_normal=0x7f020005;
public static final int btn_fb_pressed=0x7f020006;
public static final int couponcapitano=0x7f020007;
public static final int couponcastile=0x7f020008;
public static final int couponrexall=0x7f020009;
public static final int couponsushiworld=0x7f02000a;
public static final int coupontopsushi=0x7f02000b;
public static final int detailsbutton=0x7f02000c;
public static final int facebookbutton=0x7f02000d;
public static final int favicon=0x7f02000e;
public static final int favouritebutton=0x7f02000f;
public static final int fbiconoff=0x7f020010;
public static final int fbiconon=0x7f020011;
public static final int ic_launcher=0x7f020012;
public static final int logo=0x7f020013;
public static final int messageboxgray=0x7f020014;
public static final int navigationbar=0x7f020015;
public static final int redeembutton=0x7f020016;
public static final int redeemgreenicon=0x7f020017;
public static final int removefavbutton=0x7f020018;
public static final int search=0x7f020019;
public static final int splash=0x7f02001a;
public static final int takephotobutton=0x7f02001b;
public static final int textbox=0x7f02001c;
public static final int tile10=0x7f02001d;
public static final int twitterbutton=0x7f02001e;
public static final int twittericonoff=0x7f02001f;
public static final int twittericonon=0x7f020020;
}
public static final class id {
public static final int TextLayout=0x7f090005;
public static final int action_settings=0x7f090043;
public static final int bBack=0x7f090001;
public static final int bFavor=0x7f09000f;
public static final int bRedeem=0x7f09000a;
public static final int bSearch=0x7f09002b;
public static final int bStore=0x7f09000d;
public static final int bar=0x7f090000;
public static final int browser=0x7f090002;
public static final int btnFbSignIn=0x7f090011;
public static final int btnLoginTweet=0x7f090032;
public static final int btnSearch=0x7f090036;
public static final int btnTweet=0x7f090035;
public static final int buttonLayout=0x7f090008;
public static final int cbFacebook=0x7f090025;
public static final int cbFbAutoLogin=0x7f090012;
public static final int cbTwitter=0x7f090024;
public static final int detailFavorLayout=0x7f09000b;
public static final int detailLayout=0x7f09000c;
public static final int etEmail=0x7f090010;
public static final int etMessageBox=0x7f090028;
public static final int etSearch=0x7f090015;
public static final int etTweet=0x7f090034;
public static final int favorLayout=0x7f09000e;
public static final int highlight=0x7f09003a;
public static final int hyphen=0x7f09003d;
public static final int ivPhoto=0x7f090022;
public static final int ivRedeemButton=0x7f090023;
public static final int ivStore=0x7f090003;
public static final int ivTakePhoto=0x7f09002a;
public static final int ivTwitterUserImg=0x7f09003f;
public static final int ivc=0x7f090004;
public static final int layoutTwitter=0x7f090033;
public static final int lvEvents=0x7f090038;
public static final int lvTweets=0x7f090037;
public static final int redeemLayout=0x7f090009;
public static final int spDate=0x7f090013;
public static final int t1=0x7f090016;
public static final int t10=0x7f09001f;
public static final int t11=0x7f090020;
public static final int t12=0x7f090021;
public static final int t13=0x7f09002c;
public static final int t14=0x7f09002d;
public static final int t15=0x7f09002e;
public static final int t16=0x7f09002f;
public static final int t17=0x7f090030;
public static final int t18=0x7f090031;
public static final int t2=0x7f090017;
public static final int t3=0x7f090018;
public static final int t4=0x7f090019;
public static final int t5=0x7f09001a;
public static final int t6=0x7f09001b;
public static final int t7=0x7f09001c;
public static final int t8=0x7f09001d;
public static final int t9=0x7f09001e;
public static final int tvDetail=0x7f090007;
public static final int tvEndTime_event=0x7f09003e;
public static final int tvHeader_event=0x7f090039;
public static final int tvMainDis=0x7f090006;
public static final int tvRedeem=0x7f090026;
public static final int tvStartTime_event=0x7f09003c;
public static final int tvTitle_event=0x7f09003b;
public static final int tvTwitterDate=0x7f090041;
public static final int tvTwitterTweet=0x7f090042;
public static final int tvTwitterUser=0x7f090040;
public static final int tvUnderCamera=0x7f090027;
public static final int tvUnderMessageBox=0x7f090029;
public static final int viewPager=0x7f090014;
}
public static final class layout {
public static final int activity_browser=0x7f030000;
public static final int activity_coupon=0x7f030001;
public static final int activity_login=0x7f030002;
public static final int activity_scheduler=0x7f030003;
public static final int activity_search_favor=0x7f030004;
public static final int activity_share=0x7f030005;
public static final int activity_splash=0x7f030006;
public static final int activity_tiles=0x7f030007;
public static final int activity_twitterfeed=0x7f030008;
public static final int fragment_day=0x7f030009;
public static final int item_list_event=0x7f03000a;
public static final int item_list_tweet=0x7f03000b;
public static final int item_spinner=0x7f03000c;
}
public static final class menu {
public static final int splash=0x7f080000;
}
public static final class raw {
public static final int coupons=0x7f040000;
public static final int jsondealsfile=0x7f040001;
public static final int show=0x7f040002;
public static final int tiles=0x7f040003;
}
public static final class string {
public static final int Details=0x7f060004;
public static final int action_settings=0x7f060001;
public static final int app_id=0x7f060006;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060002;
public static final int link=0x7f060003;
public static final int reedem_offer=0x7f060005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| yixiu17/Dealshype | gen/com/example/deals/R.java | 3,004 | /** Default screen margins, per the Android Design guidelines.
*/ | block_comment | nl | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.deals;
public final class R {
public static final class attr {
}
public static final class dimen {
public static final int Detail_horizontal_margin=0x7f050004;
public static final int Detail_vertical_margin=0x7f050005;
/**
Customize dimensions originally defined in res/values/dimens.xml (such as
screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
*/
public static final int activity_horizontal_margin=0x7f05000d;
public static final int coupon_horizontal_margin=0x7f050002;
public static final int coupon_vertical_margin=0x7f050003;
public static final int favor_vertical_margin=0x7f050007;
public static final int fbtwitter_horizontal_margin=0x7f050009;
public static final int fbtwitter_vertical_margin=0x7f05000a;
public static final int messagebox_horizontal_margin=0x7f05000b;
public static final int messagebox_vertical_margin=0x7f05000c;
public static final int redeem_text_vertical_margin=0x7f050008;
public static final int redeem_vertical_margin=0x7f050006;
/** Default screen margins,<SUF>*/
public static final int tiles_horizontal_margin=0x7f050000;
public static final int tiles_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int back=0x7f020000;
public static final int background=0x7f020001;
public static final int box=0x7f020002;
public static final int box_signin_email=0x7f020003;
public static final int btn_fb=0x7f020004;
public static final int btn_fb_normal=0x7f020005;
public static final int btn_fb_pressed=0x7f020006;
public static final int couponcapitano=0x7f020007;
public static final int couponcastile=0x7f020008;
public static final int couponrexall=0x7f020009;
public static final int couponsushiworld=0x7f02000a;
public static final int coupontopsushi=0x7f02000b;
public static final int detailsbutton=0x7f02000c;
public static final int facebookbutton=0x7f02000d;
public static final int favicon=0x7f02000e;
public static final int favouritebutton=0x7f02000f;
public static final int fbiconoff=0x7f020010;
public static final int fbiconon=0x7f020011;
public static final int ic_launcher=0x7f020012;
public static final int logo=0x7f020013;
public static final int messageboxgray=0x7f020014;
public static final int navigationbar=0x7f020015;
public static final int redeembutton=0x7f020016;
public static final int redeemgreenicon=0x7f020017;
public static final int removefavbutton=0x7f020018;
public static final int search=0x7f020019;
public static final int splash=0x7f02001a;
public static final int takephotobutton=0x7f02001b;
public static final int textbox=0x7f02001c;
public static final int tile10=0x7f02001d;
public static final int twitterbutton=0x7f02001e;
public static final int twittericonoff=0x7f02001f;
public static final int twittericonon=0x7f020020;
}
public static final class id {
public static final int TextLayout=0x7f090005;
public static final int action_settings=0x7f090043;
public static final int bBack=0x7f090001;
public static final int bFavor=0x7f09000f;
public static final int bRedeem=0x7f09000a;
public static final int bSearch=0x7f09002b;
public static final int bStore=0x7f09000d;
public static final int bar=0x7f090000;
public static final int browser=0x7f090002;
public static final int btnFbSignIn=0x7f090011;
public static final int btnLoginTweet=0x7f090032;
public static final int btnSearch=0x7f090036;
public static final int btnTweet=0x7f090035;
public static final int buttonLayout=0x7f090008;
public static final int cbFacebook=0x7f090025;
public static final int cbFbAutoLogin=0x7f090012;
public static final int cbTwitter=0x7f090024;
public static final int detailFavorLayout=0x7f09000b;
public static final int detailLayout=0x7f09000c;
public static final int etEmail=0x7f090010;
public static final int etMessageBox=0x7f090028;
public static final int etSearch=0x7f090015;
public static final int etTweet=0x7f090034;
public static final int favorLayout=0x7f09000e;
public static final int highlight=0x7f09003a;
public static final int hyphen=0x7f09003d;
public static final int ivPhoto=0x7f090022;
public static final int ivRedeemButton=0x7f090023;
public static final int ivStore=0x7f090003;
public static final int ivTakePhoto=0x7f09002a;
public static final int ivTwitterUserImg=0x7f09003f;
public static final int ivc=0x7f090004;
public static final int layoutTwitter=0x7f090033;
public static final int lvEvents=0x7f090038;
public static final int lvTweets=0x7f090037;
public static final int redeemLayout=0x7f090009;
public static final int spDate=0x7f090013;
public static final int t1=0x7f090016;
public static final int t10=0x7f09001f;
public static final int t11=0x7f090020;
public static final int t12=0x7f090021;
public static final int t13=0x7f09002c;
public static final int t14=0x7f09002d;
public static final int t15=0x7f09002e;
public static final int t16=0x7f09002f;
public static final int t17=0x7f090030;
public static final int t18=0x7f090031;
public static final int t2=0x7f090017;
public static final int t3=0x7f090018;
public static final int t4=0x7f090019;
public static final int t5=0x7f09001a;
public static final int t6=0x7f09001b;
public static final int t7=0x7f09001c;
public static final int t8=0x7f09001d;
public static final int t9=0x7f09001e;
public static final int tvDetail=0x7f090007;
public static final int tvEndTime_event=0x7f09003e;
public static final int tvHeader_event=0x7f090039;
public static final int tvMainDis=0x7f090006;
public static final int tvRedeem=0x7f090026;
public static final int tvStartTime_event=0x7f09003c;
public static final int tvTitle_event=0x7f09003b;
public static final int tvTwitterDate=0x7f090041;
public static final int tvTwitterTweet=0x7f090042;
public static final int tvTwitterUser=0x7f090040;
public static final int tvUnderCamera=0x7f090027;
public static final int tvUnderMessageBox=0x7f090029;
public static final int viewPager=0x7f090014;
}
public static final class layout {
public static final int activity_browser=0x7f030000;
public static final int activity_coupon=0x7f030001;
public static final int activity_login=0x7f030002;
public static final int activity_scheduler=0x7f030003;
public static final int activity_search_favor=0x7f030004;
public static final int activity_share=0x7f030005;
public static final int activity_splash=0x7f030006;
public static final int activity_tiles=0x7f030007;
public static final int activity_twitterfeed=0x7f030008;
public static final int fragment_day=0x7f030009;
public static final int item_list_event=0x7f03000a;
public static final int item_list_tweet=0x7f03000b;
public static final int item_spinner=0x7f03000c;
}
public static final class menu {
public static final int splash=0x7f080000;
}
public static final class raw {
public static final int coupons=0x7f040000;
public static final int jsondealsfile=0x7f040001;
public static final int show=0x7f040002;
public static final int tiles=0x7f040003;
}
public static final class string {
public static final int Details=0x7f060004;
public static final int action_settings=0x7f060001;
public static final int app_id=0x7f060006;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060002;
public static final int link=0x7f060003;
public static final int reedem_offer=0x7f060005;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| False |
3,536 | 136342_19 | import java.util.*;
public class IntStack {
int[] stack;
int top;
public IntStack(int size) {
top=0;
stack = new int[size];
}
public void print() {
for(int i=0; i<top; i++){
System.out.println(stack[(top-1)-i]);
}
}
boolean isEmpty() {
//top==0 returns true or false
return top==0;
}
void push(int num) {
//++ happens after (does at the end of the line)
stack[top++]=num;
}
int pop() {
//--happens before and changes top only if there is something left to pop
if(isEmpty()==false){
return stack[--top];
}
return -1;
}
//Alia
int depth(){
//returns the depth, same as top
int depth = top;
return depth;
}
//Alia
/* int[] popfrompoint(int popoint){
// pop all from point that is input
int i = 0;
int[] popped = new int[top- popoint];
while (top > popoint){
popped[i++] = stack[top--];
}
// print the array
for (int b = 1; b < popped.length; b++){
System.out.print(popped[b] + " ");
}
System.out.println();
return popped;
}
*/
int peek(){
return stack[top-1];
}
IntStack reverseStack(){
//make a newStack thats empty
IntStack newStack = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = pop(); //pop the top item and push that onto the newStack
newStack.push(p);
}
return newStack; //return newStack
}
IntStack sort() {
//create two new empty stacks
IntStack newStack1 = new IntStack(stack.length);
IntStack newStack2 = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = peek(); //peek top number of original stack
if(p<5){ //if its less than five, pop it and push it onto the first new stack
newStack1.push(p);
}
else { //if its greater than or equal to five, pop it and push it onto the second new stack
newStack2.push(p);
}
}
newStack1.push(newStack2.pop()); //pop the top number of the second new stack and push it onto the first new stack
return newStack1;
}
int[] popAll() {
//make array of size top, fill that with all items in stack, and then return the array
int[] popAll = new int[top];
for(int i = 0; !isEmpty(); i++)
{
popAll[i]= pop();
System.out.println(popAll[i]);
}
return popAll;
}
int[] ascend() {
int[] ascend = new int[top];
ascend = popAll();
Arrays.sort(ascend);
return ascend;
}
int[] descend() {
int[] descend = new int[top];
descend = popAll();
Arrays.sort(descend);
reverse(descend);
return descend;
}
//peak all the values in the stack
int[] peekAll() {
//fill new int array peakAll with length stack.length
int[] peekAll = new int[stack.length];
//fill peakAll with values of stack[], stopping before "top" of stack
for(int i=0; i<top; i++) {
peekAll[i] = stack[i];
}
//return created stack
return peekAll;
}
//peek certain value in stack
int peekAt(int position) {
//returns zero if you peek value that is at or above top
if(position>=top) return 0;
//return the position
return stack[position];
}
//taken from stackoverflow
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
public static void main(String[] args) {
IntStack is = new IntStack(10);
//push things in stack
is.push(4);
is.push(5);
is.push(8);
is.push(7);
is.push(8);
is.push(3);
is.push(4);
int k = is.pop();
System.out.println(k);
//Rachel -- reverse stack
IntStack is_rev = is.reverseStack();
int bottom = is_rev.pop();
System.out.println(bottom);
//Rachel -- sort
IntStack is_sort = is.sort();
is_sort.print();
//testing peek all method
int[] mm = is.peekAll();
System.out.println(Arrays.toString(mm));
//testing peek at position 2
int p = is.peekAt(2);
System.out.println(p);
// tests for depth:
int d = is.depth();
System.out.println(d);
//tests for pop from point: this pops all of them out of the array until there are only the number you choose left
//is.popfrompoint(2);
//peek all
int[] mmm = is.peekAll();
System.out.println(Arrays.toString(mmm));
//restoring stack
is.push(7);
is.push(5);
is.push(3);
is.push(2);
//peek all
int[] mmmm = is.peekAll();
System.out.println(Arrays.toString(mmmm));
//tests for popall:
is.push(4);
is.push(5);
is.push(6);
int[] j = is.popAll(); //i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(j));
// test for ascend
is.push(4);
is.push(5);
is.push(6);
int[] l = is.ascend(); // i expect an array of size 3 with 4,5,6
System.out.println(Arrays.toString(l));
//test for descend
is.push(4);
is.push(5);
is.push(6);
int[] m = is.descend(); // i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(m));
}
}
| maguerosinclair/stack | IntStack.java | 1,880 | //peek certain value in stack | line_comment | nl | import java.util.*;
public class IntStack {
int[] stack;
int top;
public IntStack(int size) {
top=0;
stack = new int[size];
}
public void print() {
for(int i=0; i<top; i++){
System.out.println(stack[(top-1)-i]);
}
}
boolean isEmpty() {
//top==0 returns true or false
return top==0;
}
void push(int num) {
//++ happens after (does at the end of the line)
stack[top++]=num;
}
int pop() {
//--happens before and changes top only if there is something left to pop
if(isEmpty()==false){
return stack[--top];
}
return -1;
}
//Alia
int depth(){
//returns the depth, same as top
int depth = top;
return depth;
}
//Alia
/* int[] popfrompoint(int popoint){
// pop all from point that is input
int i = 0;
int[] popped = new int[top- popoint];
while (top > popoint){
popped[i++] = stack[top--];
}
// print the array
for (int b = 1; b < popped.length; b++){
System.out.print(popped[b] + " ");
}
System.out.println();
return popped;
}
*/
int peek(){
return stack[top-1];
}
IntStack reverseStack(){
//make a newStack thats empty
IntStack newStack = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = pop(); //pop the top item and push that onto the newStack
newStack.push(p);
}
return newStack; //return newStack
}
IntStack sort() {
//create two new empty stacks
IntStack newStack1 = new IntStack(stack.length);
IntStack newStack2 = new IntStack(stack.length);
while (! isEmpty()){ //repeat until isEmpty()
int p = peek(); //peek top number of original stack
if(p<5){ //if its less than five, pop it and push it onto the first new stack
newStack1.push(p);
}
else { //if its greater than or equal to five, pop it and push it onto the second new stack
newStack2.push(p);
}
}
newStack1.push(newStack2.pop()); //pop the top number of the second new stack and push it onto the first new stack
return newStack1;
}
int[] popAll() {
//make array of size top, fill that with all items in stack, and then return the array
int[] popAll = new int[top];
for(int i = 0; !isEmpty(); i++)
{
popAll[i]= pop();
System.out.println(popAll[i]);
}
return popAll;
}
int[] ascend() {
int[] ascend = new int[top];
ascend = popAll();
Arrays.sort(ascend);
return ascend;
}
int[] descend() {
int[] descend = new int[top];
descend = popAll();
Arrays.sort(descend);
reverse(descend);
return descend;
}
//peak all the values in the stack
int[] peekAll() {
//fill new int array peakAll with length stack.length
int[] peekAll = new int[stack.length];
//fill peakAll with values of stack[], stopping before "top" of stack
for(int i=0; i<top; i++) {
peekAll[i] = stack[i];
}
//return created stack
return peekAll;
}
//peek certain<SUF>
int peekAt(int position) {
//returns zero if you peek value that is at or above top
if(position>=top) return 0;
//return the position
return stack[position];
}
//taken from stackoverflow
public static void reverse(int[] data) {
for (int left = 0, right = data.length - 1; left < right; left++, right--) {
// swap the values at the left and right indices
int temp = data[left];
data[left] = data[right];
data[right] = temp;
}
}
public static void main(String[] args) {
IntStack is = new IntStack(10);
//push things in stack
is.push(4);
is.push(5);
is.push(8);
is.push(7);
is.push(8);
is.push(3);
is.push(4);
int k = is.pop();
System.out.println(k);
//Rachel -- reverse stack
IntStack is_rev = is.reverseStack();
int bottom = is_rev.pop();
System.out.println(bottom);
//Rachel -- sort
IntStack is_sort = is.sort();
is_sort.print();
//testing peek all method
int[] mm = is.peekAll();
System.out.println(Arrays.toString(mm));
//testing peek at position 2
int p = is.peekAt(2);
System.out.println(p);
// tests for depth:
int d = is.depth();
System.out.println(d);
//tests for pop from point: this pops all of them out of the array until there are only the number you choose left
//is.popfrompoint(2);
//peek all
int[] mmm = is.peekAll();
System.out.println(Arrays.toString(mmm));
//restoring stack
is.push(7);
is.push(5);
is.push(3);
is.push(2);
//peek all
int[] mmmm = is.peekAll();
System.out.println(Arrays.toString(mmmm));
//tests for popall:
is.push(4);
is.push(5);
is.push(6);
int[] j = is.popAll(); //i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(j));
// test for ascend
is.push(4);
is.push(5);
is.push(6);
int[] l = is.ascend(); // i expect an array of size 3 with 4,5,6
System.out.println(Arrays.toString(l));
//test for descend
is.push(4);
is.push(5);
is.push(6);
int[] m = is.descend(); // i expect an array of size 3 with 6,5,4
System.out.println(Arrays.toString(m));
}
}
| False |
3,191 | 107696_8 | package org.jcryptool.visual.aco.view;
import java.awt.Point;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.jcryptool.visual.aco.controller.AntColEventController;
import org.jcryptool.visual.aco.model.CommonModel;
public class AntColGraphComposite extends Composite {
private static final int KNOTRADIUS = 120;
private static final int ANTRADIUS = 90;
private CommonModel m;
private Canvas canv;
private int x; // Position Ameise
private int y;
private int x2; // Ziel Ameise
private int y2;
private boolean isAnimationRunning = false;
private final Color highlightColor = new Color(this.getDisplay(), 100, 190,
0);
private Color normalColor = new Color(this.getDisplay(), 50, 120, 50);
private Color antColor = new Color(this.getDisplay(), 139, 90, 40);
private Color eyeColor = new Color(this.getDisplay(), 255, 255, 255);
private AntColEventController controller;
/**
* Konstruktor erhaelt Model und Parent.
*
* @param model
* @param c
*/
public AntColGraphComposite(CommonModel model, Composite c) {
super(c, SWT.NONE);
this.m = model;
setLayout(new GridLayout(1, false));
redraw();
}
public void redraw() {
super.redraw();
// visualisierung nur zeigen, wenn die schlüssellänge zwischen 3 und 5
// ist.
if (canv != null) {
canv.dispose();
}
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.widthHint = 365;
// data.heightHint = 365;
canv = new Canvas(this, SWT.NONE);
canv.setLayoutData(data);
// Listener, der festlegt was geschieht wenn redraw aufgerufen wird
canv.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// Fall: Entschluesselung darstellen
drawKnots(e); // Graph zeichnen
if (m.getState() != 0) {
drawAllPropabilities(e);
drawTrail(e);
// if (m.isAnimateable()) // Ameise zeichnen
drawAnt(e, new Point(x, y), new Point(x2, y2));
}
}
});
setAnt();
layout();
}
public void animationStep() {
final Display d = this.getDisplay();
x2 = getAntCoord(m.getKnot())[0];
y2 = getAntCoord(m.getKnot())[1];
// Schrittweite
isAnimationRunning = true;
final int diffx = (int) (Math.abs(x - x2) / 15 + 0.5);
final int diffy = (int) (Math.abs(y - y2) / 15 + 0.5);
// Thread, der Bewegung uebernimmt
Runnable runnable = new Runnable() {
public void run() {
// Schritt
if (x - x2 > 0)
x -= diffx;
else
x += diffx;
if (y - y2 > 0)
y -= diffy;
else
y += diffy;
if (Math.abs(x - x2) > 15 || Math.abs(y - y2) > 15) {
canv.redraw(); // neu zeichnen
d.timerExec(150, this); // Schleife
} else { // angekommen
setAnt();
canv.redraw(); // neu zeichnen
controller.afterGraphDrawn();
isAnimationRunning = false;
}
}
};
d.timerExec(1, runnable); // Starten
}
private void drawKnots(PaintEvent e) {
e.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
String[] knots = m.getKnots();
Vector<Integer> trail = m.getTrail();
for (int i = 0; i < knots.length; i++) {
int[] a = this.getKnotCoord(i);
drawKnot(e, knots[i], a[0], a[1], trail.contains(i), i + 1);
}
}
/**
* Zeichnet den von der Ameise zurueckgelegten Weg auf das Canvas
*
* @param e
* PaintEvent
*/
private void drawTrail(PaintEvent e) {
Vector<Integer> weg = m.getTrail();
if (weg.size() > 1) {
for (int i = 0; i < weg.size() - 1; i++) {
drawKante(e, weg.elementAt(i), weg.elementAt(i + 1));
}
}
}
public void drawAllPropabilities(PaintEvent e) {
String[] knots = m.getKnots();
double[] probs = m.getProbabilities(); // W'keiten holen
for(int i = 0; i < knots.length; i++){
int[] a = getKnotCoord(i);
drawPropability(e, a[0], a[1], probs[i]);
}
}
private void drawPropability(PaintEvent e, int x, int y, double prob) {
if (prob > 0) { // W'keit
String str = prob * 100 + ""; //$NON-NLS-1$
str = str.substring(0, str.indexOf('.') + 2) + " %"; //$NON-NLS-1$
if(y < 180){
y -= 43;
} else {
y += 32;
}
e.gc.setBackground(highlightColor);
e.gc.drawString(str, x-18, y);
}
}
/**
* Zeichnet eine Kante des Weges von Knoten i zu Knoten j;
*
* @param e
* PaintEvent
* @param i
* Knoten i
* @param j
* Knoten j
*/
private void drawKante(PaintEvent e, int i, int j) {
e.gc.setForeground(highlightColor);
int[] a = this.getKnotCoord(i);
int[] b = this.getKnotCoord(j);
e.gc.drawLine(a[0], a[1], b[0], b[1]);
}
/**
* Zeichnet einen Knoten bei den uebergebenen Koordinaten und mit dem
* uebergebenen Text, Nummer und Wahrscheinlichkeit auf das Canvas.
*
* @param e
* PaintEvent
* @param s
* Spalte die zum Knoten gehoert
* @param x
* x-Koordinate Knoten
* @param y
* y-Koordinate Knoten
* @param set
* Knoten bereits passiert?
* @param prob
* W'keit, dass Ameise zu diesem Knoten im naechsten Schritt geht
* @param nr
* Knotennummer
*/
private void drawKnot(PaintEvent e, String s, int x, int y, boolean set,
int nr) {
if (set) // wenn bereits passiert in gruen
e.gc.setBackground(highlightColor);
else
e.gc.setBackground(normalColor);
// Kreis und Nummer zeichnen
e.gc.fillOval(x - 32, y - 32, 65, 65);
e.gc.drawString(nr + "", x -22, y -12); //$NON-NLS-1$
if (s.length() > 5)
s = s.substring(0, 5);
for (int i = 0; i < s.length(); i++) { // Text
e.gc.drawString(
Character.toUpperCase(s.charAt(i)) + "", x, y + 12 * (i + 1) - 40); //$NON-NLS-1$
}
}
public void destroyGraph() {
canv.dispose();
}
/**
* Zeichnet eine Ameise beim Punkt p auf das Canvas mit Orientierung
* Richtung Punkt p2
*
* @param e
* PaintEvent
* @param p
* Ort der Ameise
* @param p2
* Orientierung der Ameise
*/
private void drawAnt(PaintEvent e, Point p, Point p2) {
Color col = antColor;
e.gc.setBackground(col);
e.gc.fillOval(p.x, p.y, 15, 15);
double x = p2.x - p.x;
double y = p2.y - p.y;
// Laenge Vektor
double n = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
x /= n;
y /= n;
// Rumpf
e.gc.fillOval((int) (p.x + 15 * x), (int) (p.y + 15 * y), 15, 15);
e.gc.fillOval((int) (p.x - 15 * x), (int) (p.y - 15 * y), 15, 15);
// Fuehler
col = new Color(this.getDisplay(), 150, 150, 150);
e.gc.setForeground(col);
e.gc.drawLine((int) (p.x + 7 + 20 * x + 3 * y),
(int) (p.y + 7 + 20 * y - 3 * x),
(int) (p.x + 7 + 26 * x + 3 * y),
(int) (p.y + 7 + 26 * y - 3 * x));
e.gc.drawLine((int) (p.x + 7 + 20 * x - 3 * y),
(int) (p.y + 7 + 20 * y + 3 * x),
(int) (p.x + 7 + 26 * x - 3 * y),
(int) (p.y + 7 + 26 * y + 3 * x));
// Augen
// col = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
e.gc.setBackground(eyeColor);
e.gc.fillOval((int) (p.x + 7 + 17 * x + 3 * y),
(int) (p.y + 7 + 17 * y - 3 * x), 3, 3);
e.gc.fillOval((int) (p.x + 7 + 17 * x - 3 * y),
(int) (p.y + 7 + 17 * y + 3 * x), 3, 3);
// col.dispose();*/
}
/**
* Liefert die Koordinaten, wo die Ameise platziert werden muss, wenn sie
* sich bei Knoten i befindet.
*
* @param i
* Knoten, bei dem sich die Ameise befindet
* @return c Array mit zugehoerigen Koordinaten
*/
private int[] getAntCoord(int i) {
return getCircleCoord(i, ANTRADIUS, new Point(175, 152));
}
private int[] getKnotCoord(int i) {
return getCircleCoord(i, KNOTRADIUS, new Point(183,160));
}
private int[] getCircleCoord(int i, int radius, Point center) {
int size = m.getSize();
int[] out = new int[2];
out[0] = (int) (Math.cos(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.x);
out[1] = (int) (Math.sin(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.y);
return out;
}
/**
* Setzt die Koordinaten, wo sich die Ameise befindet in Abhaengigkeit von
* dem jeweils aktuellen Knoten.
*
*/
private void setAnt() {
int i = m.getKnot();
int[] a = this.getAntCoord(i);
int oldX = x;
int oldY = y;
x = a[0];
y = a[1];
x2 = -(a[1]-172) + a[0];
y2 = (a[0]-172) + a[1];
int scalarProd = (x-oldX)*(x2-x)+(y-oldY)*(y2-y);
if(scalarProd < 0){
x2 = (a[1]-172) + a[0];
y2 = -(a[0]-172) + a[1];
}
}
public boolean isAnimationRunning() {
return isAnimationRunning;
}
public void addController(AntColEventController reg) {
this.controller = reg;
}
}
| jcryptool/crypto | org.jcryptool.visual.aco/src/org/jcryptool/visual/aco/view/AntColGraphComposite.java | 3,722 | /**
* Zeichnet eine Kante des Weges von Knoten i zu Knoten j;
*
* @param e
* PaintEvent
* @param i
* Knoten i
* @param j
* Knoten j
*/ | block_comment | nl | package org.jcryptool.visual.aco.view;
import java.awt.Point;
import java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.jcryptool.visual.aco.controller.AntColEventController;
import org.jcryptool.visual.aco.model.CommonModel;
public class AntColGraphComposite extends Composite {
private static final int KNOTRADIUS = 120;
private static final int ANTRADIUS = 90;
private CommonModel m;
private Canvas canv;
private int x; // Position Ameise
private int y;
private int x2; // Ziel Ameise
private int y2;
private boolean isAnimationRunning = false;
private final Color highlightColor = new Color(this.getDisplay(), 100, 190,
0);
private Color normalColor = new Color(this.getDisplay(), 50, 120, 50);
private Color antColor = new Color(this.getDisplay(), 139, 90, 40);
private Color eyeColor = new Color(this.getDisplay(), 255, 255, 255);
private AntColEventController controller;
/**
* Konstruktor erhaelt Model und Parent.
*
* @param model
* @param c
*/
public AntColGraphComposite(CommonModel model, Composite c) {
super(c, SWT.NONE);
this.m = model;
setLayout(new GridLayout(1, false));
redraw();
}
public void redraw() {
super.redraw();
// visualisierung nur zeigen, wenn die schlüssellänge zwischen 3 und 5
// ist.
if (canv != null) {
canv.dispose();
}
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
data.widthHint = 365;
// data.heightHint = 365;
canv = new Canvas(this, SWT.NONE);
canv.setLayoutData(data);
// Listener, der festlegt was geschieht wenn redraw aufgerufen wird
canv.addPaintListener(new PaintListener() {
public void paintControl(PaintEvent e) {
// Fall: Entschluesselung darstellen
drawKnots(e); // Graph zeichnen
if (m.getState() != 0) {
drawAllPropabilities(e);
drawTrail(e);
// if (m.isAnimateable()) // Ameise zeichnen
drawAnt(e, new Point(x, y), new Point(x2, y2));
}
}
});
setAnt();
layout();
}
public void animationStep() {
final Display d = this.getDisplay();
x2 = getAntCoord(m.getKnot())[0];
y2 = getAntCoord(m.getKnot())[1];
// Schrittweite
isAnimationRunning = true;
final int diffx = (int) (Math.abs(x - x2) / 15 + 0.5);
final int diffy = (int) (Math.abs(y - y2) / 15 + 0.5);
// Thread, der Bewegung uebernimmt
Runnable runnable = new Runnable() {
public void run() {
// Schritt
if (x - x2 > 0)
x -= diffx;
else
x += diffx;
if (y - y2 > 0)
y -= diffy;
else
y += diffy;
if (Math.abs(x - x2) > 15 || Math.abs(y - y2) > 15) {
canv.redraw(); // neu zeichnen
d.timerExec(150, this); // Schleife
} else { // angekommen
setAnt();
canv.redraw(); // neu zeichnen
controller.afterGraphDrawn();
isAnimationRunning = false;
}
}
};
d.timerExec(1, runnable); // Starten
}
private void drawKnots(PaintEvent e) {
e.gc.setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
String[] knots = m.getKnots();
Vector<Integer> trail = m.getTrail();
for (int i = 0; i < knots.length; i++) {
int[] a = this.getKnotCoord(i);
drawKnot(e, knots[i], a[0], a[1], trail.contains(i), i + 1);
}
}
/**
* Zeichnet den von der Ameise zurueckgelegten Weg auf das Canvas
*
* @param e
* PaintEvent
*/
private void drawTrail(PaintEvent e) {
Vector<Integer> weg = m.getTrail();
if (weg.size() > 1) {
for (int i = 0; i < weg.size() - 1; i++) {
drawKante(e, weg.elementAt(i), weg.elementAt(i + 1));
}
}
}
public void drawAllPropabilities(PaintEvent e) {
String[] knots = m.getKnots();
double[] probs = m.getProbabilities(); // W'keiten holen
for(int i = 0; i < knots.length; i++){
int[] a = getKnotCoord(i);
drawPropability(e, a[0], a[1], probs[i]);
}
}
private void drawPropability(PaintEvent e, int x, int y, double prob) {
if (prob > 0) { // W'keit
String str = prob * 100 + ""; //$NON-NLS-1$
str = str.substring(0, str.indexOf('.') + 2) + " %"; //$NON-NLS-1$
if(y < 180){
y -= 43;
} else {
y += 32;
}
e.gc.setBackground(highlightColor);
e.gc.drawString(str, x-18, y);
}
}
/**
* Zeichnet eine Kante<SUF>*/
private void drawKante(PaintEvent e, int i, int j) {
e.gc.setForeground(highlightColor);
int[] a = this.getKnotCoord(i);
int[] b = this.getKnotCoord(j);
e.gc.drawLine(a[0], a[1], b[0], b[1]);
}
/**
* Zeichnet einen Knoten bei den uebergebenen Koordinaten und mit dem
* uebergebenen Text, Nummer und Wahrscheinlichkeit auf das Canvas.
*
* @param e
* PaintEvent
* @param s
* Spalte die zum Knoten gehoert
* @param x
* x-Koordinate Knoten
* @param y
* y-Koordinate Knoten
* @param set
* Knoten bereits passiert?
* @param prob
* W'keit, dass Ameise zu diesem Knoten im naechsten Schritt geht
* @param nr
* Knotennummer
*/
private void drawKnot(PaintEvent e, String s, int x, int y, boolean set,
int nr) {
if (set) // wenn bereits passiert in gruen
e.gc.setBackground(highlightColor);
else
e.gc.setBackground(normalColor);
// Kreis und Nummer zeichnen
e.gc.fillOval(x - 32, y - 32, 65, 65);
e.gc.drawString(nr + "", x -22, y -12); //$NON-NLS-1$
if (s.length() > 5)
s = s.substring(0, 5);
for (int i = 0; i < s.length(); i++) { // Text
e.gc.drawString(
Character.toUpperCase(s.charAt(i)) + "", x, y + 12 * (i + 1) - 40); //$NON-NLS-1$
}
}
public void destroyGraph() {
canv.dispose();
}
/**
* Zeichnet eine Ameise beim Punkt p auf das Canvas mit Orientierung
* Richtung Punkt p2
*
* @param e
* PaintEvent
* @param p
* Ort der Ameise
* @param p2
* Orientierung der Ameise
*/
private void drawAnt(PaintEvent e, Point p, Point p2) {
Color col = antColor;
e.gc.setBackground(col);
e.gc.fillOval(p.x, p.y, 15, 15);
double x = p2.x - p.x;
double y = p2.y - p.y;
// Laenge Vektor
double n = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
x /= n;
y /= n;
// Rumpf
e.gc.fillOval((int) (p.x + 15 * x), (int) (p.y + 15 * y), 15, 15);
e.gc.fillOval((int) (p.x - 15 * x), (int) (p.y - 15 * y), 15, 15);
// Fuehler
col = new Color(this.getDisplay(), 150, 150, 150);
e.gc.setForeground(col);
e.gc.drawLine((int) (p.x + 7 + 20 * x + 3 * y),
(int) (p.y + 7 + 20 * y - 3 * x),
(int) (p.x + 7 + 26 * x + 3 * y),
(int) (p.y + 7 + 26 * y - 3 * x));
e.gc.drawLine((int) (p.x + 7 + 20 * x - 3 * y),
(int) (p.y + 7 + 20 * y + 3 * x),
(int) (p.x + 7 + 26 * x - 3 * y),
(int) (p.y + 7 + 26 * y + 3 * x));
// Augen
// col = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
e.gc.setBackground(eyeColor);
e.gc.fillOval((int) (p.x + 7 + 17 * x + 3 * y),
(int) (p.y + 7 + 17 * y - 3 * x), 3, 3);
e.gc.fillOval((int) (p.x + 7 + 17 * x - 3 * y),
(int) (p.y + 7 + 17 * y + 3 * x), 3, 3);
// col.dispose();*/
}
/**
* Liefert die Koordinaten, wo die Ameise platziert werden muss, wenn sie
* sich bei Knoten i befindet.
*
* @param i
* Knoten, bei dem sich die Ameise befindet
* @return c Array mit zugehoerigen Koordinaten
*/
private int[] getAntCoord(int i) {
return getCircleCoord(i, ANTRADIUS, new Point(175, 152));
}
private int[] getKnotCoord(int i) {
return getCircleCoord(i, KNOTRADIUS, new Point(183,160));
}
private int[] getCircleCoord(int i, int radius, Point center) {
int size = m.getSize();
int[] out = new int[2];
out[0] = (int) (Math.cos(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.x);
out[1] = (int) (Math.sin(Math.PI * 2 * (double) i / size + Math.PI /2-Math.PI/ size) * radius + center.y);
return out;
}
/**
* Setzt die Koordinaten, wo sich die Ameise befindet in Abhaengigkeit von
* dem jeweils aktuellen Knoten.
*
*/
private void setAnt() {
int i = m.getKnot();
int[] a = this.getAntCoord(i);
int oldX = x;
int oldY = y;
x = a[0];
y = a[1];
x2 = -(a[1]-172) + a[0];
y2 = (a[0]-172) + a[1];
int scalarProd = (x-oldX)*(x2-x)+(y-oldY)*(y2-y);
if(scalarProd < 0){
x2 = (a[1]-172) + a[0];
y2 = -(a[0]-172) + a[1];
}
}
public boolean isAnimationRunning() {
return isAnimationRunning;
}
public void addController(AntColEventController reg) {
this.controller = reg;
}
}
| False |
165 | 108554_5 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" }," +
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
| B3Partners/B3pCatalog | src/main/java/nl/b3p/catalog/stripes/GeoBrabantAction.java | 2,384 | //acc.geobrabant.nl/viewer/app/RIN03/v1\" }," + | line_comment | nl | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package nl.b3p.catalog.stripes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.validation.Validate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
*
* @author Geert Plaisier
*/
public class GeoBrabantAction extends DefaultAction {
@Validate(required=false)
private String searchString;
@Validate(required=false)
private String searchType;
@Validate(required=false)
private String uuid;
private List<MapsBean> mapsList;
@DefaultHandler
public Resolution home() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/home.jsp");
}
/* Static pages */
public Resolution overgeobrabant() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/overgeobrabant.jsp");
}
public Resolution diensten() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/diensten.jsp");
}
public Resolution contact() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/contact.jsp");
}
public Resolution kaarten() {
// This JSON should be fetched from a server somewhere
String mapsJson = "[" +
"{ \"class\": \"wat-mag-waar\", \"title\": \"Wat mag waar?\", \"description\": \"Waar ligt dat stukje grond? Zou ik hier mogen bouwen? Vragen die u beantwoord zult zien worden via dit thema. Bekijk welk perceel waar ligt en wat je ermee mag doen.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN01/v1\" }," +
"{ \"class\": \"bekendmakingen\", \"title\": \"Bekendmakingen\", \"description\": \"Via bekendmakingen kunt u zien welke vergunningaanvragen in uw buurt zijn ingediend of verleend zijn. Hierdoor blijft u op de hoogte van de ontwikkelingen bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN02/v1\" }," +
"{ \"class\": \"bereikbaarheid\", \"title\": \"Bereikbaarheid\", \"description\": \"Via dit thema kunt u erachter komen hoe de beriekbaarheid van een bepaald gebied is. Zo vindt u bijvoorbeeld waar de dichtstbijzijnde parkeergarage is, waar u oplaadpalen aantreft en actuele informatie over verkeer en wegwerkzaamheden\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN03/v1\" },"<SUF>
"{ \"class\": \"veiligheid\", \"title\": \"Veiligheid\", \"description\": \"In dit thema vindt u informatie over de veiligheid in uw buurt. Waar zit de politie en brandweer, maar ook overstromingsrisico, waterkeringen en de veiligheidsregio staan hier.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN04/v1\" }," +
"{ \"class\": \"zorg\", \"title\": \"Zorg\", \"description\": \"Ziekenhuizen, doktersposten en verzorgingshuizen. Alle data met betrekking tot de (medische) zorg staan in dit thema beschreven.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN05/v1\" }," +
"{ \"class\": \"onderwijs-kinderopvang\", \"title\": \"Onderwijs & Kinderopvang\", \"description\": \"In dit thema vindt u de locatie van alle scholen en kinderopvang.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN06/v1\" }," +
"{ \"class\": \"wijkvoorzieningen\", \"title\": \"Wijkvoorzieningen\", \"description\": \"Waar bij mij in de buurt bevinden zich afvalbakken, hondenuitlaatplaatsen en de speeltuin? Dergelijke wijkvoorzieningen vindt u in dit thema, evenals buurthuizen, winkelcentra, etc.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN07/v1\" }," +
"{ \"class\": \"recreatie\", \"title\": \"Recreatie\", \"description\": \"Waar kan ik bij mij in de buurt vrije tijd besteden? In dit thema ziet u waar u kunt sporten en ontspannen. Ook wandel- en fietspaden, natuurgebieden en horecagelegenheden vindt u hier terug.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN08/v1\" }," +
"{ \"class\": \"kunst-cultuur\", \"title\": \"Kunst & Cultuur\", \"description\": \"In dit thema vindt u alle informatie over cultuurhistorie en musea: gemeentelijke- en rijksmonumenten, maar ook archeologische monumenten.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN09/v1\" }," +
"{ \"class\": \"werklocaties\", \"title\": \"Werklocaties\", \"description\": \"In dit thema vindt u alles over bedrijvigheid. Bedrijventerreinen en kantoorlocaties, maar ook winkelcentra bij u in de buurt.\", \"url\": \"http://acc.geobrabant.nl/viewer/app/RIN10/v1\" }" +
"]";
this.mapsList = new ArrayList<>();
try {
JSONArray maps = new JSONArray(mapsJson);
for (int i = 0; i < maps.length(); ++i) {
JSONObject rec = maps.getJSONObject(i);
MapsBean map = new MapsBean();
map.setTitle(rec.getString("title"));
map.setDescription(rec.getString("description"));
map.setUrl(rec.getString("url"));
map.setCssClass(rec.getString("class"));
this.mapsList.add(map);
}
} catch (JSONException ex) {
Logger.getLogger(GeoBrabantAction.class.getName()).log(Level.SEVERE, null, ex);
}
return new ForwardResolution("/WEB-INF/jsp/geobrabant/kaarten.jsp");
}
public Resolution catalogus() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/catalogus.jsp");
}
public Resolution zoeken() {
return new ForwardResolution("/WEB-INF/jsp/geobrabant/zoeken.jsp");
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public List<MapsBean> getMapsList() {
return mapsList;
}
public void setMapsList(List<MapsBean> mapsList) {
this.mapsList = mapsList;
}
public class MapsBean {
private String title;
private String description;
private String url;
private String cssClass;
public MapsBean() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCssClass() {
return cssClass;
}
public void setCssClass(String cssClass) {
this.cssClass = cssClass;
}
}
}
| False |
4,338 | 38231_5 | package er.chronic.numerizer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Numerizer {
protected static class DirectNum {
private Pattern _name;
private String _number;
public DirectNum(String name, String number) {
_name = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
_number = number;
}
public Pattern getName() {
return _name;
}
public String getNumber() {
return _number;
}
}
protected static class Prefix {
private String _name;
private Pattern _pattern;
private long _number;
public Prefix(String name, Pattern pattern, long number) {
_name = name;
_pattern = pattern;
_number = number;
}
public String getName() {
return _name;
}
public Pattern getPattern() {
return _pattern;
}
public long getNumber() {
return _number;
}
}
protected static class TenPrefix extends Prefix {
public TenPrefix(String name, long number) {
super(name, Pattern.compile("(?:" + name + ") *<num>(\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number);
}
}
protected static class BigPrefix extends Prefix {
public BigPrefix(String name, long number) {
super(name, Pattern.compile("(?:<num>)?(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number);
}
}
protected static DirectNum[] DIRECT_NUMS;
protected static TenPrefix[] TEN_PREFIXES;
protected static BigPrefix[] BIG_PREFIXES;
static {
List<DirectNum> directNums = new LinkedList<DirectNum>();
directNums.add(new DirectNum("eleven", "11"));
directNums.add(new DirectNum("twelve", "12"));
directNums.add(new DirectNum("thirteen", "13"));
directNums.add(new DirectNum("fourteen", "14"));
directNums.add(new DirectNum("fifteen", "15"));
directNums.add(new DirectNum("sixteen", "16"));
directNums.add(new DirectNum("seventeen", "17"));
directNums.add(new DirectNum("eighteen", "18"));
directNums.add(new DirectNum("nineteen", "19"));
directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling
directNums.add(new DirectNum("zero", "0"));
directNums.add(new DirectNum("one", "1"));
directNums.add(new DirectNum("two", "2"));
directNums.add(new DirectNum("three", "3"));
directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty
directNums.add(new DirectNum("five", "5"));
directNums.add(new DirectNum("six(\\W|$)", "6$1"));
directNums.add(new DirectNum("seven(\\W|$)", "7$1"));
directNums.add(new DirectNum("eight(\\W|$)", "8$1"));
directNums.add(new DirectNum("nine(\\W|$)", "9$1"));
directNums.add(new DirectNum("ten", "10"));
directNums.add(new DirectNum("\\ba\\b(.)", "1$1"));
Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]);
List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>();
tenPrefixes.add(new TenPrefix("twenty", 20));
tenPrefixes.add(new TenPrefix("thirty", 30));
tenPrefixes.add(new TenPrefix("fourty", 40)); // Common mis-spelling
tenPrefixes.add(new TenPrefix("forty", 40));
tenPrefixes.add(new TenPrefix("fifty", 50));
tenPrefixes.add(new TenPrefix("sixty", 60));
tenPrefixes.add(new TenPrefix("seventy", 70));
tenPrefixes.add(new TenPrefix("eighty", 80));
tenPrefixes.add(new TenPrefix("ninety", 90));
tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling
Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]);
List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>();
bigPrefixes.add(new BigPrefix("hundred", 100L));
bigPrefixes.add(new BigPrefix("thousand", 1000L));
bigPrefixes.add(new BigPrefix("million", 1000000L));
bigPrefixes.add(new BigPrefix("billion", 1000000000L));
bigPrefixes.add(new BigPrefix("trillion", 1000000000000L));
Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]);
}
private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)");
private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE);
private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE);
private static final Pattern ANDITION_PATTERN = Pattern.compile("<num>(\\d+)( | and )<num>(\\d+)(?=\\W|$)", Pattern.CASE_INSENSITIVE);
// FIXES
//string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
//string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
public static String numerize(String str) {
String numerizedStr = str;
// preprocess
numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction
numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end
// easy/direct replacements
for (DirectNum dn : Numerizer.DIRECT_NUMS) {
numerizedStr = dn.getName().matcher(numerizedStr).replaceAll("<num>" + dn.getNumber());
}
// ten, twenty, etc.
for (Prefix tp : Numerizer.TEN_PREFIXES) {
Matcher matcher = tp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
}
for (Prefix tp : Numerizer.TEN_PREFIXES) {
numerizedStr = Pattern.compile(tp.getName(), Pattern.CASE_INSENSITIVE).matcher(numerizedStr).replaceAll("<num>" + tp.getNumber());
}
// hundreds, thousands, millions, etc.
for (Prefix bp : Numerizer.BIG_PREFIXES) {
Matcher matcher = bp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
numerizedStr = Numerizer.andition(numerizedStr);
// combine_numbers(string) // Should to be more efficient way to do this
}
// fractional addition
// I'm not combining this with the previous block as using float addition complicates the strings
// (with extraneous .0's and such )
Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f));
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
//string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s }
numerizedStr = numerizedStr.replaceAll("<num>", "");
return numerizedStr;
}
public static String andition(String str) {
StringBuilder anditionStr = new StringBuilder(str);
Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
while (matcher.find()) {
if (matcher.group(2).equalsIgnoreCase(" and ") || (matcher.group(1).length() > matcher.group(3).length() && matcher.group(1).matches("^.+0+$"))) {
anditionStr.replace(matcher.start(), matcher.end(), "<num>" + String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim())));
matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
}
}
return anditionStr.toString();
}
}
| smarthealth/wonder | Frameworks/Misc/ERChronic/Sources/er/chronic/numerizer/Numerizer.java | 2,842 | // ten, twenty, etc. | line_comment | nl | package er.chronic.numerizer;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Numerizer {
protected static class DirectNum {
private Pattern _name;
private String _number;
public DirectNum(String name, String number) {
_name = Pattern.compile(name, Pattern.CASE_INSENSITIVE);
_number = number;
}
public Pattern getName() {
return _name;
}
public String getNumber() {
return _number;
}
}
protected static class Prefix {
private String _name;
private Pattern _pattern;
private long _number;
public Prefix(String name, Pattern pattern, long number) {
_name = name;
_pattern = pattern;
_number = number;
}
public String getName() {
return _name;
}
public Pattern getPattern() {
return _pattern;
}
public long getNumber() {
return _number;
}
}
protected static class TenPrefix extends Prefix {
public TenPrefix(String name, long number) {
super(name, Pattern.compile("(?:" + name + ") *<num>(\\d(?=\\D|$))*", Pattern.CASE_INSENSITIVE), number);
}
}
protected static class BigPrefix extends Prefix {
public BigPrefix(String name, long number) {
super(name, Pattern.compile("(?:<num>)?(\\d*) *" + name, Pattern.CASE_INSENSITIVE), number);
}
}
protected static DirectNum[] DIRECT_NUMS;
protected static TenPrefix[] TEN_PREFIXES;
protected static BigPrefix[] BIG_PREFIXES;
static {
List<DirectNum> directNums = new LinkedList<DirectNum>();
directNums.add(new DirectNum("eleven", "11"));
directNums.add(new DirectNum("twelve", "12"));
directNums.add(new DirectNum("thirteen", "13"));
directNums.add(new DirectNum("fourteen", "14"));
directNums.add(new DirectNum("fifteen", "15"));
directNums.add(new DirectNum("sixteen", "16"));
directNums.add(new DirectNum("seventeen", "17"));
directNums.add(new DirectNum("eighteen", "18"));
directNums.add(new DirectNum("nineteen", "19"));
directNums.add(new DirectNum("ninteen", "19")); // Common mis-spelling
directNums.add(new DirectNum("zero", "0"));
directNums.add(new DirectNum("one", "1"));
directNums.add(new DirectNum("two", "2"));
directNums.add(new DirectNum("three", "3"));
directNums.add(new DirectNum("four(\\W|$)", "4$1")); // The weird regex is so that it matches four but not fourty
directNums.add(new DirectNum("five", "5"));
directNums.add(new DirectNum("six(\\W|$)", "6$1"));
directNums.add(new DirectNum("seven(\\W|$)", "7$1"));
directNums.add(new DirectNum("eight(\\W|$)", "8$1"));
directNums.add(new DirectNum("nine(\\W|$)", "9$1"));
directNums.add(new DirectNum("ten", "10"));
directNums.add(new DirectNum("\\ba\\b(.)", "1$1"));
Numerizer.DIRECT_NUMS = directNums.toArray(new DirectNum[directNums.size()]);
List<TenPrefix> tenPrefixes = new LinkedList<TenPrefix>();
tenPrefixes.add(new TenPrefix("twenty", 20));
tenPrefixes.add(new TenPrefix("thirty", 30));
tenPrefixes.add(new TenPrefix("fourty", 40)); // Common mis-spelling
tenPrefixes.add(new TenPrefix("forty", 40));
tenPrefixes.add(new TenPrefix("fifty", 50));
tenPrefixes.add(new TenPrefix("sixty", 60));
tenPrefixes.add(new TenPrefix("seventy", 70));
tenPrefixes.add(new TenPrefix("eighty", 80));
tenPrefixes.add(new TenPrefix("ninety", 90));
tenPrefixes.add(new TenPrefix("ninty", 90)); // Common mis-spelling
Numerizer.TEN_PREFIXES = tenPrefixes.toArray(new TenPrefix[tenPrefixes.size()]);
List<BigPrefix> bigPrefixes = new LinkedList<BigPrefix>();
bigPrefixes.add(new BigPrefix("hundred", 100L));
bigPrefixes.add(new BigPrefix("thousand", 1000L));
bigPrefixes.add(new BigPrefix("million", 1000000L));
bigPrefixes.add(new BigPrefix("billion", 1000000000L));
bigPrefixes.add(new BigPrefix("trillion", 1000000000000L));
Numerizer.BIG_PREFIXES = bigPrefixes.toArray(new BigPrefix[bigPrefixes.size()]);
}
private static final Pattern DEHYPHENATOR = Pattern.compile(" +|(\\D)-(\\D)");
private static final Pattern DEHALFER = Pattern.compile("a half", Pattern.CASE_INSENSITIVE);
private static final Pattern DEHAALFER = Pattern.compile("(\\d+)(?: | and |-)*haAlf", Pattern.CASE_INSENSITIVE);
private static final Pattern ANDITION_PATTERN = Pattern.compile("<num>(\\d+)( | and )<num>(\\d+)(?=\\W|$)", Pattern.CASE_INSENSITIVE);
// FIXES
//string.gsub!(/ +|([^\d])-([^d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
//string.gsub!(/ +|([^\d])-([^\\d])/, '\1 \2') # will mutilate hyphenated-words but shouldn't matter for date extraction
public static String numerize(String str) {
String numerizedStr = str;
// preprocess
numerizedStr = Numerizer.DEHYPHENATOR.matcher(numerizedStr).replaceAll("$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction
numerizedStr = Numerizer.DEHALFER.matcher(numerizedStr).replaceAll("haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end
// easy/direct replacements
for (DirectNum dn : Numerizer.DIRECT_NUMS) {
numerizedStr = dn.getName().matcher(numerizedStr).replaceAll("<num>" + dn.getNumber());
}
// ten, twenty,<SUF>
for (Prefix tp : Numerizer.TEN_PREFIXES) {
Matcher matcher = tp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(tp.getNumber() + Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
}
for (Prefix tp : Numerizer.TEN_PREFIXES) {
numerizedStr = Pattern.compile(tp.getName(), Pattern.CASE_INSENSITIVE).matcher(numerizedStr).replaceAll("<num>" + tp.getNumber());
}
// hundreds, thousands, millions, etc.
for (Prefix bp : Numerizer.BIG_PREFIXES) {
Matcher matcher = bp.getPattern().matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
if (matcher.group(1) == null) {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber()));
}
else {
matcher.appendReplacement(matcherBuffer, "<num>" + String.valueOf(bp.getNumber() * Long.parseLong(matcher.group(1).trim())));
}
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
numerizedStr = Numerizer.andition(numerizedStr);
// combine_numbers(string) // Should to be more efficient way to do this
}
// fractional addition
// I'm not combining this with the previous block as using float addition complicates the strings
// (with extraneous .0's and such )
Matcher matcher = Numerizer.DEHAALFER.matcher(numerizedStr);
if (matcher.find()) {
StringBuffer matcherBuffer = new StringBuffer();
do {
matcher.appendReplacement(matcherBuffer, String.valueOf(Float.parseFloat(matcher.group(1).trim()) + 0.5f));
} while (matcher.find());
matcher.appendTail(matcherBuffer);
numerizedStr = matcherBuffer.toString();
}
//string.gsub!(/(\d+)(?: | and |-)*haAlf/i) { ($1.to_f + 0.5).to_s }
numerizedStr = numerizedStr.replaceAll("<num>", "");
return numerizedStr;
}
public static String andition(String str) {
StringBuilder anditionStr = new StringBuilder(str);
Matcher matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
while (matcher.find()) {
if (matcher.group(2).equalsIgnoreCase(" and ") || (matcher.group(1).length() > matcher.group(3).length() && matcher.group(1).matches("^.+0+$"))) {
anditionStr.replace(matcher.start(), matcher.end(), "<num>" + String.valueOf(Integer.parseInt(matcher.group(1).trim()) + Integer.parseInt(matcher.group(3).trim())));
matcher = Numerizer.ANDITION_PATTERN.matcher(anditionStr);
}
}
return anditionStr.toString();
}
}
| False |
1,545 | 128647_20 | import abschreibungen.src.de.htwsaar.stl.winf.abschreibungen.core.*;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Java Fx Applikation zu dem Abschreibungsprogramm
* @author Schwanzer
*
* @version 1.1
*/
public class AbschreibungenSimpelJavaFX extends Application {
private static final String LINEAR = "Linear";
private static final String GEOMETRISCH_DEGRESSIV = "Geometrisch-degressiv";
private static final String LINEAR_GEOMETRISCH_DEGRESSIV = "Wandelnd";
//StringBuilder für die Texte
private static StringBuilder readme = new StringBuilder();
private static StringBuilder license = new StringBuilder();
private static StringBuilder linearErklaerung = new StringBuilder();
private static StringBuilder geometrischDegressivErklaerung = new StringBuilder();
private static StringBuilder linearGeometrischDegressivErklaerung = new StringBuilder();
private static StringBuilder abschreibungErklaerung = new StringBuilder();
private static final String filePath = "Pfad zu den Texten";
//Dark Mode toggle. Ohne Dark Mode wäre es keine richtige Applikation :)
private ToggleButton dark_mode = new ToggleButton("Dark Mode off");
private BorderPane root = new BorderPane();
private Scene scene = new Scene(root, 850, 550);
private Vermoegensgegenstand maschine;
public static void main(String[] args) {
launch(args);
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //Matched einer Ganzzahl oder einer Gleitkommazahl
}
private static String readFile(String filePath) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(filePath));
return new String(encoded, StandardCharsets.UTF_8);
}
/**
* Ueberprueft die Laenge des Strings
* @param s der StringBuilder
* @return boolscher Ausdruck, ob der String die Laenge 0 hat.
*/
private static boolean checkStringLoaded(StringBuilder s) {
return s.length() == 0;
}
/**
* Die Start Methode, hier werden bereits TextArea Eigenschaften festgelegt
* @param primaryStage die Primary Stage fuer das Hauptfenster
*/
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Abschreibung JavaFX (simpel)");
TextArea textArea = new TextArea();
//Center of Frame
textArea.setMaxSize(400, 500);
root.setLeft(textArea);
createCenter(root, textArea);
createMenuBar(root, primaryStage);
primaryStage.setScene(scene);
scene.getStylesheets().add(AbschreibungenSimpelJavaFX.class.getResource("Abschreibungen.css").toExternalForm());
primaryStage.show();
}
/**
* Erzeugt die Maschine, von der abgeschrieben wird
* @param anschaffungskostenText das Anschaffungskosten-TextField
* @param nutzungsdauerText das Nutzungsdauer-TextField
* @param result
*/
private void createMaschine(TextField anschaffungskostenText, TextField nutzungsdauerText, String result) {
maschine = new VermoegensgegenstandImpl(checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString()));
maschine.setAbschreibungsverfahren(getCorrectAbschreibungsverfahren(result));
maschine.abschreiben();
}
private Vermoegensgegenstand.Abschreibungsverfahren getCorrectAbschreibungsverfahren(String res) {
switch (res) {
case GEOMETRISCH_DEGRESSIV:
return Vermoegensgegenstand.Abschreibungsverfahren.GEOMETRISCH_DEGRESSIV;
case LINEAR_GEOMETRISCH_DEGRESSIV:
return Vermoegensgegenstand.Abschreibungsverfahren.GEOMETRISCH_DEGRESSIV_LINEAR;
default:
return Vermoegensgegenstand.Abschreibungsverfahren.LINEAR;
}
}
/**
* Check Methode, die überprüft, ob der Text im TextField eine Double ist, gibt sonst eine Exception (Listener Button)
* @param ueberpruefenderText der Text des TextFields
* @return 0 wenn falsch, wenn richtig die geparste double Zahl
*/
private double checkStringContainsDouble(String ueberpruefenderText) {
if (!isNumeric(ueberpruefenderText)) {
return 0;
}
return Double.parseDouble(ueberpruefenderText);
}
/**
* Check Methode, die ueberprueft, ob der Text im TextField eine Double ist, gibt sonst eine Exception (Listener Button)
* @param ueberpruefenderText der Text des TextFields
* @return 0 wenn falsch, wenn die gesparste integer Zahl
*/
private int checkStringContainsInteger(String ueberpruefenderText) {
if (!isNumeric(ueberpruefenderText)) {
return 0;
}
return Integer.parseInt(ueberpruefenderText);
}
/**
* Updated den Text im Button
* @param btn der Button
* @param anschaffungskosten die Anschaffungskosten
* @param nutzungsdauer die Nutzungsdauer
*/
private void updateButton(Button btn, double anschaffungskosten, int nutzungsdauer) {
btn.setText("Abschreiben (" + anschaffungskosten + " EUR, " + nutzungsdauer + " Jahre)");
}
/**
* Das Fenster, welches bei Klick auf Menuitems geöffnet wird
* @param text der Text, der angezeigt werden soll
* @param primaryStage die HauptStage der Anwendung
*/
private void createWindow(String text, Stage primaryStage) {
int i = text.indexOf("\n");
String title = text.substring(0, i);
Label secondLabel = new Label(text);
ScrollPane root = new ScrollPane();
root.setContent(secondLabel);
Scene secondScene = new Scene(root, 230, 100);
root.setContent(secondLabel);
// New window (Stage)
Stage newWindow = new Stage();
newWindow.setTitle(title);
newWindow.initModality(Modality.APPLICATION_MODAL);
secondLabel.setWrapText(true);
secondLabel.prefWidthProperty().bind(newWindow.widthProperty().subtract(15));
// Set position of second window, related to primary window.
newWindow.setX(primaryStage.getX() + 200);
newWindow.setY(primaryStage.getY() + 100);
newWindow.setWidth(450);
newWindow.setHeight(600);
newWindow.setScene(secondScene);
if (!dark_mode.isSelected()) {
newWindow.getScene().getStylesheets().add(this.getClass().getResource("andereFenster.css").toExternalForm());
}
newWindow.show();
}
/**
* Erstellt die MenueBar (top)
* @param root die BorderPane, die die Elemente auf der primaryStage ordnet
* @param primaryStage die primary Stage, die zum Erstellen des Fenster benoetigt wird
*/
private void createMenuBar(BorderPane root, Stage primaryStage) {
//MenuBar erstellen
MenuBar menuBar = new MenuBar();
// einzelne Menus
Menu m1 = new Menu("Abschreibung");
Menu m2 = new Menu("Abschreibungsverfahren");
Menu m3 = new Menu("About");
//Abschreibungsverfahren
MenuItem abschreibungen = new MenuItem("Abschreibung");
MenuItem linear = new MenuItem("Linear");
MenuItem geometrischDegressiv = new MenuItem("Geometrisch-Degressiv");
MenuItem linearGeometrischDegressiv = new MenuItem("Wandelnd");
//About Items
MenuItem licensingMenuItem = new MenuItem("Licensing");
MenuItem readMeMenuItem = new MenuItem("Readme");
//Dark Mode
//Menues zu Bar hinzufügen
menuBar.getMenus().add(m1);
menuBar.getMenus().add(m2);
menuBar.getMenus().add(m3);
//Menuitems zum Menuepunkt "Abschreibungsverfahren" hinzufügen
m2.getItems().add(linear);
m2.getItems().add(geometrischDegressiv);
m2.getItems().add(linearGeometrischDegressiv);
m1.getItems().add(abschreibungen);
//Menueitems zum Menuepunkt "About" hinzufuegen
m3.getItems().add(licensingMenuItem);
m3.getItems().add(readMeMenuItem);
//Listeners zu den MenuItems
licensingMenuItem.setOnAction(e -> createWindow(loadStringFileContent("LICENSE.txt", license), primaryStage));
readMeMenuItem.setOnAction(e -> createWindow(loadStringFileContent("README.md", readme), primaryStage));
linear.setOnAction(e -> createWindow(loadStringFileContent("Linear.txt", linearErklaerung), primaryStage));
geometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("GeometrischDegressiv.txt", geometrischDegressivErklaerung), primaryStage));
linearGeometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("Wandelnd.txt", linearGeometrischDegressivErklaerung), primaryStage));
linearGeometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("GeometrischDegressiv.txt", abschreibungErklaerung), primaryStage));
abschreibungen.setOnAction(e -> createWindow(loadStringFileContent("Abschreibungen.txt", linearErklaerung), primaryStage));
root.setTop(menuBar);
}
/**
* Ueberprueft, ob der Button gedrueckt wurde, wenn ja, dann wird das Stylesheet geloescht. Es entsteht ein "Light Theme"
* @param pressed boolean Ausdruck, ob der Toggle Button gedrueckt wurde
*/
private void Dark_Mode(boolean pressed) {
//System.out.println(pressed);
if (pressed) {
scene.getStylesheets().clear();
} else {
scene.getStylesheets().add(this.getClass().getResource("Abschreibungen.css").toExternalForm());
}
}
/**
* Das Center der BorderPane wird hier erstellt enthaelt alle Buttons/TextFields
* @param root die BorderPane
* @param textArea die TextArea
*/
private void createCenter(BorderPane root, TextArea textArea) {
double anschaffungskosten = 10000;
int nutzungsdauer = 10;
GridPane rightGridPane = new GridPane();
//Combobox Items
ObservableList<String> options = FXCollections.observableArrayList(LINEAR, GEOMETRISCH_DEGRESSIV, LINEAR_GEOMETRISCH_DEGRESSIV);
//Combobox
ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(options);
comboBox.setValue(LINEAR);
//Textfields
TextField anschaffungskostenText = new TextField();
anschaffungskostenText.insertText(0, Double.toString(anschaffungskosten));
TextField nutzungsdauerText = new TextField();
nutzungsdauerText.insertText(0, Integer.toString(nutzungsdauer));
//Buttons
Button abschreibeButton = new Button();
updateButton(abschreibeButton, anschaffungskosten, nutzungsdauer);
//Listener zu Textfields hinzufügen
anschaffungskostenText.textProperty().addListener(observable -> updateButton(abschreibeButton, checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString())));
nutzungsdauerText.textProperty().addListener(observable -> updateButton(abschreibeButton, checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString())));
//die einzelnen Labels
Label properties = new Label("Eigenschaften");
Label abschreibungsverfahren = new Label("Abschreibungsverfahren: ");
Label anschaffungskostenLabel = new Label("Anschaffungskosten: ");
Label nutzungsdauerLabel = new Label("Nutzungsdauer: ");
//Label Eigenschaften:
rightGridPane.add(properties, 1, 0);
//Label Abschreibungsverfahren
rightGridPane.add(abschreibungsverfahren, 0, 1);
//Combobox
rightGridPane.add(comboBox, 1, 1);
rightGridPane.add(anschaffungskostenLabel, 0, 3);
rightGridPane.add(nutzungsdauerLabel, 0, 5);
rightGridPane.add(anschaffungskostenText, 1, 3);
rightGridPane.add(nutzungsdauerText, 1, 5);
rightGridPane.add(abschreibeButton, 0, 6);
dark_mode.selectedProperty().addListener((observable -> Dark_Mode(dark_mode.isSelected())));
rightGridPane.add(dark_mode, 0, 7);
abschreibeButton.setOnAction(event -> {
String abschreibungsArt = comboBox.getValue();
createMaschine(anschaffungskostenText, nutzungsdauerText, abschreibungsArt);
textArea.appendText(maschine.toString());
textArea.appendText("\n" + "-----------------------------------------------------------" + "\n");
});
//GridPane in Center of Border Pane
root.setCenter(rightGridPane);
}
/**
* Ueberprueft, ob der String bereits geladen wurde, dann wird nur der bereits geladene String zurueckgegeben,
* sonst wird er aus der Datei ausgelesen und zurueckgegeben
* @param fileName Der Dateiname
* @param content der StringBuilder der jeweiligen Datei
* @return der String mit dem Content
*/
private String loadStringFileContent(String fileName, StringBuilder content) {
if (!checkStringLoaded(content)) return content.toString();
try {
content.append(readFile(filePath + fileName));
} catch (Exception e) {
String error="Der Pfad wurde nicht korrekt auf das Verzeichnis Texte gesetzt: "+filePath;
showErrorDialog(e,error);
}
return content.toString();
}
/**
* zeigt einen Java FX Alert an
* @param e die Exception
* @param error der zusaetzliche Hinweis als String (wird vor der Exception ausgegeben)
*/
private void showErrorDialog(Exception e,String error) {
double alertDialogSize=1000;
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ein Fehler ist aufgetreten");
alert.setHeaderText(e.toString());
//CharacterStream schreibt output in StringBuffer
StringWriter sw = new StringWriter();
//PrintWriter: Prints formatted representations of objects to a text-output stream.
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw); //prints this throwable and its backtrace to the specified print stream
String exceptionmsg = sw.toString();
TextArea textArea = new TextArea();
textArea.appendText(error+"\n"+exceptionmsg);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
Label label = new Label("Der Stacktrace lautet:");
GridPane expContent = new GridPane();
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
expContent.setMinWidth(textArea.getWidth());
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
alert.getDialogPane().setMinWidth(alertDialogSize);
alert.showAndWait();
}
}
| SamTV12345/AbschreibungJavaFX | AbschreibungenSimpelJavaFX.java | 4,689 | /**
* Das Center der BorderPane wird hier erstellt enthaelt alle Buttons/TextFields
* @param root die BorderPane
* @param textArea die TextArea
*/ | block_comment | nl | import abschreibungen.src.de.htwsaar.stl.winf.abschreibungen.core.*;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Java Fx Applikation zu dem Abschreibungsprogramm
* @author Schwanzer
*
* @version 1.1
*/
public class AbschreibungenSimpelJavaFX extends Application {
private static final String LINEAR = "Linear";
private static final String GEOMETRISCH_DEGRESSIV = "Geometrisch-degressiv";
private static final String LINEAR_GEOMETRISCH_DEGRESSIV = "Wandelnd";
//StringBuilder für die Texte
private static StringBuilder readme = new StringBuilder();
private static StringBuilder license = new StringBuilder();
private static StringBuilder linearErklaerung = new StringBuilder();
private static StringBuilder geometrischDegressivErklaerung = new StringBuilder();
private static StringBuilder linearGeometrischDegressivErklaerung = new StringBuilder();
private static StringBuilder abschreibungErklaerung = new StringBuilder();
private static final String filePath = "Pfad zu den Texten";
//Dark Mode toggle. Ohne Dark Mode wäre es keine richtige Applikation :)
private ToggleButton dark_mode = new ToggleButton("Dark Mode off");
private BorderPane root = new BorderPane();
private Scene scene = new Scene(root, 850, 550);
private Vermoegensgegenstand maschine;
public static void main(String[] args) {
launch(args);
}
public static boolean isNumeric(String str) {
return str.matches("-?\\d+(\\.\\d+)?"); //Matched einer Ganzzahl oder einer Gleitkommazahl
}
private static String readFile(String filePath) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(filePath));
return new String(encoded, StandardCharsets.UTF_8);
}
/**
* Ueberprueft die Laenge des Strings
* @param s der StringBuilder
* @return boolscher Ausdruck, ob der String die Laenge 0 hat.
*/
private static boolean checkStringLoaded(StringBuilder s) {
return s.length() == 0;
}
/**
* Die Start Methode, hier werden bereits TextArea Eigenschaften festgelegt
* @param primaryStage die Primary Stage fuer das Hauptfenster
*/
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Abschreibung JavaFX (simpel)");
TextArea textArea = new TextArea();
//Center of Frame
textArea.setMaxSize(400, 500);
root.setLeft(textArea);
createCenter(root, textArea);
createMenuBar(root, primaryStage);
primaryStage.setScene(scene);
scene.getStylesheets().add(AbschreibungenSimpelJavaFX.class.getResource("Abschreibungen.css").toExternalForm());
primaryStage.show();
}
/**
* Erzeugt die Maschine, von der abgeschrieben wird
* @param anschaffungskostenText das Anschaffungskosten-TextField
* @param nutzungsdauerText das Nutzungsdauer-TextField
* @param result
*/
private void createMaschine(TextField anschaffungskostenText, TextField nutzungsdauerText, String result) {
maschine = new VermoegensgegenstandImpl(checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString()));
maschine.setAbschreibungsverfahren(getCorrectAbschreibungsverfahren(result));
maschine.abschreiben();
}
private Vermoegensgegenstand.Abschreibungsverfahren getCorrectAbschreibungsverfahren(String res) {
switch (res) {
case GEOMETRISCH_DEGRESSIV:
return Vermoegensgegenstand.Abschreibungsverfahren.GEOMETRISCH_DEGRESSIV;
case LINEAR_GEOMETRISCH_DEGRESSIV:
return Vermoegensgegenstand.Abschreibungsverfahren.GEOMETRISCH_DEGRESSIV_LINEAR;
default:
return Vermoegensgegenstand.Abschreibungsverfahren.LINEAR;
}
}
/**
* Check Methode, die überprüft, ob der Text im TextField eine Double ist, gibt sonst eine Exception (Listener Button)
* @param ueberpruefenderText der Text des TextFields
* @return 0 wenn falsch, wenn richtig die geparste double Zahl
*/
private double checkStringContainsDouble(String ueberpruefenderText) {
if (!isNumeric(ueberpruefenderText)) {
return 0;
}
return Double.parseDouble(ueberpruefenderText);
}
/**
* Check Methode, die ueberprueft, ob der Text im TextField eine Double ist, gibt sonst eine Exception (Listener Button)
* @param ueberpruefenderText der Text des TextFields
* @return 0 wenn falsch, wenn die gesparste integer Zahl
*/
private int checkStringContainsInteger(String ueberpruefenderText) {
if (!isNumeric(ueberpruefenderText)) {
return 0;
}
return Integer.parseInt(ueberpruefenderText);
}
/**
* Updated den Text im Button
* @param btn der Button
* @param anschaffungskosten die Anschaffungskosten
* @param nutzungsdauer die Nutzungsdauer
*/
private void updateButton(Button btn, double anschaffungskosten, int nutzungsdauer) {
btn.setText("Abschreiben (" + anschaffungskosten + " EUR, " + nutzungsdauer + " Jahre)");
}
/**
* Das Fenster, welches bei Klick auf Menuitems geöffnet wird
* @param text der Text, der angezeigt werden soll
* @param primaryStage die HauptStage der Anwendung
*/
private void createWindow(String text, Stage primaryStage) {
int i = text.indexOf("\n");
String title = text.substring(0, i);
Label secondLabel = new Label(text);
ScrollPane root = new ScrollPane();
root.setContent(secondLabel);
Scene secondScene = new Scene(root, 230, 100);
root.setContent(secondLabel);
// New window (Stage)
Stage newWindow = new Stage();
newWindow.setTitle(title);
newWindow.initModality(Modality.APPLICATION_MODAL);
secondLabel.setWrapText(true);
secondLabel.prefWidthProperty().bind(newWindow.widthProperty().subtract(15));
// Set position of second window, related to primary window.
newWindow.setX(primaryStage.getX() + 200);
newWindow.setY(primaryStage.getY() + 100);
newWindow.setWidth(450);
newWindow.setHeight(600);
newWindow.setScene(secondScene);
if (!dark_mode.isSelected()) {
newWindow.getScene().getStylesheets().add(this.getClass().getResource("andereFenster.css").toExternalForm());
}
newWindow.show();
}
/**
* Erstellt die MenueBar (top)
* @param root die BorderPane, die die Elemente auf der primaryStage ordnet
* @param primaryStage die primary Stage, die zum Erstellen des Fenster benoetigt wird
*/
private void createMenuBar(BorderPane root, Stage primaryStage) {
//MenuBar erstellen
MenuBar menuBar = new MenuBar();
// einzelne Menus
Menu m1 = new Menu("Abschreibung");
Menu m2 = new Menu("Abschreibungsverfahren");
Menu m3 = new Menu("About");
//Abschreibungsverfahren
MenuItem abschreibungen = new MenuItem("Abschreibung");
MenuItem linear = new MenuItem("Linear");
MenuItem geometrischDegressiv = new MenuItem("Geometrisch-Degressiv");
MenuItem linearGeometrischDegressiv = new MenuItem("Wandelnd");
//About Items
MenuItem licensingMenuItem = new MenuItem("Licensing");
MenuItem readMeMenuItem = new MenuItem("Readme");
//Dark Mode
//Menues zu Bar hinzufügen
menuBar.getMenus().add(m1);
menuBar.getMenus().add(m2);
menuBar.getMenus().add(m3);
//Menuitems zum Menuepunkt "Abschreibungsverfahren" hinzufügen
m2.getItems().add(linear);
m2.getItems().add(geometrischDegressiv);
m2.getItems().add(linearGeometrischDegressiv);
m1.getItems().add(abschreibungen);
//Menueitems zum Menuepunkt "About" hinzufuegen
m3.getItems().add(licensingMenuItem);
m3.getItems().add(readMeMenuItem);
//Listeners zu den MenuItems
licensingMenuItem.setOnAction(e -> createWindow(loadStringFileContent("LICENSE.txt", license), primaryStage));
readMeMenuItem.setOnAction(e -> createWindow(loadStringFileContent("README.md", readme), primaryStage));
linear.setOnAction(e -> createWindow(loadStringFileContent("Linear.txt", linearErklaerung), primaryStage));
geometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("GeometrischDegressiv.txt", geometrischDegressivErklaerung), primaryStage));
linearGeometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("Wandelnd.txt", linearGeometrischDegressivErklaerung), primaryStage));
linearGeometrischDegressiv.setOnAction(e -> createWindow(loadStringFileContent("GeometrischDegressiv.txt", abschreibungErklaerung), primaryStage));
abschreibungen.setOnAction(e -> createWindow(loadStringFileContent("Abschreibungen.txt", linearErklaerung), primaryStage));
root.setTop(menuBar);
}
/**
* Ueberprueft, ob der Button gedrueckt wurde, wenn ja, dann wird das Stylesheet geloescht. Es entsteht ein "Light Theme"
* @param pressed boolean Ausdruck, ob der Toggle Button gedrueckt wurde
*/
private void Dark_Mode(boolean pressed) {
//System.out.println(pressed);
if (pressed) {
scene.getStylesheets().clear();
} else {
scene.getStylesheets().add(this.getClass().getResource("Abschreibungen.css").toExternalForm());
}
}
/**
* Das Center der<SUF>*/
private void createCenter(BorderPane root, TextArea textArea) {
double anschaffungskosten = 10000;
int nutzungsdauer = 10;
GridPane rightGridPane = new GridPane();
//Combobox Items
ObservableList<String> options = FXCollections.observableArrayList(LINEAR, GEOMETRISCH_DEGRESSIV, LINEAR_GEOMETRISCH_DEGRESSIV);
//Combobox
ComboBox<String> comboBox = new ComboBox<>();
comboBox.setItems(options);
comboBox.setValue(LINEAR);
//Textfields
TextField anschaffungskostenText = new TextField();
anschaffungskostenText.insertText(0, Double.toString(anschaffungskosten));
TextField nutzungsdauerText = new TextField();
nutzungsdauerText.insertText(0, Integer.toString(nutzungsdauer));
//Buttons
Button abschreibeButton = new Button();
updateButton(abschreibeButton, anschaffungskosten, nutzungsdauer);
//Listener zu Textfields hinzufügen
anschaffungskostenText.textProperty().addListener(observable -> updateButton(abschreibeButton, checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString())));
nutzungsdauerText.textProperty().addListener(observable -> updateButton(abschreibeButton, checkStringContainsDouble(anschaffungskostenText.getCharacters().toString()),
checkStringContainsInteger(nutzungsdauerText.getCharacters().toString())));
//die einzelnen Labels
Label properties = new Label("Eigenschaften");
Label abschreibungsverfahren = new Label("Abschreibungsverfahren: ");
Label anschaffungskostenLabel = new Label("Anschaffungskosten: ");
Label nutzungsdauerLabel = new Label("Nutzungsdauer: ");
//Label Eigenschaften:
rightGridPane.add(properties, 1, 0);
//Label Abschreibungsverfahren
rightGridPane.add(abschreibungsverfahren, 0, 1);
//Combobox
rightGridPane.add(comboBox, 1, 1);
rightGridPane.add(anschaffungskostenLabel, 0, 3);
rightGridPane.add(nutzungsdauerLabel, 0, 5);
rightGridPane.add(anschaffungskostenText, 1, 3);
rightGridPane.add(nutzungsdauerText, 1, 5);
rightGridPane.add(abschreibeButton, 0, 6);
dark_mode.selectedProperty().addListener((observable -> Dark_Mode(dark_mode.isSelected())));
rightGridPane.add(dark_mode, 0, 7);
abschreibeButton.setOnAction(event -> {
String abschreibungsArt = comboBox.getValue();
createMaschine(anschaffungskostenText, nutzungsdauerText, abschreibungsArt);
textArea.appendText(maschine.toString());
textArea.appendText("\n" + "-----------------------------------------------------------" + "\n");
});
//GridPane in Center of Border Pane
root.setCenter(rightGridPane);
}
/**
* Ueberprueft, ob der String bereits geladen wurde, dann wird nur der bereits geladene String zurueckgegeben,
* sonst wird er aus der Datei ausgelesen und zurueckgegeben
* @param fileName Der Dateiname
* @param content der StringBuilder der jeweiligen Datei
* @return der String mit dem Content
*/
private String loadStringFileContent(String fileName, StringBuilder content) {
if (!checkStringLoaded(content)) return content.toString();
try {
content.append(readFile(filePath + fileName));
} catch (Exception e) {
String error="Der Pfad wurde nicht korrekt auf das Verzeichnis Texte gesetzt: "+filePath;
showErrorDialog(e,error);
}
return content.toString();
}
/**
* zeigt einen Java FX Alert an
* @param e die Exception
* @param error der zusaetzliche Hinweis als String (wird vor der Exception ausgegeben)
*/
private void showErrorDialog(Exception e,String error) {
double alertDialogSize=1000;
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Ein Fehler ist aufgetreten");
alert.setHeaderText(e.toString());
//CharacterStream schreibt output in StringBuffer
StringWriter sw = new StringWriter();
//PrintWriter: Prints formatted representations of objects to a text-output stream.
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw); //prints this throwable and its backtrace to the specified print stream
String exceptionmsg = sw.toString();
TextArea textArea = new TextArea();
textArea.appendText(error+"\n"+exceptionmsg);
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setMaxWidth(Double.MAX_VALUE);
textArea.setMaxHeight(Double.MAX_VALUE);
Label label = new Label("Der Stacktrace lautet:");
GridPane expContent = new GridPane();
GridPane.setVgrow(textArea, Priority.ALWAYS);
GridPane.setHgrow(textArea, Priority.ALWAYS);
expContent.setMinWidth(textArea.getWidth());
expContent.add(label, 0, 0);
expContent.add(textArea, 0, 1);
alert.getDialogPane().setExpandableContent(expContent);
alert.getDialogPane().setMinWidth(alertDialogSize);
alert.showAndWait();
}
}
| False |
791 | 140583_50 | /*_x000D_
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The BeautyEye Project. _x000D_
* All rights reserved._x000D_
* Project URL:https://github.com/JackJiang2011/beautyeye_x000D_
* Version 3.6_x000D_
* _x000D_
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms._x000D_
* _x000D_
* BEInternalFrameTitlePane.java at 2015-2-1 20:25:36, original version by Jack Jiang._x000D_
* You can contact author with jb2011@163.com._x000D_
*/_x000D_
package org.jb2011.lnf.beautyeye.ch10_internalframe;_x000D_
_x000D_
import java.awt.Color;_x000D_
import java.awt.Component;_x000D_
import java.awt.Container;_x000D_
import java.awt.Dimension;_x000D_
import java.awt.Font;_x000D_
import java.awt.FontMetrics;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.Insets;_x000D_
import java.awt.LayoutManager;_x000D_
import java.awt.Rectangle;_x000D_
import java.beans.PropertyChangeEvent;_x000D_
import java.beans.PropertyChangeListener;_x000D_
_x000D_
import javax.swing.Icon;_x000D_
import javax.swing.JInternalFrame;_x000D_
import javax.swing.JMenu;_x000D_
import javax.swing.JOptionPane;_x000D_
import javax.swing.UIManager;_x000D_
import javax.swing.border.Border;_x000D_
import javax.swing.border.EmptyBorder;_x000D_
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;_x000D_
import javax.swing.plaf.metal.MetalLookAndFeel;_x000D_
_x000D_
import org.jb2011.lnf.beautyeye.ch1_titlepane.BETitlePane;_x000D_
import org.jb2011.lnf.beautyeye.utils.MySwingUtilities2;_x000D_
import org.jb2011.lnf.beautyeye.winlnfutils.WinUtils;_x000D_
_x000D_
/**_x000D_
* 内部窗体的标题栏UI实现._x000D_
* _x000D_
* @author Jack Jiang_x000D_
*/_x000D_
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 Start_x000D_
//BeautyEye外观实现中取消了isPalette的所有特殊处理,isPalette及相关属性在_x000D_
//该外观中将失去意义,请注意!_x000D_
//虽然beautyEye是参考自MetalLookAndFeel,但因beautyEye使用了Insets很大的立体边框,_x000D_
//则如果还要像MetalLookAndFeel实现Palette类型的JInternalFrame则效果会很难看,干脆就就像_x000D_
//WindowsLookAndFeel一样,不去理会什么Palette,在当前的L&F下没有任何减分。_x000D_
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 END_x000D_
public class BEInternalFrameTitlePane extends BasicInternalFrameTitlePane_x000D_
{_x000D_
// protected boolean isPalette = false;_x000D_
// protected Icon paletteCloseIcon;_x000D_
// protected int paletteTitleHeight;_x000D_
_x000D_
/** The Constant handyEmptyBorder. */_x000D_
private static final Border handyEmptyBorder = new EmptyBorder(0, 0, 0, 0);_x000D_
_x000D_
/**_x000D_
* Key used to lookup Color from UIManager. If this is null,_x000D_
* <code>getWindowTitleBackground</code> is used._x000D_
*/_x000D_
private String selectedBackgroundKey;_x000D_
/**_x000D_
* Key used to lookup Color from UIManager. If this is null,_x000D_
* <code>getWindowTitleForeground</code> is used._x000D_
*/_x000D_
private String selectedForegroundKey;_x000D_
/**_x000D_
* Key used to lookup shadow color from UIManager. If this is null,_x000D_
* <code>getPrimaryControlDarkShadow</code> is used._x000D_
*/_x000D_
private String selectedShadowKey;_x000D_
/**_x000D_
* Boolean indicating the state of the <code>JInternalFrame</code>s_x000D_
* closable property at <code>updateUI</code> time._x000D_
*/_x000D_
private boolean wasClosable;_x000D_
_x000D_
/** The buttons width. */_x000D_
int buttonsWidth = 0;_x000D_
_x000D_
/**_x000D_
* Instantiates a new bE internal frame title pane._x000D_
*_x000D_
* @param f the f_x000D_
*/_x000D_
public BEInternalFrameTitlePane(JInternalFrame f)_x000D_
{_x000D_
super(f);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.JComponent#addNotify()_x000D_
*/_x000D_
public void addNotify()_x000D_
{_x000D_
super.addNotify();_x000D_
// This is done here instead of in installDefaults as I was worried_x000D_
// that the BasicInternalFrameUI might not be fully initialized, and_x000D_
// that if this resets the closable state the BasicInternalFrameUI_x000D_
// Listeners that get notified might be in an odd/uninitialized state._x000D_
updateOptionPaneState();_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#installDefaults()_x000D_
*/_x000D_
protected void installDefaults()_x000D_
{_x000D_
super.installDefaults();_x000D_
setFont(UIManager.getFont("InternalFrame.titleFont"));_x000D_
// paletteTitleHeight = UIManager_x000D_
// .getInt("InternalFrame.paletteTitleHeight");_x000D_
// paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon");_x000D_
wasClosable = frame.isClosable();_x000D_
selectedForegroundKey = selectedBackgroundKey = null;_x000D_
if (true)_x000D_
{_x000D_
setOpaque(false);_x000D_
}_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallDefaults()_x000D_
*/_x000D_
protected void uninstallDefaults()_x000D_
{_x000D_
super.uninstallDefaults();_x000D_
if (wasClosable != frame.isClosable())_x000D_
{_x000D_
frame.setClosable(wasClosable);_x000D_
}_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createButtons()_x000D_
*/_x000D_
protected void createButtons()_x000D_
{_x000D_
super.createButtons();_x000D_
_x000D_
Boolean paintActive = frame.isSelected() ? Boolean.TRUE : Boolean.FALSE;_x000D_
iconButton.putClientProperty("paintActive", paintActive);_x000D_
iconButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
maxButton.putClientProperty("paintActive", paintActive);_x000D_
maxButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
closeButton.putClientProperty("paintActive", paintActive);_x000D_
closeButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
// The palette close icon isn't opaque while the regular close icon is._x000D_
// This makes sure palette close buttons have the right background._x000D_
closeButton.setBackground(MetalLookAndFeel.getPrimaryControlShadow());_x000D_
_x000D_
if (true)_x000D_
{_x000D_
iconButton.setContentAreaFilled(false);_x000D_
maxButton.setContentAreaFilled(false);_x000D_
closeButton.setContentAreaFilled(false);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not _x000D_
* have system menus._x000D_
*/_x000D_
protected void assembleSystemMenu()_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not_x000D_
* have system menus._x000D_
*_x000D_
* @param systemMenu the system menu_x000D_
*/_x000D_
protected void addSystemMenuItems(JMenu systemMenu)_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not _x000D_
* have system menus._x000D_
*/_x000D_
protected void showSystemMenu()_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method avoid creating a menu bar. Metal frames_x000D_
* do not have system menus._x000D_
*/_x000D_
protected void addSubComponents()_x000D_
{_x000D_
add(iconButton);_x000D_
add(maxButton);_x000D_
add(closeButton);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createPropertyChangeListener()_x000D_
*/_x000D_
protected PropertyChangeListener createPropertyChangeListener()_x000D_
{_x000D_
return new MetalPropertyChangeHandler();_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createLayout()_x000D_
*/_x000D_
protected LayoutManager createLayout()_x000D_
{_x000D_
return new XMetalTitlePaneLayout();_x000D_
}_x000D_
_x000D_
/**_x000D_
* The Class MetalPropertyChangeHandler._x000D_
*/_x000D_
class MetalPropertyChangeHandler extends_x000D_
BasicInternalFrameTitlePane.PropertyChangeHandler_x000D_
{_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.PropertyChangeHandler#propertyChange(java.beans.PropertyChangeEvent)_x000D_
*/_x000D_
public void propertyChange(PropertyChangeEvent evt)_x000D_
{_x000D_
String prop = (String) evt.getPropertyName();_x000D_
if (prop.equals(JInternalFrame.IS_SELECTED_PROPERTY))_x000D_
{_x000D_
Boolean b = (Boolean) evt.getNewValue();_x000D_
iconButton.putClientProperty("paintActive", b);_x000D_
closeButton.putClientProperty("paintActive", b);_x000D_
maxButton.putClientProperty("paintActive", b);_x000D_
}_x000D_
else if ("JInternalFrame.messageType".equals(prop))_x000D_
{_x000D_
updateOptionPaneState();_x000D_
frame.repaint();_x000D_
}_x000D_
super.propertyChange(evt); _x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* The Class XZCMetalTitlePaneLayout._x000D_
*/_x000D_
class XMetalTitlePaneLayout extends TitlePaneLayout_x000D_
{_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#addLayoutComponent(java.lang.String, java.awt.Component)_x000D_
*/_x000D_
public void addLayoutComponent(String name, Component c)_x000D_
{_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#removeLayoutComponent(java.awt.Component)_x000D_
*/_x000D_
public void removeLayoutComponent(Component c)_x000D_
{_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#preferredLayoutSize(java.awt.Container)_x000D_
*/_x000D_
public Dimension preferredLayoutSize(Container c)_x000D_
{_x000D_
return minimumLayoutSize(c);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#minimumLayoutSize(java.awt.Container)_x000D_
*/_x000D_
public Dimension minimumLayoutSize(Container c)_x000D_
{_x000D_
// Compute width._x000D_
int width = 30;_x000D_
if (frame.isClosable())_x000D_
{_x000D_
width += 21;_x000D_
}_x000D_
if (frame.isMaximizable())_x000D_
{_x000D_
width += 16 + (frame.isClosable() ? 10 : 4);_x000D_
}_x000D_
if (frame.isIconifiable())_x000D_
{_x000D_
width += 16 + (frame.isMaximizable() ? 2_x000D_
: (frame.isClosable() ? 10 : 4));_x000D_
}_x000D_
FontMetrics fm = frame.getFontMetrics(getFont());_x000D_
String frameTitle = frame.getTitle();_x000D_
int title_w = frameTitle != null ? MySwingUtilities2.stringWidth(_x000D_
frame, fm, frameTitle) : 0;_x000D_
int title_length = frameTitle != null ? frameTitle.length() : 0;_x000D_
_x000D_
if (title_length > 2)_x000D_
{_x000D_
int subtitle_w = MySwingUtilities2.stringWidth(frame, fm, frame_x000D_
.getTitle().substring(0, 2)_x000D_
+ "...");_x000D_
width += (title_w < subtitle_w) ? title_w : subtitle_w;_x000D_
}_x000D_
else_x000D_
{_x000D_
width += title_w;_x000D_
}_x000D_
_x000D_
// Compute height._x000D_
int height = 0;_x000D_
_x000D_
// if (isPalette)_x000D_
// {_x000D_
// height = paletteTitleHeight;_x000D_
// }_x000D_
// else_x000D_
{_x000D_
int fontHeight = fm.getHeight();_x000D_
fontHeight += 4;//默认是 +=7 _x000D_
Icon icon = frame.getFrameIcon();_x000D_
int iconHeight = 0;_x000D_
if (icon != null)_x000D_
{_x000D_
// SystemMenuBar forces the icon to be 16x16 or less._x000D_
iconHeight = Math.min(icon.getIconHeight(), 16);_x000D_
}_x000D_
iconHeight += 5;_x000D_
height = Math.max(fontHeight, iconHeight) + 5;//默认是 +0,modified by jb2011 2012-06-18_x000D_
}_x000D_
_x000D_
return new Dimension(width, height);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#layoutContainer(java.awt.Container)_x000D_
*/_x000D_
public void layoutContainer(Container c)_x000D_
{_x000D_
boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
_x000D_
int w = getWidth();_x000D_
int x = leftToRight ? w : 0;_x000D_
int y = 5;//默认是0,modified by jb2011_x000D_
int spacing;_x000D_
_x000D_
// assumes all buttons have the same dimensions_x000D_
// these dimensions include the borders_x000D_
int buttonHeight = closeButton.getIcon().getIconHeight();_x000D_
int buttonWidth = closeButton.getIcon().getIconWidth();_x000D_
_x000D_
if (frame.isClosable())_x000D_
{_x000D_
// if (isPalette)_x000D_
// {_x000D_
// spacing = 3;_x000D_
// x += leftToRight ? -spacing - (buttonWidth + 2) : spacing;_x000D_
// closeButton.setBounds(x, y, buttonWidth + 2,_x000D_
// getHeight() - 4);_x000D_
// if (!leftToRight)_x000D_
// x += (buttonWidth + 2);_x000D_
// }_x000D_
// else_x000D_
{_x000D_
spacing = 4;_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
closeButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
}_x000D_
_x000D_
if (frame.isMaximizable())// && !isPalette)_x000D_
{_x000D_
spacing = frame.isClosable() ? 2 : 4; //10 : 40_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
maxButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
_x000D_
if (frame.isIconifiable())// && !isPalette)_x000D_
{_x000D_
spacing = frame.isMaximizable() ? 2 : (frame.isClosable() ? 10_x000D_
: 4);_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
iconButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
_x000D_
buttonsWidth = leftToRight ? w - x : x;_x000D_
}_x000D_
}_x000D_
_x000D_
// public void paintPalette(Graphics g)_x000D_
// {_x000D_
// boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
//_x000D_
// int width = getWidth();_x000D_
// int height = getHeight();_x000D_
//_x000D_
// Color background = MetalLookAndFeel.getPrimaryControlShadow();_x000D_
// Color darkShadow = MetalLookAndFeel.getPrimaryControlDarkShadow();_x000D_
//_x000D_
// NLTitlePane.paintTitlePane(g, 0, 0, width , height, false_x000D_
// , background, darkShadow);_x000D_
// }_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#paintComponent(java.awt.Graphics)_x000D_
*/_x000D_
public void paintComponent(Graphics g)_x000D_
{_x000D_
// if (isPalette)_x000D_
// {_x000D_
// paintPalette(g);_x000D_
// return;_x000D_
// }_x000D_
_x000D_
boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
boolean isSelected = frame.isSelected();//! 选中与否的判断方式,参见border部分的注释_x000D_
_x000D_
int width = getWidth();_x000D_
int height = getHeight();_x000D_
_x000D_
Color background = null;_x000D_
Color foreground = null;_x000D_
Color shadow = null;_x000D_
_x000D_
if (isSelected)_x000D_
{_x000D_
// if (!true)_x000D_
// {_x000D_
// closeButton.setContentAreaFilled(true);_x000D_
// maxButton.setContentAreaFilled(true);_x000D_
// iconButton.setContentAreaFilled(true);_x000D_
// }_x000D_
if (selectedBackgroundKey != null)_x000D_
{_x000D_
background = UIManager.getColor(selectedBackgroundKey);_x000D_
}_x000D_
if (background == null)_x000D_
{_x000D_
background = UIManager.getColor("activeCaption");_x000D_
}_x000D_
if (selectedForegroundKey != null)_x000D_
{_x000D_
foreground = UIManager.getColor(selectedForegroundKey);_x000D_
}_x000D_
if (selectedShadowKey != null)_x000D_
{_x000D_
shadow = UIManager.getColor(selectedShadowKey);_x000D_
}_x000D_
if (shadow == null)_x000D_
{_x000D_
shadow = UIManager.getColor("activeCaptionBorder");_x000D_
}_x000D_
if (foreground == null)_x000D_
{_x000D_
foreground = UIManager.getColor("activeCaptionText");_x000D_
}_x000D_
}_x000D_
else_x000D_
{_x000D_
if (!true)_x000D_
{_x000D_
closeButton.setContentAreaFilled(false);_x000D_
maxButton.setContentAreaFilled(false);_x000D_
iconButton.setContentAreaFilled(false);_x000D_
}_x000D_
background = UIManager.getColor("inactiveCaption");_x000D_
foreground = UIManager.getColor("inactiveCaptionText");_x000D_
shadow = UIManager.getColor("inactiveCaptionBorder");_x000D_
}_x000D_
_x000D_
//---------------------------------------------------绘制标题栏背景_x000D_
// Color topDarkShadow2 = LNFUtils.getColor(_x000D_
// background, -40, -40, -40)_x000D_
// ,topHightLight2 = LNFUtils.getColor(background,_x000D_
// 60, 60, 60)_x000D_
// ,topDarkHightLight2 = LNFUtils.getColor(background,_x000D_
// 20, 20, 20);_x000D_
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景START */_x000D_
/*_x000D_
* ** bug修正 by js,2009-09-30(这因是JDK1.5的Swing底层BUG)_x000D_
* _x000D_
* BUG描述:当操作系统的主题切换时,JInternalFrame有时相同的方法this.getBounds()获得的结果是不一样的_x000D_
* ,这种差异主要在于有时this.getBounds()获得的结果并未包括它的border,主要表现就是结果_x000D_
* 的(x,y)的坐标是未包含border的坐标,因而这种情况下它的(x=0,y=0),而正确应该_x000D_
* (x=border.insets.left,y=border.insets.top),如果无视此bug,则titlePane_x000D_
* 在填充时会变的丑陋。_x000D_
* _x000D_
* 解决方法:当确知这个bug发生后,只能以人工方式弥补这种异相,如 强制修正其(x,y)的坐标,并相应地调整_x000D_
* titlePane的填充区域。_x000D_
*/_x000D_
// Border b=frame.getBorder();_x000D_
// Insets is=b.getBorderInsets(frame);_x000D_
// Rectangle bounds = this.getBounds();_x000D_
// int paintTitlePaneX = bounds.x,paintTitlePaneY = bounds.y;_x000D_
//// boolean isBUG = false;_x000D_
////// System.out.println("JInternalFrame的UI是否处于正常isBUG="+isBUG);_x000D_
//// if(isBUG=(is.left!=bounds.x))//当is.left!=bounds.x即可认定已经产生了BUG_x000D_
//// paintTitlePaneX = is.left;_x000D_
//// if(isBUG=(is.top!=bounds.y))//当is.left!=bounds.x同样可认定已经产生了BUG_x000D_
//// paintTitlePaneY = is.top;_x000D_
//// if(isBUG)//有BUG时的填充_x000D_
//// {_x000D_
//// //----------------------------- 以下代码是为了弥补因BUG而产生的填充异常_x000D_
//// //*以下(1),(2),(3)部分代码是用于弥补BUG下的border外观被titlePane覆盖的错误_x000D_
//// //*请参见JInternalFrameDialogBorder的边框填充代码(尽量在此处模拟出边框的TOP部分效果)>_x000D_
//// //水平第一条线(1)_x000D_
//// g.setColor(topDarkShadow2);_x000D_
//// g.drawLine(0, 0, width, 0);_x000D_
//// g.drawLine(0, 1, 0, height);//左坚线_x000D_
//// g.drawLine(width, 1, width, height);//右坚线_x000D_
//// //水平第二条线(2)_x000D_
//// g.setColor(topHightLight2);_x000D_
//// g.drawLine(1, 1, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 1);_x000D_
//// //水平第三条线(3)_x000D_
//// g.setColor(topDarkHightLight2);_x000D_
//// g.drawLine(2, 2, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 2);_x000D_
//// _x000D_
//// NLTitlePane.paintTitlePane(g//左右空起的部分由Border绘制_x000D_
//// , paintTitlePaneX//ZCMetalBorders.InternalFrameDialogBorder.insets.left_x000D_
//// , paintTitlePaneY//ZCMetalBorders.InternalFrameDialogBorder.insets.left_x000D_
//// , width-is.left*2 //注意此处也因BUG而作了填充区域的调整_x000D_
//// , height, isSelected_x000D_
//// , background, shadow);_x000D_
//// //----------------------------- END_x000D_
//// }_x000D_
//// //正常无BUG时的填充_x000D_
//// else_x000D_
{_x000D_
Insets frameInsets = frame.getInsets();_x000D_
//** Swing BUG:按理说,此处是不需要传入frameInstes的,因父类BasicInternalFrameTitlePane的布局_x000D_
//是存在BUG(布计算时没有把BorderInstes算入到x、y的偏移中,导致UI中paint时只能自行_x000D_
//进行增益,否则填充的图璩形肯定就因没有算上borderInstes而错位,详见父类中的_x000D_
//BasicInternalFrameTitlePane中内部类Handler的layoutContainer方法里_x000D_
//getNorthPane().setBounds(..)这一段_x000D_
// NLTitlePane.paintTitlePane(g_x000D_
// , frameInsets.left//0_x000D_
// , frameInsets.top//0_x000D_
// , width-frameInsets.left-frameInsets.right//-0_x000D_
// , height, isSelected_x000D_
//// , background, shadow_x000D_
// );_x000D_
paintTitlePaneImpl(frameInsets, g, width,height, isSelected);_x000D_
}_x000D_
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景END */_x000D_
_x000D_
//----------------------------------------------------绘制标题及图标_x000D_
int titleLength = 0;_x000D_
int xOffset = leftToRight ? 5 : width - 5;_x000D_
String frameTitle = frame.getTitle();_x000D_
_x000D_
Icon icon = frame.getFrameIcon();_x000D_
if (icon != null)_x000D_
{_x000D_
if (!leftToRight)_x000D_
xOffset -= icon.getIconWidth();_x000D_
int iconY = ((height / 2) - (icon.getIconHeight() / 2));_x000D_
icon.paintIcon(frame, g, xOffset +2, iconY+1);//默认是xOffset +0, iconY+0_x000D_
xOffset += leftToRight ? icon.getIconWidth() + 5 : -5;_x000D_
}_x000D_
_x000D_
if (frameTitle != null)_x000D_
{_x000D_
Font f = getFont();_x000D_
g.setFont(f);_x000D_
FontMetrics fm = MySwingUtilities2.getFontMetrics(frame, g, f);_x000D_
int fHeight = fm.getHeight();_x000D_
_x000D_
int yOffset = ((height - fm.getHeight()) / 2) + fm.getAscent();_x000D_
_x000D_
Rectangle rect = new Rectangle(0, 0, 0, 0);_x000D_
if (frame.isIconifiable())_x000D_
{_x000D_
rect = iconButton.getBounds();_x000D_
}_x000D_
else if (frame.isMaximizable())_x000D_
{_x000D_
rect = maxButton.getBounds();_x000D_
}_x000D_
else if (frame.isClosable())_x000D_
{_x000D_
rect = closeButton.getBounds();_x000D_
}_x000D_
int titleW;_x000D_
_x000D_
if (leftToRight)_x000D_
{_x000D_
if (rect.x == 0)_x000D_
{_x000D_
rect.x = frame.getWidth() - frame.getInsets().right - 2;_x000D_
}_x000D_
titleW = rect.x - xOffset - 4;_x000D_
frameTitle = getTitle(frameTitle, fm, titleW);_x000D_
}_x000D_
else_x000D_
{_x000D_
titleW = xOffset - rect.x - rect.width - 4;_x000D_
frameTitle = getTitle(frameTitle, fm, titleW);_x000D_
xOffset -= MySwingUtilities2.stringWidth(frame, fm, frameTitle);_x000D_
}_x000D_
_x000D_
titleLength = MySwingUtilities2.stringWidth(frame, fm, frameTitle);_x000D_
_x000D_
// g.setColor(Color.DARK_GRAY);//_x000D_
// NLUtils.drawString(frame, g, frameTitle, xOffset+1, yOffset+1);_x000D_
g.setColor(foreground);_x000D_
// if(NLLookAndFeel.windowTitleAntialising)_x000D_
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,true);_x000D_
MySwingUtilities2.drawString(frame, g, frameTitle, xOffset, yOffset);_x000D_
// if(NLLookAndFeel.windowTitleAntialising)_x000D_
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,false);_x000D_
xOffset += leftToRight ? titleLength + 5 : -5;_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Paint title pane impl._x000D_
*_x000D_
* @param frameInsets the frame insets_x000D_
* @param g the g_x000D_
* @param width the width_x000D_
* @param height the height_x000D_
* @param isSelected the is selected_x000D_
*/_x000D_
protected void paintTitlePaneImpl(Insets frameInsets,Graphics g_x000D_
, int width,int height, boolean isSelected)_x000D_
{_x000D_
BETitlePane.paintTitlePane(g_x000D_
, frameInsets.left//0_x000D_
, frameInsets.top//0_x000D_
, width-frameInsets.left-frameInsets.right//-0_x000D_
, height, isSelected_x000D_
// , background, shadow_x000D_
);_x000D_
}_x000D_
_x000D_
// public void setPalette(boolean b)_x000D_
// {_x000D_
// isPalette = b;_x000D_
//_x000D_
// if (isPalette)_x000D_
// {_x000D_
// closeButton.setIcon(paletteCloseIcon);_x000D_
// if (frame.isMaximizable())_x000D_
// remove(maxButton);_x000D_
// if (frame.isIconifiable())_x000D_
// remove(iconButton);_x000D_
// }_x000D_
// else_x000D_
// {_x000D_
// closeButton.setIcon(closeIcon);_x000D_
// if (frame.isMaximizable())_x000D_
// add(maxButton);_x000D_
// if (frame.isIconifiable())_x000D_
// add(iconButton);_x000D_
// }_x000D_
// revalidate();_x000D_
// repaint();_x000D_
// }_x000D_
_x000D_
/**_x000D_
* Updates any state dependant upon the JInternalFrame being shown in_x000D_
* a <code>JOptionPane</code>._x000D_
*/_x000D_
private void updateOptionPaneState()_x000D_
{_x000D_
int type = -2;_x000D_
boolean closable = wasClosable;_x000D_
Object obj = frame.getClientProperty("JInternalFrame.messageType");_x000D_
_x000D_
if (obj == null)_x000D_
{_x000D_
// Don't change the closable state unless in an JOptionPane._x000D_
return;_x000D_
}_x000D_
if (obj instanceof Integer)_x000D_
{_x000D_
type = ((Integer) obj).intValue();_x000D_
}_x000D_
switch (type)_x000D_
{_x000D_
case JOptionPane.ERROR_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.errorDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.errorDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.QUESTION_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.questionDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.questionDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.questionDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.WARNING_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.warningDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.warningDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.INFORMATION_MESSAGE:_x000D_
case JOptionPane.PLAIN_MESSAGE:_x000D_
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;_x000D_
closable = false;_x000D_
break;_x000D_
default:_x000D_
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;_x000D_
break;_x000D_
}_x000D_
if (closable != frame.isClosable())_x000D_
{_x000D_
frame.setClosable(closable);_x000D_
}_x000D_
}_x000D_
_x000D_
//改变父类的方法的可见性为public,方便外界调用,仅此而已,_x000D_
//modified by jb2011_x000D_
//@see com.sun.java.swing.plaf.windows.uninstallListeners()_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallListeners()_x000D_
*/_x000D_
public void uninstallListeners() {_x000D_
// Get around protected method in superclass_x000D_
super.uninstallListeners();_x000D_
}_x000D_
}_x000D_
| JackJiang2011/beautyeye | src_all/beautyeye_v3.7_utf8/src/org/jb2011/lnf/beautyeye/ch10_internalframe/BEInternalFrameTitlePane.java | 7,920 | // getHeight() - 4);_x000D_ | line_comment | nl | /*_x000D_
* Copyright (C) 2015 Jack Jiang(cngeeker.com) The BeautyEye Project. _x000D_
* All rights reserved._x000D_
* Project URL:https://github.com/JackJiang2011/beautyeye_x000D_
* Version 3.6_x000D_
* _x000D_
* Jack Jiang PROPRIETARY/CONFIDENTIAL. Use is subject to license terms._x000D_
* _x000D_
* BEInternalFrameTitlePane.java at 2015-2-1 20:25:36, original version by Jack Jiang._x000D_
* You can contact author with jb2011@163.com._x000D_
*/_x000D_
package org.jb2011.lnf.beautyeye.ch10_internalframe;_x000D_
_x000D_
import java.awt.Color;_x000D_
import java.awt.Component;_x000D_
import java.awt.Container;_x000D_
import java.awt.Dimension;_x000D_
import java.awt.Font;_x000D_
import java.awt.FontMetrics;_x000D_
import java.awt.Graphics;_x000D_
import java.awt.Insets;_x000D_
import java.awt.LayoutManager;_x000D_
import java.awt.Rectangle;_x000D_
import java.beans.PropertyChangeEvent;_x000D_
import java.beans.PropertyChangeListener;_x000D_
_x000D_
import javax.swing.Icon;_x000D_
import javax.swing.JInternalFrame;_x000D_
import javax.swing.JMenu;_x000D_
import javax.swing.JOptionPane;_x000D_
import javax.swing.UIManager;_x000D_
import javax.swing.border.Border;_x000D_
import javax.swing.border.EmptyBorder;_x000D_
import javax.swing.plaf.basic.BasicInternalFrameTitlePane;_x000D_
import javax.swing.plaf.metal.MetalLookAndFeel;_x000D_
_x000D_
import org.jb2011.lnf.beautyeye.ch1_titlepane.BETitlePane;_x000D_
import org.jb2011.lnf.beautyeye.utils.MySwingUtilities2;_x000D_
import org.jb2011.lnf.beautyeye.winlnfutils.WinUtils;_x000D_
_x000D_
/**_x000D_
* 内部窗体的标题栏UI实现._x000D_
* _x000D_
* @author Jack Jiang_x000D_
*/_x000D_
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 Start_x000D_
//BeautyEye外观实现中取消了isPalette的所有特殊处理,isPalette及相关属性在_x000D_
//该外观中将失去意义,请注意!_x000D_
//虽然beautyEye是参考自MetalLookAndFeel,但因beautyEye使用了Insets很大的立体边框,_x000D_
//则如果还要像MetalLookAndFeel实现Palette类型的JInternalFrame则效果会很难看,干脆就就像_x000D_
//WindowsLookAndFeel一样,不去理会什么Palette,在当前的L&F下没有任何减分。_x000D_
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 一些说明 END_x000D_
public class BEInternalFrameTitlePane extends BasicInternalFrameTitlePane_x000D_
{_x000D_
// protected boolean isPalette = false;_x000D_
// protected Icon paletteCloseIcon;_x000D_
// protected int paletteTitleHeight;_x000D_
_x000D_
/** The Constant handyEmptyBorder. */_x000D_
private static final Border handyEmptyBorder = new EmptyBorder(0, 0, 0, 0);_x000D_
_x000D_
/**_x000D_
* Key used to lookup Color from UIManager. If this is null,_x000D_
* <code>getWindowTitleBackground</code> is used._x000D_
*/_x000D_
private String selectedBackgroundKey;_x000D_
/**_x000D_
* Key used to lookup Color from UIManager. If this is null,_x000D_
* <code>getWindowTitleForeground</code> is used._x000D_
*/_x000D_
private String selectedForegroundKey;_x000D_
/**_x000D_
* Key used to lookup shadow color from UIManager. If this is null,_x000D_
* <code>getPrimaryControlDarkShadow</code> is used._x000D_
*/_x000D_
private String selectedShadowKey;_x000D_
/**_x000D_
* Boolean indicating the state of the <code>JInternalFrame</code>s_x000D_
* closable property at <code>updateUI</code> time._x000D_
*/_x000D_
private boolean wasClosable;_x000D_
_x000D_
/** The buttons width. */_x000D_
int buttonsWidth = 0;_x000D_
_x000D_
/**_x000D_
* Instantiates a new bE internal frame title pane._x000D_
*_x000D_
* @param f the f_x000D_
*/_x000D_
public BEInternalFrameTitlePane(JInternalFrame f)_x000D_
{_x000D_
super(f);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.JComponent#addNotify()_x000D_
*/_x000D_
public void addNotify()_x000D_
{_x000D_
super.addNotify();_x000D_
// This is done here instead of in installDefaults as I was worried_x000D_
// that the BasicInternalFrameUI might not be fully initialized, and_x000D_
// that if this resets the closable state the BasicInternalFrameUI_x000D_
// Listeners that get notified might be in an odd/uninitialized state._x000D_
updateOptionPaneState();_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#installDefaults()_x000D_
*/_x000D_
protected void installDefaults()_x000D_
{_x000D_
super.installDefaults();_x000D_
setFont(UIManager.getFont("InternalFrame.titleFont"));_x000D_
// paletteTitleHeight = UIManager_x000D_
// .getInt("InternalFrame.paletteTitleHeight");_x000D_
// paletteCloseIcon = UIManager.getIcon("InternalFrame.paletteCloseIcon");_x000D_
wasClosable = frame.isClosable();_x000D_
selectedForegroundKey = selectedBackgroundKey = null;_x000D_
if (true)_x000D_
{_x000D_
setOpaque(false);_x000D_
}_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallDefaults()_x000D_
*/_x000D_
protected void uninstallDefaults()_x000D_
{_x000D_
super.uninstallDefaults();_x000D_
if (wasClosable != frame.isClosable())_x000D_
{_x000D_
frame.setClosable(wasClosable);_x000D_
}_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createButtons()_x000D_
*/_x000D_
protected void createButtons()_x000D_
{_x000D_
super.createButtons();_x000D_
_x000D_
Boolean paintActive = frame.isSelected() ? Boolean.TRUE : Boolean.FALSE;_x000D_
iconButton.putClientProperty("paintActive", paintActive);_x000D_
iconButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
maxButton.putClientProperty("paintActive", paintActive);_x000D_
maxButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
closeButton.putClientProperty("paintActive", paintActive);_x000D_
closeButton.setBorder(handyEmptyBorder);_x000D_
_x000D_
// The palette close icon isn't opaque while the regular close icon is._x000D_
// This makes sure palette close buttons have the right background._x000D_
closeButton.setBackground(MetalLookAndFeel.getPrimaryControlShadow());_x000D_
_x000D_
if (true)_x000D_
{_x000D_
iconButton.setContentAreaFilled(false);_x000D_
maxButton.setContentAreaFilled(false);_x000D_
closeButton.setContentAreaFilled(false);_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not _x000D_
* have system menus._x000D_
*/_x000D_
protected void assembleSystemMenu()_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not_x000D_
* have system menus._x000D_
*_x000D_
* @param systemMenu the system menu_x000D_
*/_x000D_
protected void addSystemMenuItems(JMenu systemMenu)_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method to do nothing. Metal frames do not _x000D_
* have system menus._x000D_
*/_x000D_
protected void showSystemMenu()_x000D_
{_x000D_
}_x000D_
_x000D_
/**_x000D_
* Override the parent's method avoid creating a menu bar. Metal frames_x000D_
* do not have system menus._x000D_
*/_x000D_
protected void addSubComponents()_x000D_
{_x000D_
add(iconButton);_x000D_
add(maxButton);_x000D_
add(closeButton);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createPropertyChangeListener()_x000D_
*/_x000D_
protected PropertyChangeListener createPropertyChangeListener()_x000D_
{_x000D_
return new MetalPropertyChangeHandler();_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#createLayout()_x000D_
*/_x000D_
protected LayoutManager createLayout()_x000D_
{_x000D_
return new XMetalTitlePaneLayout();_x000D_
}_x000D_
_x000D_
/**_x000D_
* The Class MetalPropertyChangeHandler._x000D_
*/_x000D_
class MetalPropertyChangeHandler extends_x000D_
BasicInternalFrameTitlePane.PropertyChangeHandler_x000D_
{_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.PropertyChangeHandler#propertyChange(java.beans.PropertyChangeEvent)_x000D_
*/_x000D_
public void propertyChange(PropertyChangeEvent evt)_x000D_
{_x000D_
String prop = (String) evt.getPropertyName();_x000D_
if (prop.equals(JInternalFrame.IS_SELECTED_PROPERTY))_x000D_
{_x000D_
Boolean b = (Boolean) evt.getNewValue();_x000D_
iconButton.putClientProperty("paintActive", b);_x000D_
closeButton.putClientProperty("paintActive", b);_x000D_
maxButton.putClientProperty("paintActive", b);_x000D_
}_x000D_
else if ("JInternalFrame.messageType".equals(prop))_x000D_
{_x000D_
updateOptionPaneState();_x000D_
frame.repaint();_x000D_
}_x000D_
super.propertyChange(evt); _x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* The Class XZCMetalTitlePaneLayout._x000D_
*/_x000D_
class XMetalTitlePaneLayout extends TitlePaneLayout_x000D_
{_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#addLayoutComponent(java.lang.String, java.awt.Component)_x000D_
*/_x000D_
public void addLayoutComponent(String name, Component c)_x000D_
{_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#removeLayoutComponent(java.awt.Component)_x000D_
*/_x000D_
public void removeLayoutComponent(Component c)_x000D_
{_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#preferredLayoutSize(java.awt.Container)_x000D_
*/_x000D_
public Dimension preferredLayoutSize(Container c)_x000D_
{_x000D_
return minimumLayoutSize(c);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#minimumLayoutSize(java.awt.Container)_x000D_
*/_x000D_
public Dimension minimumLayoutSize(Container c)_x000D_
{_x000D_
// Compute width._x000D_
int width = 30;_x000D_
if (frame.isClosable())_x000D_
{_x000D_
width += 21;_x000D_
}_x000D_
if (frame.isMaximizable())_x000D_
{_x000D_
width += 16 + (frame.isClosable() ? 10 : 4);_x000D_
}_x000D_
if (frame.isIconifiable())_x000D_
{_x000D_
width += 16 + (frame.isMaximizable() ? 2_x000D_
: (frame.isClosable() ? 10 : 4));_x000D_
}_x000D_
FontMetrics fm = frame.getFontMetrics(getFont());_x000D_
String frameTitle = frame.getTitle();_x000D_
int title_w = frameTitle != null ? MySwingUtilities2.stringWidth(_x000D_
frame, fm, frameTitle) : 0;_x000D_
int title_length = frameTitle != null ? frameTitle.length() : 0;_x000D_
_x000D_
if (title_length > 2)_x000D_
{_x000D_
int subtitle_w = MySwingUtilities2.stringWidth(frame, fm, frame_x000D_
.getTitle().substring(0, 2)_x000D_
+ "...");_x000D_
width += (title_w < subtitle_w) ? title_w : subtitle_w;_x000D_
}_x000D_
else_x000D_
{_x000D_
width += title_w;_x000D_
}_x000D_
_x000D_
// Compute height._x000D_
int height = 0;_x000D_
_x000D_
// if (isPalette)_x000D_
// {_x000D_
// height = paletteTitleHeight;_x000D_
// }_x000D_
// else_x000D_
{_x000D_
int fontHeight = fm.getHeight();_x000D_
fontHeight += 4;//默认是 +=7 _x000D_
Icon icon = frame.getFrameIcon();_x000D_
int iconHeight = 0;_x000D_
if (icon != null)_x000D_
{_x000D_
// SystemMenuBar forces the icon to be 16x16 or less._x000D_
iconHeight = Math.min(icon.getIconHeight(), 16);_x000D_
}_x000D_
iconHeight += 5;_x000D_
height = Math.max(fontHeight, iconHeight) + 5;//默认是 +0,modified by jb2011 2012-06-18_x000D_
}_x000D_
_x000D_
return new Dimension(width, height);_x000D_
}_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane.TitlePaneLayout#layoutContainer(java.awt.Container)_x000D_
*/_x000D_
public void layoutContainer(Container c)_x000D_
{_x000D_
boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
_x000D_
int w = getWidth();_x000D_
int x = leftToRight ? w : 0;_x000D_
int y = 5;//默认是0,modified by jb2011_x000D_
int spacing;_x000D_
_x000D_
// assumes all buttons have the same dimensions_x000D_
// these dimensions include the borders_x000D_
int buttonHeight = closeButton.getIcon().getIconHeight();_x000D_
int buttonWidth = closeButton.getIcon().getIconWidth();_x000D_
_x000D_
if (frame.isClosable())_x000D_
{_x000D_
// if (isPalette)_x000D_
// {_x000D_
// spacing = 3;_x000D_
// x += leftToRight ? -spacing - (buttonWidth + 2) : spacing;_x000D_
// closeButton.setBounds(x, y, buttonWidth + 2,_x000D_
// getHeight() -<SUF>
// if (!leftToRight)_x000D_
// x += (buttonWidth + 2);_x000D_
// }_x000D_
// else_x000D_
{_x000D_
spacing = 4;_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
closeButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
}_x000D_
_x000D_
if (frame.isMaximizable())// && !isPalette)_x000D_
{_x000D_
spacing = frame.isClosable() ? 2 : 4; //10 : 40_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
maxButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
_x000D_
if (frame.isIconifiable())// && !isPalette)_x000D_
{_x000D_
spacing = frame.isMaximizable() ? 2 : (frame.isClosable() ? 10_x000D_
: 4);_x000D_
x += leftToRight ? -spacing - buttonWidth : spacing;_x000D_
iconButton.setBounds(x, y, buttonWidth, buttonHeight);_x000D_
if (!leftToRight)_x000D_
x += buttonWidth;_x000D_
}_x000D_
_x000D_
buttonsWidth = leftToRight ? w - x : x;_x000D_
}_x000D_
}_x000D_
_x000D_
// public void paintPalette(Graphics g)_x000D_
// {_x000D_
// boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
//_x000D_
// int width = getWidth();_x000D_
// int height = getHeight();_x000D_
//_x000D_
// Color background = MetalLookAndFeel.getPrimaryControlShadow();_x000D_
// Color darkShadow = MetalLookAndFeel.getPrimaryControlDarkShadow();_x000D_
//_x000D_
// NLTitlePane.paintTitlePane(g, 0, 0, width , height, false_x000D_
// , background, darkShadow);_x000D_
// }_x000D_
_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#paintComponent(java.awt.Graphics)_x000D_
*/_x000D_
public void paintComponent(Graphics g)_x000D_
{_x000D_
// if (isPalette)_x000D_
// {_x000D_
// paintPalette(g);_x000D_
// return;_x000D_
// }_x000D_
_x000D_
boolean leftToRight = WinUtils.isLeftToRight(frame);_x000D_
boolean isSelected = frame.isSelected();//! 选中与否的判断方式,参见border部分的注释_x000D_
_x000D_
int width = getWidth();_x000D_
int height = getHeight();_x000D_
_x000D_
Color background = null;_x000D_
Color foreground = null;_x000D_
Color shadow = null;_x000D_
_x000D_
if (isSelected)_x000D_
{_x000D_
// if (!true)_x000D_
// {_x000D_
// closeButton.setContentAreaFilled(true);_x000D_
// maxButton.setContentAreaFilled(true);_x000D_
// iconButton.setContentAreaFilled(true);_x000D_
// }_x000D_
if (selectedBackgroundKey != null)_x000D_
{_x000D_
background = UIManager.getColor(selectedBackgroundKey);_x000D_
}_x000D_
if (background == null)_x000D_
{_x000D_
background = UIManager.getColor("activeCaption");_x000D_
}_x000D_
if (selectedForegroundKey != null)_x000D_
{_x000D_
foreground = UIManager.getColor(selectedForegroundKey);_x000D_
}_x000D_
if (selectedShadowKey != null)_x000D_
{_x000D_
shadow = UIManager.getColor(selectedShadowKey);_x000D_
}_x000D_
if (shadow == null)_x000D_
{_x000D_
shadow = UIManager.getColor("activeCaptionBorder");_x000D_
}_x000D_
if (foreground == null)_x000D_
{_x000D_
foreground = UIManager.getColor("activeCaptionText");_x000D_
}_x000D_
}_x000D_
else_x000D_
{_x000D_
if (!true)_x000D_
{_x000D_
closeButton.setContentAreaFilled(false);_x000D_
maxButton.setContentAreaFilled(false);_x000D_
iconButton.setContentAreaFilled(false);_x000D_
}_x000D_
background = UIManager.getColor("inactiveCaption");_x000D_
foreground = UIManager.getColor("inactiveCaptionText");_x000D_
shadow = UIManager.getColor("inactiveCaptionBorder");_x000D_
}_x000D_
_x000D_
//---------------------------------------------------绘制标题栏背景_x000D_
// Color topDarkShadow2 = LNFUtils.getColor(_x000D_
// background, -40, -40, -40)_x000D_
// ,topHightLight2 = LNFUtils.getColor(background,_x000D_
// 60, 60, 60)_x000D_
// ,topDarkHightLight2 = LNFUtils.getColor(background,_x000D_
// 20, 20, 20);_x000D_
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景START */_x000D_
/*_x000D_
* ** bug修正 by js,2009-09-30(这因是JDK1.5的Swing底层BUG)_x000D_
* _x000D_
* BUG描述:当操作系统的主题切换时,JInternalFrame有时相同的方法this.getBounds()获得的结果是不一样的_x000D_
* ,这种差异主要在于有时this.getBounds()获得的结果并未包括它的border,主要表现就是结果_x000D_
* 的(x,y)的坐标是未包含border的坐标,因而这种情况下它的(x=0,y=0),而正确应该_x000D_
* (x=border.insets.left,y=border.insets.top),如果无视此bug,则titlePane_x000D_
* 在填充时会变的丑陋。_x000D_
* _x000D_
* 解决方法:当确知这个bug发生后,只能以人工方式弥补这种异相,如 强制修正其(x,y)的坐标,并相应地调整_x000D_
* titlePane的填充区域。_x000D_
*/_x000D_
// Border b=frame.getBorder();_x000D_
// Insets is=b.getBorderInsets(frame);_x000D_
// Rectangle bounds = this.getBounds();_x000D_
// int paintTitlePaneX = bounds.x,paintTitlePaneY = bounds.y;_x000D_
//// boolean isBUG = false;_x000D_
////// System.out.println("JInternalFrame的UI是否处于正常isBUG="+isBUG);_x000D_
//// if(isBUG=(is.left!=bounds.x))//当is.left!=bounds.x即可认定已经产生了BUG_x000D_
//// paintTitlePaneX = is.left;_x000D_
//// if(isBUG=(is.top!=bounds.y))//当is.left!=bounds.x同样可认定已经产生了BUG_x000D_
//// paintTitlePaneY = is.top;_x000D_
//// if(isBUG)//有BUG时的填充_x000D_
//// {_x000D_
//// //----------------------------- 以下代码是为了弥补因BUG而产生的填充异常_x000D_
//// //*以下(1),(2),(3)部分代码是用于弥补BUG下的border外观被titlePane覆盖的错误_x000D_
//// //*请参见JInternalFrameDialogBorder的边框填充代码(尽量在此处模拟出边框的TOP部分效果)>_x000D_
//// //水平第一条线(1)_x000D_
//// g.setColor(topDarkShadow2);_x000D_
//// g.drawLine(0, 0, width, 0);_x000D_
//// g.drawLine(0, 1, 0, height);//左坚线_x000D_
//// g.drawLine(width, 1, width, height);//右坚线_x000D_
//// //水平第二条线(2)_x000D_
//// g.setColor(topHightLight2);_x000D_
//// g.drawLine(1, 1, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 1);_x000D_
//// //水平第三条线(3)_x000D_
//// g.setColor(topDarkHightLight2);_x000D_
//// g.drawLine(2, 2, width-NLMetalBorders.InternalFrameDialogBorder.insets.left, 2);_x000D_
//// _x000D_
//// NLTitlePane.paintTitlePane(g//左右空起的部分由Border绘制_x000D_
//// , paintTitlePaneX//ZCMetalBorders.InternalFrameDialogBorder.insets.left_x000D_
//// , paintTitlePaneY//ZCMetalBorders.InternalFrameDialogBorder.insets.left_x000D_
//// , width-is.left*2 //注意此处也因BUG而作了填充区域的调整_x000D_
//// , height, isSelected_x000D_
//// , background, shadow);_x000D_
//// //----------------------------- END_x000D_
//// }_x000D_
//// //正常无BUG时的填充_x000D_
//// else_x000D_
{_x000D_
Insets frameInsets = frame.getInsets();_x000D_
//** Swing BUG:按理说,此处是不需要传入frameInstes的,因父类BasicInternalFrameTitlePane的布局_x000D_
//是存在BUG(布计算时没有把BorderInstes算入到x、y的偏移中,导致UI中paint时只能自行_x000D_
//进行增益,否则填充的图璩形肯定就因没有算上borderInstes而错位,详见父类中的_x000D_
//BasicInternalFrameTitlePane中内部类Handler的layoutContainer方法里_x000D_
//getNorthPane().setBounds(..)这一段_x000D_
// NLTitlePane.paintTitlePane(g_x000D_
// , frameInsets.left//0_x000D_
// , frameInsets.top//0_x000D_
// , width-frameInsets.left-frameInsets.right//-0_x000D_
// , height, isSelected_x000D_
//// , background, shadow_x000D_
// );_x000D_
paintTitlePaneImpl(frameInsets, g, width,height, isSelected);_x000D_
}_x000D_
/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 绘制标题栏背景END */_x000D_
_x000D_
//----------------------------------------------------绘制标题及图标_x000D_
int titleLength = 0;_x000D_
int xOffset = leftToRight ? 5 : width - 5;_x000D_
String frameTitle = frame.getTitle();_x000D_
_x000D_
Icon icon = frame.getFrameIcon();_x000D_
if (icon != null)_x000D_
{_x000D_
if (!leftToRight)_x000D_
xOffset -= icon.getIconWidth();_x000D_
int iconY = ((height / 2) - (icon.getIconHeight() / 2));_x000D_
icon.paintIcon(frame, g, xOffset +2, iconY+1);//默认是xOffset +0, iconY+0_x000D_
xOffset += leftToRight ? icon.getIconWidth() + 5 : -5;_x000D_
}_x000D_
_x000D_
if (frameTitle != null)_x000D_
{_x000D_
Font f = getFont();_x000D_
g.setFont(f);_x000D_
FontMetrics fm = MySwingUtilities2.getFontMetrics(frame, g, f);_x000D_
int fHeight = fm.getHeight();_x000D_
_x000D_
int yOffset = ((height - fm.getHeight()) / 2) + fm.getAscent();_x000D_
_x000D_
Rectangle rect = new Rectangle(0, 0, 0, 0);_x000D_
if (frame.isIconifiable())_x000D_
{_x000D_
rect = iconButton.getBounds();_x000D_
}_x000D_
else if (frame.isMaximizable())_x000D_
{_x000D_
rect = maxButton.getBounds();_x000D_
}_x000D_
else if (frame.isClosable())_x000D_
{_x000D_
rect = closeButton.getBounds();_x000D_
}_x000D_
int titleW;_x000D_
_x000D_
if (leftToRight)_x000D_
{_x000D_
if (rect.x == 0)_x000D_
{_x000D_
rect.x = frame.getWidth() - frame.getInsets().right - 2;_x000D_
}_x000D_
titleW = rect.x - xOffset - 4;_x000D_
frameTitle = getTitle(frameTitle, fm, titleW);_x000D_
}_x000D_
else_x000D_
{_x000D_
titleW = xOffset - rect.x - rect.width - 4;_x000D_
frameTitle = getTitle(frameTitle, fm, titleW);_x000D_
xOffset -= MySwingUtilities2.stringWidth(frame, fm, frameTitle);_x000D_
}_x000D_
_x000D_
titleLength = MySwingUtilities2.stringWidth(frame, fm, frameTitle);_x000D_
_x000D_
// g.setColor(Color.DARK_GRAY);//_x000D_
// NLUtils.drawString(frame, g, frameTitle, xOffset+1, yOffset+1);_x000D_
g.setColor(foreground);_x000D_
// if(NLLookAndFeel.windowTitleAntialising)_x000D_
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,true);_x000D_
MySwingUtilities2.drawString(frame, g, frameTitle, xOffset, yOffset);_x000D_
// if(NLLookAndFeel.windowTitleAntialising)_x000D_
// NLLookAndFeel.setAntiAliasing((Graphics2D) g,false);_x000D_
xOffset += leftToRight ? titleLength + 5 : -5;_x000D_
}_x000D_
}_x000D_
_x000D_
/**_x000D_
* Paint title pane impl._x000D_
*_x000D_
* @param frameInsets the frame insets_x000D_
* @param g the g_x000D_
* @param width the width_x000D_
* @param height the height_x000D_
* @param isSelected the is selected_x000D_
*/_x000D_
protected void paintTitlePaneImpl(Insets frameInsets,Graphics g_x000D_
, int width,int height, boolean isSelected)_x000D_
{_x000D_
BETitlePane.paintTitlePane(g_x000D_
, frameInsets.left//0_x000D_
, frameInsets.top//0_x000D_
, width-frameInsets.left-frameInsets.right//-0_x000D_
, height, isSelected_x000D_
// , background, shadow_x000D_
);_x000D_
}_x000D_
_x000D_
// public void setPalette(boolean b)_x000D_
// {_x000D_
// isPalette = b;_x000D_
//_x000D_
// if (isPalette)_x000D_
// {_x000D_
// closeButton.setIcon(paletteCloseIcon);_x000D_
// if (frame.isMaximizable())_x000D_
// remove(maxButton);_x000D_
// if (frame.isIconifiable())_x000D_
// remove(iconButton);_x000D_
// }_x000D_
// else_x000D_
// {_x000D_
// closeButton.setIcon(closeIcon);_x000D_
// if (frame.isMaximizable())_x000D_
// add(maxButton);_x000D_
// if (frame.isIconifiable())_x000D_
// add(iconButton);_x000D_
// }_x000D_
// revalidate();_x000D_
// repaint();_x000D_
// }_x000D_
_x000D_
/**_x000D_
* Updates any state dependant upon the JInternalFrame being shown in_x000D_
* a <code>JOptionPane</code>._x000D_
*/_x000D_
private void updateOptionPaneState()_x000D_
{_x000D_
int type = -2;_x000D_
boolean closable = wasClosable;_x000D_
Object obj = frame.getClientProperty("JInternalFrame.messageType");_x000D_
_x000D_
if (obj == null)_x000D_
{_x000D_
// Don't change the closable state unless in an JOptionPane._x000D_
return;_x000D_
}_x000D_
if (obj instanceof Integer)_x000D_
{_x000D_
type = ((Integer) obj).intValue();_x000D_
}_x000D_
switch (type)_x000D_
{_x000D_
case JOptionPane.ERROR_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.errorDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.errorDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.errorDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.QUESTION_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.questionDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.questionDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.questionDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.WARNING_MESSAGE:_x000D_
selectedBackgroundKey = "OptionPane.warningDialog.titlePane.background";_x000D_
selectedForegroundKey = "OptionPane.warningDialog.titlePane.foreground";_x000D_
selectedShadowKey = "OptionPane.warningDialog.titlePane.shadow";_x000D_
closable = false;_x000D_
break;_x000D_
case JOptionPane.INFORMATION_MESSAGE:_x000D_
case JOptionPane.PLAIN_MESSAGE:_x000D_
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;_x000D_
closable = false;_x000D_
break;_x000D_
default:_x000D_
selectedBackgroundKey = selectedForegroundKey = selectedShadowKey = null;_x000D_
break;_x000D_
}_x000D_
if (closable != frame.isClosable())_x000D_
{_x000D_
frame.setClosable(closable);_x000D_
}_x000D_
}_x000D_
_x000D_
//改变父类的方法的可见性为public,方便外界调用,仅此而已,_x000D_
//modified by jb2011_x000D_
//@see com.sun.java.swing.plaf.windows.uninstallListeners()_x000D_
/* (non-Javadoc)_x000D_
* @see javax.swing.plaf.basic.BasicInternalFrameTitlePane#uninstallListeners()_x000D_
*/_x000D_
public void uninstallListeners() {_x000D_
// Get around protected method in superclass_x000D_
super.uninstallListeners();_x000D_
}_x000D_
}_x000D_
| False |
1,355 | 70583_7 |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen in de int array
mapID++;
int mapIcon = this.map[y][x];
//if (mapIcon == -1) {
// continue;
//}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen van het object.
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (row * TILE_HEIGHT) + TILE_HEIGHT / 2;
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| ROCMondriaanTIN/project-greenfoot-game-20Jorden01 | TileEngine.java | 2,484 | // Nummer ophalen in de int array | line_comment | nl |
import greenfoot.*;
import java.util.List;
/**
*
* @author R. Springer
*/
public class TileEngine {
public static int TILE_WIDTH;
public static int TILE_HEIGHT;
public static int SCREEN_HEIGHT;
public static int SCREEN_WIDTH;
public static int MAP_WIDTH;
public static int MAP_HEIGHT;
private World world;
private int[][] map;
private Tile[][] generateMap;
private TileFactory tileFactory;
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
*/
public TileEngine(World world, int tileWidth, int tileHeight) {
this.world = world;
TILE_WIDTH = tileWidth;
TILE_HEIGHT = tileHeight;
SCREEN_WIDTH = world.getWidth();
SCREEN_HEIGHT = world.getHeight();
this.tileFactory = new TileFactory();
}
/**
* Constuctor of the TileEngine
*
* @param world A World class or a extend of it.
* @param tileWidth The width of the tile used in the TileFactory and
* calculations
* @param tileHeight The heigth of the tile used in the TileFactory and
* calculations
* @param map A tilemap with numbers
*/
public TileEngine(World world, int tileWidth, int tileHeight, int[][] map) {
this(world, tileWidth, tileHeight);
this.setMap(map);
}
/**
* The setMap method used to set a map. This method also clears the previous
* map and generates a new one.
*
* @param map
*/
public void setMap(int[][] map) {
this.clearTilesWorld();
this.map = map;
MAP_HEIGHT = this.map.length;
MAP_WIDTH = this.map[0].length;
this.generateMap = new Tile[MAP_HEIGHT][MAP_WIDTH];
this.generateWorld();
}
/**
* The setTileFactory sets a tilefactory. You can use this if you want to
* create you own tilefacory and use it in the class.
*
* @param tf A Tilefactory or extend of it.
*/
public void setTileFactory(TileFactory tf) {
this.tileFactory = tf;
}
/**
* Removes al the tiles from the world.
*/
public void clearTilesWorld() {
List<Tile> removeObjects = this.world.getObjects(Tile.class);
this.world.removeObjects(removeObjects);
this.map = null;
this.generateMap = null;
MAP_HEIGHT = 0;
MAP_WIDTH = 0;
}
/**
* Creates the tile world based on the TileFactory and the map icons.
*/
public void generateWorld() {
int mapID = 0;
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
// Nummer ophalen<SUF>
mapID++;
int mapIcon = this.map[y][x];
//if (mapIcon == -1) {
// continue;
//}
// Als de mapIcon -1 is dan wordt de code hieronder overgeslagen
// Dus er wordt geen tile aangemaakt. -1 is dus geen tile;
Tile createdTile = this.tileFactory.createTile(mapIcon);
createdTile.setMapID(mapID);
createdTile.setMapIcon(mapIcon);
addTileAt(createdTile, x, y);
}
}
}
/**
* Adds a tile on the colom and row. Calculation is based on TILE_WIDTH and
* TILE_HEIGHT
*
* @param tile The Tile
* @param colom The colom where the tile exist in the map
* @param row The row where the tile exist in the map
*/
public void addTileAt(Tile tile, int colom, int row) {
// De X en Y positie zitten het midden van de Actor.
// De tilemap genereerd een wereld gebaseerd op dat de X en Y
// positie links boven in zitten. Vandaar de we de helft van de
// breedte en hoogte optellen zodat de X en Y links boven zit voor
// het toevoegen van het object.
this.world.addObject(tile, (colom * TILE_WIDTH) + TILE_WIDTH / 2, (row * TILE_HEIGHT) + TILE_HEIGHT / 2);
tile.x = (colom * TILE_WIDTH) + TILE_WIDTH / 2;
tile.y = (row * TILE_HEIGHT) + TILE_HEIGHT / 2;
// Toevoegen aan onze lokale array. Makkelijk om de tile op te halen
// op basis van een x en y positie van de map
this.generateMap[row][colom] = tile;
tile.setColom(colom);
tile.setRow(row);
}
/**
* Retrieves a tile at the location based on colom and row in the map
*
* @param colom
* @param row
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return null;
}
return this.generateMap[row][colom];
}
/**
* Retrieves a tile based on a x and y position in the world
*
* @param x X-position in the world
* @param y Y-position in the world
* @return The tile at the location colom and row. Returns null if it cannot
* find a tile.
*/
public Tile getTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
Tile tile = getTileAt(col, row);
return tile;
}
/**
* Removes tile at the given colom and row
*
* @param colom
* @param row
* @return true if the tile has successfully been removed
*/
public boolean removeTileAt(int colom, int row) {
if (row < 0 || row >= MAP_HEIGHT || colom < 0 || colom >= MAP_WIDTH) {
return false;
}
Tile tile = this.generateMap[row][colom];
if (tile != null) {
this.world.removeObject(tile);
this.generateMap[row][colom] = null;
return true;
}
return false;
}
/**
* Removes tile at the given x and y position
*
* @param x X-position in the world
* @param y Y-position in the world
* @return true if the tile has successfully been removed
*/
public boolean removeTileAtXY(int x, int y) {
int col = getColumn(x);
int row = getRow(y);
return removeTileAt(col, row);
}
/**
* Removes the tile based on a tile
*
* @param tile Tile from the tilemap
* @return true if the tile has successfully been removed
*/
public boolean removeTile(Tile tile) {
int colom = tile.getColom();
int row = tile.getRow();
if (colom != -1 && row != -1) {
return this.removeTileAt(colom, row);
}
return false;
}
/**
* This methode checks if a tile on a x and y position in the world is solid
* or not.
*
* @param x X-position in the world
* @param y Y-position in the world
* @return Tile at location is solid
*/
public boolean checkTileSolid(int x, int y) {
Tile tile = getTileAtXY(x, y);
if (tile != null && tile.isSolid) {
return true;
}
return false;
}
/**
* This methode returns a colom based on a x position.
*
* @param x
* @return the colom
*/
public int getColumn(int x) {
return (int) Math.floor(x / TILE_WIDTH);
}
/**
* This methode returns a row based on a y position.
*
* @param y
* @return the row
*/
public int getRow(int y) {
return (int) Math.floor(y / TILE_HEIGHT);
}
/**
* This methode returns a x position based on the colom
*
* @param col
* @return The x position
*/
public int getX(int col) {
return col * TILE_WIDTH;
}
/**
* This methode returns a y position based on the row
*
* @param row
* @return The y position
*/
public int getY(int row) {
return row * TILE_HEIGHT;
}
}
| True |
2,769 | 155247_16 | package com.gdxsoft.spider;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gdxsoft.easyweb.utils.UFile;
import com.gdxsoft.easyweb.utils.UNet;
public class SpiderBase {
private Document doc_;
private String root_;
private String context_;
private String url_;
private boolean isSkipExists_; // 是否忽略已经存在的,默认false
private String phyPath_; // 列表和文章及图片保存的物理路径
private String urlPath_;// 替换文章的图片地址的根url
private Map<String, String> hashNameMap_;
private static Logger LOOGER = LoggerFactory.getLogger(SpiderBase.class);
public SpiderBase(String url, String phyPath, String urlPath) {
this.url_ = url;
this.phyPath_ = phyPath;
this.urlPath_ = urlPath;
this.hashNameMap_ = new HashMap<String, String>();
}
public void log(Object msg) {
LOOGER.info(msg.toString());
}
/**
* 下载html document
*
* @param url
* 网址
* @return
* @throws IOException
* @throws URISyntaxException
*/
public Document downloadDoc() throws IOException, URISyntaxException {
String exists = this.isSkipExists_ ? null : this.readExists(this.url_);
Document doc;
if (exists != null) {
LOOGER.info("exists: " + this.url_);
doc = Jsoup.parse(exists);
doc.setBaseUri(url_);
doc.getElementsByTag("script").remove();
doc.getElementsByTag("style").remove();
} else {
LOOGER.info("GET: " + this.url_);
int timeout = 100 * 1000; // 100 s
doc = Jsoup.connect(this.url_).userAgent(UNet.AGENT).timeout(timeout).get();
this.saveCache(url_, doc.outerHtml());
}
this.praseRootAndContext(doc);
this.doc_ = doc;
return doc;
}
/**
* 下载图片
*
* @param sourceUrl
* @return
*/
public String downloadImg(String sourceUrl) {
String my_url = this.getHashUrl(sourceUrl);
if (!this.checkFileExists(sourceUrl)) {
// this.log("DL: " + sourceUrl);
UNet net = new UNet();
net.setIsShowLog(true);
try {
byte[] buf = net.downloadData(sourceUrl);
this.saveCache(sourceUrl, buf);
} catch (Exception err) {
LOOGER.error(err.getMessage());
}
} else {
// LOOGER.info("EXISTS: " + sourceUrl);
}
return my_url;
}
/**
* 根据url获取物理文件位置
*
* @param url
* @return
*/
public String getUrlPhyPath(String url) {
String hashName = this.getHashName(url);
String path = this.phyPath_ + "/" + hashName;
return path;
}
/**
* 检查url对应的物理文件是否存在
*
* @param url
* @return
*/
public boolean checkFileExists(String url) {
String p = this.getUrlPhyPath(url);
File f = new File(p);
if (f.exists() && f.length() > 0) {
return true;
} else {
return false;
}
}
/**
* 保存文件
*
* @param url
* @param content
*/
public boolean saveCache(String url, String content) {
String hashName = this.getHashName(url);
String path = this.phyPath_ + "/" + hashName;
try {
UFile.createNewTextFile(path, content);
return true;
} catch (IOException e) {
this.log(e);
return false;
}
}
/**
* 保存文件
*
* @param url
* @param content
*/
public boolean saveCache(String url, byte[] buf) {
String path = this.getUrlPhyPath(url);
try {
UFile.createBinaryFile(path, buf, true);
return true;
} catch (Exception e) {
this.log(e);
return false;
}
}
/**
* 读取已经存在的文本文件
*
* @param url
* @return
*/
public String readExists(String url) {
String path = this.getUrlPhyPath(url);
if (this.checkFileExists(url)) {
try {
return UFile.readFileText(path);
} catch (Exception e) {
this.log(e);
}
}
return null;
}
/**
* 去除url中的参数
*
* @param url
* @param removedParamNames
* @return
*/
public String removeUrlParameters(String url, String[] removedParamNames) {
if (url == null || url.isEmpty() || removedParamNames == null || removedParamNames.length == 0) {
return url;
}
int loc0 = url.indexOf("?");
if (loc0 < 0) {
return url;
}
String c = url.substring(0, loc0);
// 参数,+1表示不带?号
String q = url.substring(loc0 + 1);
String[] params = q.split("\\&");
HashMap<String, String> remvedParamsMap = new HashMap<String, String>();
for (int i = 0; i < removedParamNames.length; i++) {
String paramName = removedParamNames[i].trim();
remvedParamsMap.put(paramName.toUpperCase(), paramName);
}
StringBuilder sb = new StringBuilder(c);
int inc = 0;
for (int i = 0; i < params.length; i++) {
String param = params[i];
String[] paramExp = param.split("\\=");
if (remvedParamsMap.containsKey(paramExp[0].toUpperCase().trim())) {
continue;
}
sb.append(inc == 0 ? "?" : "&");
sb.append(param);
inc++;
}
return sb.toString();
}
public String urlEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
}
try {
return java.net.URLEncoder.encode(s, "utf-8");
} catch (UnsupportedEncodingException e) {
return s;
}
}
/**
* 处理url中特殊的字符
*
* @param source
* @return
*/
public String fixSpecialCodeFromHref(String source) {
String[] location = source.split("\\?");
// 处理url中的中文
String[] sources = (location[0] + "__GGGDXX__").split("\\/");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sources.length; i++) {
String s = sources[i];
if (i == sources.length - 1) {
s = s.replace("__GGGDXX__", "");
}
sb.append(i > 0 ? "/" : "");
if (s.indexOf(":") >= 0 || s.toLowerCase().equals("http:") || s.toLowerCase().equals("https:")) {
sb.append(s);
} else {
sb.append(urlEncode(s));
}
}
if (location.length > 1) {
try {
String[] params = location[1].split("\\&");
for (int i = 0; i < params.length; i++) {
String param = params[i];
String[] paramExp = param.split("\\=");
sb.append(i == 0 ? "?" : "&");
sb.append(urlEncode(paramExp[0]));
if (paramExp.length > 1) {
sb.append("=");
sb.append(urlEncode(paramExp[1]));
}
}
} catch (Exception err) {
System.out.println(err);
}
} else if (source.endsWith("?")) {
sb.append("?");
}
return sb.toString().replace("+", "%20");
}
/**
* 修正href网址
*
* @param source
* @return
*/
public String fixHref(String source) {
if (source == null || source.trim().length() == 0) {
return source;
}
if (source.indexOf("小二班") >= 0) {
System.out.println(source);
}
if (source.toLowerCase().indexOf("http://") == 0 || source.toLowerCase().indexOf("https://") == 0) {
return fixSpecialCodeFromHref(source);
}
if (source.startsWith("/")) {
return fixSpecialCodeFromHref(this.root_ + source);
} else if (source.startsWith("?")) {
return fixSpecialCodeFromHref(this.url_.split("\\?")[0] + source);
} else {
return fixSpecialCodeFromHref(this.context_ + source);
}
}
/**
* 创建hash文件名
*
* @param url
* @return
*/
public String getHashName(String url) {
if (this.hashNameMap_.containsKey(url)) {
return this.hashNameMap_.get(url);
}
String hash = "GdX" + (url.hashCode() + "").replace("-", "_");
String[] parts = url.split("\\.");
String ext = "";
if (parts.length > 1) {
ext = "." + parts[parts.length - 1];
if (ext.indexOf("/") >= 0) {
ext = "";
} else {
ext = ext.split("\\?")[0];
ext = ext.replace("&", "");
}
}
ext = ext.replace("/", "_").replace("\\", "_");
String p = hash + ext;
this.hashNameMap_.put(url, p);
return p;
}
/**
* 获取远程url对应的本地的url,用于图片src的替换等..
*
* @param url
* 远程url
* @return
*/
public String getHashUrl(String url) {
String hashname = this.getHashName(url);
return this.urlPath_ + hashname;
}
/**
* 删除对象的所有on事件
*
* @param ele
*/
public void removeEleEvts(Element ele) {
if (ele == null) {
return;
}
Iterator<Attribute> it = ele.attributes().iterator();
List<String> lst = new ArrayList<String>();
while (it.hasNext()) {
Attribute keyAttr = it.next();
if (keyAttr.getKey().toLowerCase().indexOf("on") == 0) {
lst.add(keyAttr.getKey());
}
}
for (int i = 0; i < lst.size(); i++) {
ele.attributes().remove(lst.get(i));
}
}
public void praseRootAndContext(Document doc) throws URISyntaxException {
String fack = "GGDDXX129sdjkfsdkfsdf912";
String title = doc.baseUri();
java.net.URI u = new java.net.URI(title);
this.root_ = u.getScheme() + "://" + u.getHost() + (u.getPort() > 0 ? ":" + u.getPort() : "");
this.context_ = this.root_;
// example /Category_19/Index.aspx
String[] contents = (u.getPath() + fack).split("\\/");
for (int i = 0; i < contents.length - 1; i++) {
String ctx = contents[i].replace(fack, "");
this.context_ += ctx + "/";
}
}
/**
* @return the root_
*/
public String getUrlRoot() {
return root_;
}
/**
* @param root_
* the root_ to set
*/
public void setUrlRoot(String root) {
this.root_ = root;
}
/**
* @return the context_
*/
public String getUrlContext() {
return context_;
}
/**
* @param context_
* the context_ to set
*/
public void setUrlContext(String context) {
this.context_ = context;
}
/**
* @return the doc_
*/
public Document getDoc() {
return doc_;
}
/**
* @param doc_
* the doc_ to set
*/
public void setDoc(Document doc) {
this.doc_ = doc;
}
/**
* 文档的网址
*
* @return the url_
*/
public String getUrl() {
return url_;
}
/**
* 文件保存的物理路径
*
* @return the phyPath_
*/
public String getPhyPath() {
return phyPath_;
}
/**
* 文件保存的物理路径
*
* @param phyPath_
* the phyPath_ to set
*/
public void setPhyPath(String phyPath) {
this.phyPath_ = phyPath;
}
/**
* @return the urlPath_
*/
public String getUrlPath() {
return urlPath_;
}
/**
* @param urlPath_
* the urlPath_ to set
*/
public void setUrlPath(String urlPath) {
this.urlPath_ = urlPath;
}
/**
* 是否忽略已经存在的下载,默认false,如果是true的话是重新下载
*
* @return the isSkipExists_
*/
public boolean isSkipExists() {
return isSkipExists_;
}
/**
* 是否忽略已经存在的下载,默认false,如果是true的话是重新下载
*
* @param isSkipExists_
* the isSkipExists_ to set
*/
public void setSkipExists(boolean isSkipExists) {
this.isSkipExists_ = isSkipExists;
}
}
| gdx1231/emp-script-web | src/main/java/com/gdxsoft/spider/SpiderBase.java | 3,979 | //" + u.getHost() + (u.getPort() > 0 ? ":" + u.getPort() : ""); | line_comment | nl | package com.gdxsoft.spider;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gdxsoft.easyweb.utils.UFile;
import com.gdxsoft.easyweb.utils.UNet;
public class SpiderBase {
private Document doc_;
private String root_;
private String context_;
private String url_;
private boolean isSkipExists_; // 是否忽略已经存在的,默认false
private String phyPath_; // 列表和文章及图片保存的物理路径
private String urlPath_;// 替换文章的图片地址的根url
private Map<String, String> hashNameMap_;
private static Logger LOOGER = LoggerFactory.getLogger(SpiderBase.class);
public SpiderBase(String url, String phyPath, String urlPath) {
this.url_ = url;
this.phyPath_ = phyPath;
this.urlPath_ = urlPath;
this.hashNameMap_ = new HashMap<String, String>();
}
public void log(Object msg) {
LOOGER.info(msg.toString());
}
/**
* 下载html document
*
* @param url
* 网址
* @return
* @throws IOException
* @throws URISyntaxException
*/
public Document downloadDoc() throws IOException, URISyntaxException {
String exists = this.isSkipExists_ ? null : this.readExists(this.url_);
Document doc;
if (exists != null) {
LOOGER.info("exists: " + this.url_);
doc = Jsoup.parse(exists);
doc.setBaseUri(url_);
doc.getElementsByTag("script").remove();
doc.getElementsByTag("style").remove();
} else {
LOOGER.info("GET: " + this.url_);
int timeout = 100 * 1000; // 100 s
doc = Jsoup.connect(this.url_).userAgent(UNet.AGENT).timeout(timeout).get();
this.saveCache(url_, doc.outerHtml());
}
this.praseRootAndContext(doc);
this.doc_ = doc;
return doc;
}
/**
* 下载图片
*
* @param sourceUrl
* @return
*/
public String downloadImg(String sourceUrl) {
String my_url = this.getHashUrl(sourceUrl);
if (!this.checkFileExists(sourceUrl)) {
// this.log("DL: " + sourceUrl);
UNet net = new UNet();
net.setIsShowLog(true);
try {
byte[] buf = net.downloadData(sourceUrl);
this.saveCache(sourceUrl, buf);
} catch (Exception err) {
LOOGER.error(err.getMessage());
}
} else {
// LOOGER.info("EXISTS: " + sourceUrl);
}
return my_url;
}
/**
* 根据url获取物理文件位置
*
* @param url
* @return
*/
public String getUrlPhyPath(String url) {
String hashName = this.getHashName(url);
String path = this.phyPath_ + "/" + hashName;
return path;
}
/**
* 检查url对应的物理文件是否存在
*
* @param url
* @return
*/
public boolean checkFileExists(String url) {
String p = this.getUrlPhyPath(url);
File f = new File(p);
if (f.exists() && f.length() > 0) {
return true;
} else {
return false;
}
}
/**
* 保存文件
*
* @param url
* @param content
*/
public boolean saveCache(String url, String content) {
String hashName = this.getHashName(url);
String path = this.phyPath_ + "/" + hashName;
try {
UFile.createNewTextFile(path, content);
return true;
} catch (IOException e) {
this.log(e);
return false;
}
}
/**
* 保存文件
*
* @param url
* @param content
*/
public boolean saveCache(String url, byte[] buf) {
String path = this.getUrlPhyPath(url);
try {
UFile.createBinaryFile(path, buf, true);
return true;
} catch (Exception e) {
this.log(e);
return false;
}
}
/**
* 读取已经存在的文本文件
*
* @param url
* @return
*/
public String readExists(String url) {
String path = this.getUrlPhyPath(url);
if (this.checkFileExists(url)) {
try {
return UFile.readFileText(path);
} catch (Exception e) {
this.log(e);
}
}
return null;
}
/**
* 去除url中的参数
*
* @param url
* @param removedParamNames
* @return
*/
public String removeUrlParameters(String url, String[] removedParamNames) {
if (url == null || url.isEmpty() || removedParamNames == null || removedParamNames.length == 0) {
return url;
}
int loc0 = url.indexOf("?");
if (loc0 < 0) {
return url;
}
String c = url.substring(0, loc0);
// 参数,+1表示不带?号
String q = url.substring(loc0 + 1);
String[] params = q.split("\\&");
HashMap<String, String> remvedParamsMap = new HashMap<String, String>();
for (int i = 0; i < removedParamNames.length; i++) {
String paramName = removedParamNames[i].trim();
remvedParamsMap.put(paramName.toUpperCase(), paramName);
}
StringBuilder sb = new StringBuilder(c);
int inc = 0;
for (int i = 0; i < params.length; i++) {
String param = params[i];
String[] paramExp = param.split("\\=");
if (remvedParamsMap.containsKey(paramExp[0].toUpperCase().trim())) {
continue;
}
sb.append(inc == 0 ? "?" : "&");
sb.append(param);
inc++;
}
return sb.toString();
}
public String urlEncode(String s) {
if (s == null || s.isEmpty()) {
return s;
}
try {
return java.net.URLEncoder.encode(s, "utf-8");
} catch (UnsupportedEncodingException e) {
return s;
}
}
/**
* 处理url中特殊的字符
*
* @param source
* @return
*/
public String fixSpecialCodeFromHref(String source) {
String[] location = source.split("\\?");
// 处理url中的中文
String[] sources = (location[0] + "__GGGDXX__").split("\\/");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sources.length; i++) {
String s = sources[i];
if (i == sources.length - 1) {
s = s.replace("__GGGDXX__", "");
}
sb.append(i > 0 ? "/" : "");
if (s.indexOf(":") >= 0 || s.toLowerCase().equals("http:") || s.toLowerCase().equals("https:")) {
sb.append(s);
} else {
sb.append(urlEncode(s));
}
}
if (location.length > 1) {
try {
String[] params = location[1].split("\\&");
for (int i = 0; i < params.length; i++) {
String param = params[i];
String[] paramExp = param.split("\\=");
sb.append(i == 0 ? "?" : "&");
sb.append(urlEncode(paramExp[0]));
if (paramExp.length > 1) {
sb.append("=");
sb.append(urlEncode(paramExp[1]));
}
}
} catch (Exception err) {
System.out.println(err);
}
} else if (source.endsWith("?")) {
sb.append("?");
}
return sb.toString().replace("+", "%20");
}
/**
* 修正href网址
*
* @param source
* @return
*/
public String fixHref(String source) {
if (source == null || source.trim().length() == 0) {
return source;
}
if (source.indexOf("小二班") >= 0) {
System.out.println(source);
}
if (source.toLowerCase().indexOf("http://") == 0 || source.toLowerCase().indexOf("https://") == 0) {
return fixSpecialCodeFromHref(source);
}
if (source.startsWith("/")) {
return fixSpecialCodeFromHref(this.root_ + source);
} else if (source.startsWith("?")) {
return fixSpecialCodeFromHref(this.url_.split("\\?")[0] + source);
} else {
return fixSpecialCodeFromHref(this.context_ + source);
}
}
/**
* 创建hash文件名
*
* @param url
* @return
*/
public String getHashName(String url) {
if (this.hashNameMap_.containsKey(url)) {
return this.hashNameMap_.get(url);
}
String hash = "GdX" + (url.hashCode() + "").replace("-", "_");
String[] parts = url.split("\\.");
String ext = "";
if (parts.length > 1) {
ext = "." + parts[parts.length - 1];
if (ext.indexOf("/") >= 0) {
ext = "";
} else {
ext = ext.split("\\?")[0];
ext = ext.replace("&", "");
}
}
ext = ext.replace("/", "_").replace("\\", "_");
String p = hash + ext;
this.hashNameMap_.put(url, p);
return p;
}
/**
* 获取远程url对应的本地的url,用于图片src的替换等..
*
* @param url
* 远程url
* @return
*/
public String getHashUrl(String url) {
String hashname = this.getHashName(url);
return this.urlPath_ + hashname;
}
/**
* 删除对象的所有on事件
*
* @param ele
*/
public void removeEleEvts(Element ele) {
if (ele == null) {
return;
}
Iterator<Attribute> it = ele.attributes().iterator();
List<String> lst = new ArrayList<String>();
while (it.hasNext()) {
Attribute keyAttr = it.next();
if (keyAttr.getKey().toLowerCase().indexOf("on") == 0) {
lst.add(keyAttr.getKey());
}
}
for (int i = 0; i < lst.size(); i++) {
ele.attributes().remove(lst.get(i));
}
}
public void praseRootAndContext(Document doc) throws URISyntaxException {
String fack = "GGDDXX129sdjkfsdkfsdf912";
String title = doc.baseUri();
java.net.URI u = new java.net.URI(title);
this.root_ = u.getScheme() + "://" +<SUF>
this.context_ = this.root_;
// example /Category_19/Index.aspx
String[] contents = (u.getPath() + fack).split("\\/");
for (int i = 0; i < contents.length - 1; i++) {
String ctx = contents[i].replace(fack, "");
this.context_ += ctx + "/";
}
}
/**
* @return the root_
*/
public String getUrlRoot() {
return root_;
}
/**
* @param root_
* the root_ to set
*/
public void setUrlRoot(String root) {
this.root_ = root;
}
/**
* @return the context_
*/
public String getUrlContext() {
return context_;
}
/**
* @param context_
* the context_ to set
*/
public void setUrlContext(String context) {
this.context_ = context;
}
/**
* @return the doc_
*/
public Document getDoc() {
return doc_;
}
/**
* @param doc_
* the doc_ to set
*/
public void setDoc(Document doc) {
this.doc_ = doc;
}
/**
* 文档的网址
*
* @return the url_
*/
public String getUrl() {
return url_;
}
/**
* 文件保存的物理路径
*
* @return the phyPath_
*/
public String getPhyPath() {
return phyPath_;
}
/**
* 文件保存的物理路径
*
* @param phyPath_
* the phyPath_ to set
*/
public void setPhyPath(String phyPath) {
this.phyPath_ = phyPath;
}
/**
* @return the urlPath_
*/
public String getUrlPath() {
return urlPath_;
}
/**
* @param urlPath_
* the urlPath_ to set
*/
public void setUrlPath(String urlPath) {
this.urlPath_ = urlPath;
}
/**
* 是否忽略已经存在的下载,默认false,如果是true的话是重新下载
*
* @return the isSkipExists_
*/
public boolean isSkipExists() {
return isSkipExists_;
}
/**
* 是否忽略已经存在的下载,默认false,如果是true的话是重新下载
*
* @param isSkipExists_
* the isSkipExists_ to set
*/
public void setSkipExists(boolean isSkipExists) {
this.isSkipExists_ = isSkipExists;
}
}
| False |
796 | 127151_14 | // Copyright (c) 2014 by B.W. van Schooten, info@borisvanschooten.nl
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event: 2
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| JakeCoxon/glesjs | src/net/tmtg/glesjs/MainActivity.java | 2,284 | // move event: 2 | line_comment | nl | // Copyright (c) 2014 by B.W. van Schooten, info@borisvanschooten.nl
package net.tmtg.glesjs;
import android.os.Bundle;
import android.app.Activity;
import android.app.Application;
import android.hardware.*;
import android.view.*;
import android.graphics.*;
import android.graphics.drawable.Drawable;
import android.content.Intent;
import android.net.Uri;
import android.content.Context;
import android.opengl.*;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.util.Log;
public class MainActivity extends Activity {
static boolean surface_already_created=false;
MyGLSurfaceView mView=null;
MyRenderer mRen=null;
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
GlesJSUtils.init(this);
mView = new MyGLSurfaceView(getApplication());
// Try to hang on to GL context
mView.setPreserveEGLContextOnPause(true);
setContentView(mView);
}
@Override protected void onPause() {
super.onPause();
//mView.setVisibility(View.GONE);
mView.onPause();
GlesJSUtils.pauseAudio();
}
@Override protected void onResume() {
super.onResume();
mView.onResume();
GlesJSUtils.resumeAudio();
}
/*@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus && mView.getVisibility() == View.GONE) {
mView.setVisibility(View.VISIBLE);
}
}*/
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
return GameController.onKeyDown(keyCode,event);
}
@Override public boolean onKeyUp(int keyCode, KeyEvent event) {
return GameController.onKeyUp(keyCode,event);
}
@Override public boolean onGenericMotionEvent(MotionEvent event) {
return GameController.onGenericMotionEvent(event);
}
class MyGLSurfaceView extends GLSurfaceView {
public MyGLSurfaceView(Context context){
super(context);
setEGLContextClientVersion(2);
// Set the Renderer for drawing on the GLSurfaceView
mRen = new MyRenderer();
setRenderer(mRen);
}
@Override
public boolean onTouchEvent(MotionEvent me) {
// queue event, and handle it from the renderer thread later
// to avoid concurrency handling
if (mRen!=null) mRen.queueTouchEvent(me);
return true;
}
}
class MyRenderer implements GLSurfaceView.Renderer {
static final int MAXQUEUELEN = 6;
Object queuelock = new Object();
MotionEvent [] motionqueue = new MotionEvent [MAXQUEUELEN];
int motionqueue_len = 0;
public void queueTouchEvent(MotionEvent ev) {
synchronized (queuelock) {
if (motionqueue_len >= MAXQUEUELEN) return;
motionqueue[motionqueue_len++] = MotionEvent.obtain(ev);
}
}
static final int MAXTOUCHES=8;
int [] touchids = new int[MAXTOUCHES];
double [] touchx = new double[MAXTOUCHES];
double [] touchy = new double[MAXTOUCHES];
int touchlen = 0;
public void handleTouchEvent(MotionEvent me) {
// XXX We should mask out the pointer id info in some of the
// action codes. Since 2.2, we should use getActionMasked for
// this.
// use MotionEventCompat to do this?
int action = me.getActionMasked();
int ptridx = me.getActionIndex();
// Default coord is the current coordinates of an arbitrary active
// pointer.
double x = me.getX(ptridx);
double y = me.getY(ptridx);
// on a multitouch, touches after the first touch are also
// considered mouse-down flanks.
boolean press = action == MotionEvent.ACTION_DOWN
|| action == MotionEvent.ACTION_POINTER_DOWN;
// boolean down = press || action == MotionEvent.ACTION_MOVE;
// Alcatel pop:
// down event: 0
// move event:<SUF>
// up event: 9.
// ACTION_UP=1, ACTION_POINTER_UP=6
//boolean release = (action & ( MotionEvent.ACTION_UP)) != 0;
// Normal:
boolean release = action == MotionEvent.ACTION_UP
|| action == MotionEvent.ACTION_POINTER_UP;
int ptrid=0;
try {
ptrid = me.getPointerId(ptridx);
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
return;
}
// pass multitouch coordinates before touch event
int pointerCount = me.getPointerCount();
// signal start multitouch info
GlesJSLib.onMultitouchCoordinates(-1,0,0);
for (int p = 0; p < pointerCount; p++) {
try {
int pid = me.getPointerId(p);
GlesJSLib.onMultitouchCoordinates(pid,me.getX(p),me.getY(p));
} catch (IllegalArgumentException e) {
// getPointerId sometimes throws pointer index out of range
// -> ignore
System.err.println("Failed getting pointer. Ignoring.");
e.printStackTrace();
}
}
// signal end coordinate info, start button info
//GlesJSLib.onMultitouchCoordinates(-2,0,0);
// single touch / press-release info
// !press && !release means move
GlesJSLib.onTouchEvent(ptrid,x,y,press,release);
// signal end touch info
GlesJSLib.onMultitouchCoordinates(-3,0,0);
}
public void onDrawFrame(GL10 gl) {
GameController.startOfFrame();
// handle events in the render thread
synchronized (queuelock) {
for (int i=0; i<motionqueue_len; i++) {
if (motionqueue[i]!=null) {
handleTouchEvent(motionqueue[i]);
motionqueue[i].recycle();
motionqueue[i] = null;
}
}
motionqueue_len = 0;
}
for (int i=0; i<GameController.NR_PLAYERS; i++) {
GameController con = GameController.getControllerByPlayer(i);
if (con.isConnected()) {
//System.out.println("##################active@@@@@"+i);
boolean [] buttons = con.getButtons();
float [] axes = con.getAxes();
GlesJSLib.onControllerEvent(i,true,buttons,axes);
} else {
GlesJSLib.onControllerEvent(i,false,null,null);
}
/* FOR TESTING:
} else if (i==0) {
boolean [] buttons = new boolean[]
{true,false,true,false,true,false,true};
float [] axes = new float[]
{9,8,7,6,5};
GlesJSLib.onControllerEvent(i,true,buttons,axes);
}
*/
}
GlesJSLib.onDrawFrame();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GameController.init(MainActivity.this);
GlesJSLib.onSurfaceChanged(width, height);
surface_already_created=true;
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
if (surface_already_created) {
// gl context was lost -> we can't handle that yet
// -> commit suicide
// TODO generate contextlost event in JS
System.err.println("GL context lost. Cannot restore. Exiting.");
System.exit(0);
}
// Do nothing.
}
}
}
| False |