file_id
stringlengths 5
10
| content
stringlengths 110
36.3k
| 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
36.3k
|
---|---|---|---|---|---|---|---|---|
163219_0 | package fact.it.preferenceservice;
import fact.it.preferenceservice.dto.PreferenceRequest;
import fact.it.preferenceservice.dto.PreferenceResponse;
import fact.it.preferenceservice.model.Preference;
import fact.it.preferenceservice.repository.PreferenceRepository;
import fact.it.preferenceservice.service.PreferenceService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
@ExtendWith(MockitoExtension.class)
public class PreferenceServiceUnitTests {
@InjectMocks
private PreferenceService preferenceService;
@Mock
private PreferenceRepository preferenceRepository;
@Test
public void testCreatePreference(){
//ARRANGE
String name = "name";
String user = "user";
PreferenceRequest preferenceRequest = new PreferenceRequest(name, user);
//ACT
Preference preference = preferenceService.createPreference(preferenceRequest);
//ASSERT
assertEquals(name, preference.getName());
assertEquals(user, preference.getUserId());
assertNotNull(preference.getCode());
}
@Test
public void testGetPreferencesByUserId(){
//ARRANGE
String user = "user";
Preference preference1 = new Preference("id1", "code1", "name1", user);
Preference preference2 = new Preference("id2", "code2","name2", user);
List<Preference> preferences = Arrays.asList(preference1, preference2);
when(preferenceRepository.findByUserId(user)).thenReturn(preferences);
//ACT
List<PreferenceResponse> response = preferenceService.getPreferencesByUserId(user);
//ASSERT
assertEquals(2, response.size());
assertEquals(preference1.getCode(), response.get(0).getCode());
assertEquals(preference1.getName(), response.get(0).getName());
assertEquals(preference2.getCode(), response.get(1).getCode());
assertEquals(preference2.getName(), response.get(1).getName());
//Alle userId's moeten gelijk zijn, omdat assertEquals geen 4 strings kan argumenten kan aannemen assert ik 2 keer, als beide asserts positief zijn doorlopen, dat betekent dat alle userId's hetzelfde zijn
assertEquals(preference1.getUserId(), response.get(0).getUserId(),response.get(1).getUserId());
assertEquals(preference2.getUserId(), response.get(1).getUserId());
}
@Test
public void testUpdatePreference(){
//ARRANGE
String code = "code";
String name = "name";
String user = "user";
PreferenceRequest preferenceRequest = new PreferenceRequest(name, user);
Preference preference = new Preference("id", code,name, user);
when(preferenceRepository.findByCode(code)).thenReturn(preference);
//ACT
PreferenceResponse response = preferenceService.updatePreference(preferenceRequest, code);
//ASSERT
assertEquals(response.getCode(),code);
assertEquals(response.getName(),name);
assertEquals(response.getUserId(), user);
}
}
| rafengelen/playlist_generator | preference-service/src/test/java/fact/it/preferenceservice/PreferenceServiceUnitTests.java | 947 | //Alle userId's moeten gelijk zijn, omdat assertEquals geen 4 strings kan argumenten kan aannemen assert ik 2 keer, als beide asserts positief zijn doorlopen, dat betekent dat alle userId's hetzelfde zijn | line_comment | nl | package fact.it.preferenceservice;
import fact.it.preferenceservice.dto.PreferenceRequest;
import fact.it.preferenceservice.dto.PreferenceResponse;
import fact.it.preferenceservice.model.Preference;
import fact.it.preferenceservice.repository.PreferenceRepository;
import fact.it.preferenceservice.service.PreferenceService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.List;
@ExtendWith(MockitoExtension.class)
public class PreferenceServiceUnitTests {
@InjectMocks
private PreferenceService preferenceService;
@Mock
private PreferenceRepository preferenceRepository;
@Test
public void testCreatePreference(){
//ARRANGE
String name = "name";
String user = "user";
PreferenceRequest preferenceRequest = new PreferenceRequest(name, user);
//ACT
Preference preference = preferenceService.createPreference(preferenceRequest);
//ASSERT
assertEquals(name, preference.getName());
assertEquals(user, preference.getUserId());
assertNotNull(preference.getCode());
}
@Test
public void testGetPreferencesByUserId(){
//ARRANGE
String user = "user";
Preference preference1 = new Preference("id1", "code1", "name1", user);
Preference preference2 = new Preference("id2", "code2","name2", user);
List<Preference> preferences = Arrays.asList(preference1, preference2);
when(preferenceRepository.findByUserId(user)).thenReturn(preferences);
//ACT
List<PreferenceResponse> response = preferenceService.getPreferencesByUserId(user);
//ASSERT
assertEquals(2, response.size());
assertEquals(preference1.getCode(), response.get(0).getCode());
assertEquals(preference1.getName(), response.get(0).getName());
assertEquals(preference2.getCode(), response.get(1).getCode());
assertEquals(preference2.getName(), response.get(1).getName());
//Alle userId's<SUF>
assertEquals(preference1.getUserId(), response.get(0).getUserId(),response.get(1).getUserId());
assertEquals(preference2.getUserId(), response.get(1).getUserId());
}
@Test
public void testUpdatePreference(){
//ARRANGE
String code = "code";
String name = "name";
String user = "user";
PreferenceRequest preferenceRequest = new PreferenceRequest(name, user);
Preference preference = new Preference("id", code,name, user);
when(preferenceRepository.findByCode(code)).thenReturn(preference);
//ACT
PreferenceResponse response = preferenceService.updatePreference(preferenceRequest, code);
//ASSERT
assertEquals(response.getCode(),code);
assertEquals(response.getName(),name);
assertEquals(response.getUserId(), user);
}
}
|
139614_16 | /*
* Copyright (C) 2018 Raffaele Conforti (www.raffaeleconforti.com)
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.raffaeleconforti.ilpminer;
import net.sf.javailp.*;
import org.deckfour.xes.classification.XEventClass;
import org.processmining.framework.plugin.PluginContext;
import org.processmining.framework.util.Pair;
import org.processmining.plugins.ilpminer.ILPMinerSettings;
import org.processmining.plugins.ilpminer.ILPMinerSolution;
import org.processmining.plugins.ilpminer.ILPModelSettings;
import org.processmining.plugins.ilpminer.templates.PetriNetILPModelSettings;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Raffaele Conforti ([email protected]) on 21/10/2016.
*/
public class PetriNetILPModel extends ILPModelJavaILP {
protected static PetriNetILPModelSettings strategySettings;
public int trans = 0, lang = 0;
public int[][] a = {}, aPrime = {};
public ArrayList<Integer> cd = null;
protected ArrayList<XEventClass> initialPlaces, notInitialPlaces;
protected boolean initialPlace;
public PetriNetILPModel(Class<?>[] extensions, Map<ILPMinerSettings.SolverSetting, Object> solverSettings, ILPModelSettings settings) {
super(extensions, solverSettings, settings);
strategySettings = (PetriNetILPModelSettings) settings;
}
public Problem getModel() {
Problem p = new Problem();
addObjective(p);
addConstraints(p);
addExtensionConstraints(p);
addVariables(p);
return p;
}
public void makeData() {
// store the log information provided in the parameters for future
// access
Object[] values = m.values().toArray();
trans = values.length;
lang = l.last();
a = l.getTransitionCountMatrix();
aPrime = l.getTransitionCountMatrix(1);
// find all transitions that are not in the second part of a causal
// dependency
// start with everything and remove those that are in the second part of
// a causal dependency
initialPlaces = new ArrayList<XEventClass>(r.getEventClasses().getClasses());
notInitialPlaces = new ArrayList<XEventClass>();
for (Map.Entry<Pair<XEventClass, XEventClass>, Double> entry : r.getCausalDependencies().entrySet()) {
if (entry.getValue() > 0) {
int size = initialPlaces.size();
initialPlaces.remove(entry.getKey().getSecond());
if (initialPlaces.size() != size) {
notInitialPlaces.add(entry.getKey().getSecond());
}
}
}
}
protected void processModel(PluginContext context, SolverFactory factory) {
if (strategySettings.separateInitialPlaces()) {
initialPlace = true;
processInitialPlaces(context);
}
initialPlace = false;
switch (strategySettings.getSearchType()) {
case BASIC :
processBasic(context);
break;
case PER_TRANSITION :
processTransitions(context, true);
processTransitions(context, false);
break;
case PRE_PER_TRANSITION :
processTransitions(context, true);
break;
case POST_PER_TRANSITION :
processTransitions(context, false);
break;
default :// PER_CD
processCausalDependencies(context);
break;
}
}
protected void processInitialPlaces(PluginContext context) {
for (XEventClass c : initialPlaces) {
if (context.getProgress().isCancelled()) {
return;
}
cd = new ArrayList<Integer>();
cd.add(m.get(c));
cd.add(-1);
addSolution(solve(context));
}
}
protected void processBasic(PluginContext context) {
boolean isOK = true;
while (isOK && !context.getProgress().isCancelled()) {
Result res = solve(context);
addSolution(res);
isOK = res != null;
isOK = isOK && (solutions.size() < Math.pow(r.getEventClasses().size(), 2));
}
}
protected void processTransitions(PluginContext context, boolean beforeTrans) {
ArrayList<XEventClass> places = new ArrayList<XEventClass>(r.getEventClasses().getClasses());
if (strategySettings.separateInitialPlaces() && beforeTrans) {
places = notInitialPlaces;
}
int i = 1;
context.getProgress().setIndeterminate(false);
context.getProgress().setMaximum(places.size());
for (XEventClass clazz : places) {
if (context.getProgress().isCancelled()) {
return;
}
context.getProgress().setValue(i);
i++;
cd = new ArrayList<Integer>();
cd.add(m.get(clazz));
// abuse cd to indicate wether we search
// in front of (0) or after (1) a transition
cd.add(beforeTrans ? 0 : 1);
addSolution(solve(context));
}
context.getProgress().setIndeterminate(true);
}
protected void processCausalDependencies(PluginContext context) {
int i = 1;
context.getProgress().setIndeterminate(false);
context.getProgress().setMaximum(r.getCausalDependencies().size());
for (Map.Entry<Pair<XEventClass, XEventClass>, Double> entry : r.getCausalDependencies().entrySet()) {
if (context.getProgress().isCancelled()) {
return;
}
if (entry.getValue() > 0) {
context.getProgress().setValue(i);
i++;
cd = new ArrayList<Integer>();
cd.add(m.get(entry.getKey().getFirst()));
cd.add(m.get(entry.getKey().getSecond()));
addSolution(solve(context));
}
}
context.getProgress().setIndeterminate(true);
}
/**
* defines the variable types and bounds in the problem
*
* @param p
* - problem
*/
protected void addVariables(Problem p) {
for (int t = 0; t < trans; t++) {
p.setVarType("x" + t, VarType.INT);
p.setVarLowerBound("x" + t, 0);
p.setVarUpperBound("x" + t, 1);
p.setVarType("y" + t, VarType.INT);
p.setVarLowerBound("y" + t, 0);
p.setVarUpperBound("y" + t, 1);
}
p.setVarType("c", VarType.INT);
p.setVarLowerBound("c", 0);
p.setVarUpperBound("c", 1);
}
/**
* adds an objective to the problem
*
* @param p
* - problem
*/
protected void addObjective(Problem p) {
// "c + sum(w in Lang) ( c + ( sum(t in trans) A[w][t] ) * (x[t] - y[t]) );";
Linear l = new Linear();
l.add(1 + lang, "c");
for (int t = 0; t < trans; t++) {
int sum = 0;
for (int w = 0; w < lang; w++) {
sum += a[w][t];
}
l.add(sum, "x" + t);
l.add(-sum, "y" + t);
}
p.setObjective(l, OptType.MIN);
}
/**
* adds the constraints to the problem
*
* @param p
* - problem
*/
protected void addConstraints(Problem p) {
// forall(w in Lang) ctMinimalRegion: c + ( sum(t in Trans) APrime[w][t]
// * x[t] ) - ( sum(t in Trans) A[w][t] * y[t] ) >= 0;
for (int w = 0; w < lang; w++) {
Linear l = new Linear();
l.add(1, "c");
for (int t = 0; t < trans; t++) {
if (aPrime[w][t] > 0) {
l.add(aPrime[w][t], "x" + t);
}
if (a[w][t] > 0) {
l.add(-a[w][t], "y" + t);
}
}
p.add(l, Operator.GE, 0);
}
addPlaceConstraints(p);
}
protected void addPlaceConstraints(Problem p) {
if (initialPlace) {
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
// ctToken: c == 1;
Linear l = new Linear();
l.add(1, "c");
p.add(l, Operator.EQ, 1);
// ctInitialPlace: sum(t in Trans) x[t] == 0;" + "y[CD.To] == 1;
l = new Linear();
for (int t = 0; t < trans; t++) {
l.add(1, "x" + t);
}
p.add(l, Operator.EQ, 0);
l = new Linear();
l.add(1, "y" + cd.get(0).toString());
p.add(l, Operator.EQ, 1);
} else {
if (strategySettings.separateInitialPlaces()) {
// ctNoToken: c == 0;
Linear l = new Linear();
l.add(1, "c");
p.add(l, Operator.EQ, 0);
}
switch (strategySettings.getSearchType()) {
case BASIC :
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
Linear l = new Linear();
for (int t = 0; t < trans; t++) {
l.add(1, "x" + t);
l.add(1, "y" + t);
}
p.add(l, Operator.GE, 1);
// ctNotOldSolution: forall(s in Solutions) 2 * c * s.C + sum(t
// in Trans) (2 * x[t] * s.X[t] + 2 * y[t] * s.Y[t]) < c + s.c +
// sum(t in Trans) (x[t] + s.X[t] + y[t] + s.Y[t]);
for (ILPMinerSolution s : solutions) {
int sumS = 0;
l = new Linear();
l.add(2 * s.getTokens() - 1, "c");
sumS += s.getTokens();
for (int t = 0; t < trans; t++) {
l.add(2 * s.getInputSet()[t] - 1, "x" + t);
sumS += s.getInputSet()[t];
l.add(2 * s.getOutputSet()[t] - 1, "y" + t);
sumS += s.getOutputSet()[t];
}
p.add(l, Operator.LE, sumS - 1);
}
break;
case PER_TRANSITION :
case PRE_PER_TRANSITION :
case POST_PER_TRANSITION :
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
l = new Linear();
if (cd.get(1) == 0) { // search the place in front of the
// transition
l.add(1, "y" + cd.get(0).toString());
} else { // cd.get(1) == 1; search the place after the
// transition
l.add(1, "x" + cd.get(0).toString());
}
p.add(l, Operator.EQ, 1);
break;
default : // PER_CD
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
// ctCausalDependency: x[CD.From] == 1 && y[CD.To] == 1;
l = new Linear();
l.add(1, "x" + cd.get(0).toString());
p.add(l, Operator.EQ, 1);
l = new Linear();
l.add(1, "y" + cd.get(1).toString());
p.add(l, Operator.EQ, 1);
break;
}
}
}
/**
* converts the Java-ILP result in a solution (place representation) and
* adds it to the set of found solutions
*
* @param result
*/
protected void addSolution(Result result) {
if (result != null) {
solutions.add(makeSolution(result));
}
}
/**
* converts the Java-ILP result in a solution (place representation)
*
* @param result
* @return the converted solution
*/
protected ILPMinerSolution makeSolution(Result result) {
double[] x = new double[trans];
double[] y = new double[trans];
for (int t = 0; t < trans; t++) {
x[t] = result.get("x" + t).doubleValue();
y[t] = result.get("y" + t).doubleValue();
}
double c = result.get("c").doubleValue();
return new ILPMinerSolution(x, y, c);
}
}
| raffaeleconforti/ResearchCode | modified-miners/src/main/java/com/raffaeleconforti/ilpminer/PetriNetILPModel.java | 4,004 | // ctToken: c == 1; | line_comment | nl | /*
* Copyright (C) 2018 Raffaele Conforti (www.raffaeleconforti.com)
*
* This program 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 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.raffaeleconforti.ilpminer;
import net.sf.javailp.*;
import org.deckfour.xes.classification.XEventClass;
import org.processmining.framework.plugin.PluginContext;
import org.processmining.framework.util.Pair;
import org.processmining.plugins.ilpminer.ILPMinerSettings;
import org.processmining.plugins.ilpminer.ILPMinerSolution;
import org.processmining.plugins.ilpminer.ILPModelSettings;
import org.processmining.plugins.ilpminer.templates.PetriNetILPModelSettings;
import java.util.ArrayList;
import java.util.Map;
/**
* Created by Raffaele Conforti ([email protected]) on 21/10/2016.
*/
public class PetriNetILPModel extends ILPModelJavaILP {
protected static PetriNetILPModelSettings strategySettings;
public int trans = 0, lang = 0;
public int[][] a = {}, aPrime = {};
public ArrayList<Integer> cd = null;
protected ArrayList<XEventClass> initialPlaces, notInitialPlaces;
protected boolean initialPlace;
public PetriNetILPModel(Class<?>[] extensions, Map<ILPMinerSettings.SolverSetting, Object> solverSettings, ILPModelSettings settings) {
super(extensions, solverSettings, settings);
strategySettings = (PetriNetILPModelSettings) settings;
}
public Problem getModel() {
Problem p = new Problem();
addObjective(p);
addConstraints(p);
addExtensionConstraints(p);
addVariables(p);
return p;
}
public void makeData() {
// store the log information provided in the parameters for future
// access
Object[] values = m.values().toArray();
trans = values.length;
lang = l.last();
a = l.getTransitionCountMatrix();
aPrime = l.getTransitionCountMatrix(1);
// find all transitions that are not in the second part of a causal
// dependency
// start with everything and remove those that are in the second part of
// a causal dependency
initialPlaces = new ArrayList<XEventClass>(r.getEventClasses().getClasses());
notInitialPlaces = new ArrayList<XEventClass>();
for (Map.Entry<Pair<XEventClass, XEventClass>, Double> entry : r.getCausalDependencies().entrySet()) {
if (entry.getValue() > 0) {
int size = initialPlaces.size();
initialPlaces.remove(entry.getKey().getSecond());
if (initialPlaces.size() != size) {
notInitialPlaces.add(entry.getKey().getSecond());
}
}
}
}
protected void processModel(PluginContext context, SolverFactory factory) {
if (strategySettings.separateInitialPlaces()) {
initialPlace = true;
processInitialPlaces(context);
}
initialPlace = false;
switch (strategySettings.getSearchType()) {
case BASIC :
processBasic(context);
break;
case PER_TRANSITION :
processTransitions(context, true);
processTransitions(context, false);
break;
case PRE_PER_TRANSITION :
processTransitions(context, true);
break;
case POST_PER_TRANSITION :
processTransitions(context, false);
break;
default :// PER_CD
processCausalDependencies(context);
break;
}
}
protected void processInitialPlaces(PluginContext context) {
for (XEventClass c : initialPlaces) {
if (context.getProgress().isCancelled()) {
return;
}
cd = new ArrayList<Integer>();
cd.add(m.get(c));
cd.add(-1);
addSolution(solve(context));
}
}
protected void processBasic(PluginContext context) {
boolean isOK = true;
while (isOK && !context.getProgress().isCancelled()) {
Result res = solve(context);
addSolution(res);
isOK = res != null;
isOK = isOK && (solutions.size() < Math.pow(r.getEventClasses().size(), 2));
}
}
protected void processTransitions(PluginContext context, boolean beforeTrans) {
ArrayList<XEventClass> places = new ArrayList<XEventClass>(r.getEventClasses().getClasses());
if (strategySettings.separateInitialPlaces() && beforeTrans) {
places = notInitialPlaces;
}
int i = 1;
context.getProgress().setIndeterminate(false);
context.getProgress().setMaximum(places.size());
for (XEventClass clazz : places) {
if (context.getProgress().isCancelled()) {
return;
}
context.getProgress().setValue(i);
i++;
cd = new ArrayList<Integer>();
cd.add(m.get(clazz));
// abuse cd to indicate wether we search
// in front of (0) or after (1) a transition
cd.add(beforeTrans ? 0 : 1);
addSolution(solve(context));
}
context.getProgress().setIndeterminate(true);
}
protected void processCausalDependencies(PluginContext context) {
int i = 1;
context.getProgress().setIndeterminate(false);
context.getProgress().setMaximum(r.getCausalDependencies().size());
for (Map.Entry<Pair<XEventClass, XEventClass>, Double> entry : r.getCausalDependencies().entrySet()) {
if (context.getProgress().isCancelled()) {
return;
}
if (entry.getValue() > 0) {
context.getProgress().setValue(i);
i++;
cd = new ArrayList<Integer>();
cd.add(m.get(entry.getKey().getFirst()));
cd.add(m.get(entry.getKey().getSecond()));
addSolution(solve(context));
}
}
context.getProgress().setIndeterminate(true);
}
/**
* defines the variable types and bounds in the problem
*
* @param p
* - problem
*/
protected void addVariables(Problem p) {
for (int t = 0; t < trans; t++) {
p.setVarType("x" + t, VarType.INT);
p.setVarLowerBound("x" + t, 0);
p.setVarUpperBound("x" + t, 1);
p.setVarType("y" + t, VarType.INT);
p.setVarLowerBound("y" + t, 0);
p.setVarUpperBound("y" + t, 1);
}
p.setVarType("c", VarType.INT);
p.setVarLowerBound("c", 0);
p.setVarUpperBound("c", 1);
}
/**
* adds an objective to the problem
*
* @param p
* - problem
*/
protected void addObjective(Problem p) {
// "c + sum(w in Lang) ( c + ( sum(t in trans) A[w][t] ) * (x[t] - y[t]) );";
Linear l = new Linear();
l.add(1 + lang, "c");
for (int t = 0; t < trans; t++) {
int sum = 0;
for (int w = 0; w < lang; w++) {
sum += a[w][t];
}
l.add(sum, "x" + t);
l.add(-sum, "y" + t);
}
p.setObjective(l, OptType.MIN);
}
/**
* adds the constraints to the problem
*
* @param p
* - problem
*/
protected void addConstraints(Problem p) {
// forall(w in Lang) ctMinimalRegion: c + ( sum(t in Trans) APrime[w][t]
// * x[t] ) - ( sum(t in Trans) A[w][t] * y[t] ) >= 0;
for (int w = 0; w < lang; w++) {
Linear l = new Linear();
l.add(1, "c");
for (int t = 0; t < trans; t++) {
if (aPrime[w][t] > 0) {
l.add(aPrime[w][t], "x" + t);
}
if (a[w][t] > 0) {
l.add(-a[w][t], "y" + t);
}
}
p.add(l, Operator.GE, 0);
}
addPlaceConstraints(p);
}
protected void addPlaceConstraints(Problem p) {
if (initialPlace) {
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
// ctToken: c<SUF>
Linear l = new Linear();
l.add(1, "c");
p.add(l, Operator.EQ, 1);
// ctInitialPlace: sum(t in Trans) x[t] == 0;" + "y[CD.To] == 1;
l = new Linear();
for (int t = 0; t < trans; t++) {
l.add(1, "x" + t);
}
p.add(l, Operator.EQ, 0);
l = new Linear();
l.add(1, "y" + cd.get(0).toString());
p.add(l, Operator.EQ, 1);
} else {
if (strategySettings.separateInitialPlaces()) {
// ctNoToken: c == 0;
Linear l = new Linear();
l.add(1, "c");
p.add(l, Operator.EQ, 0);
}
switch (strategySettings.getSearchType()) {
case BASIC :
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
Linear l = new Linear();
for (int t = 0; t < trans; t++) {
l.add(1, "x" + t);
l.add(1, "y" + t);
}
p.add(l, Operator.GE, 1);
// ctNotOldSolution: forall(s in Solutions) 2 * c * s.C + sum(t
// in Trans) (2 * x[t] * s.X[t] + 2 * y[t] * s.Y[t]) < c + s.c +
// sum(t in Trans) (x[t] + s.X[t] + y[t] + s.Y[t]);
for (ILPMinerSolution s : solutions) {
int sumS = 0;
l = new Linear();
l.add(2 * s.getTokens() - 1, "c");
sumS += s.getTokens();
for (int t = 0; t < trans; t++) {
l.add(2 * s.getInputSet()[t] - 1, "x" + t);
sumS += s.getInputSet()[t];
l.add(2 * s.getOutputSet()[t] - 1, "y" + t);
sumS += s.getOutputSet()[t];
}
p.add(l, Operator.LE, sumS - 1);
}
break;
case PER_TRANSITION :
case PRE_PER_TRANSITION :
case POST_PER_TRANSITION :
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
l = new Linear();
if (cd.get(1) == 0) { // search the place in front of the
// transition
l.add(1, "y" + cd.get(0).toString());
} else { // cd.get(1) == 1; search the place after the
// transition
l.add(1, "x" + cd.get(0).toString());
}
p.add(l, Operator.EQ, 1);
break;
default : // PER_CD
// ctAtLeastOneArc: sum(t in Trans) (x[t] + y[t]) >= 1;
// => volgt uit volgende constraint(s)
// ctCausalDependency: x[CD.From] == 1 && y[CD.To] == 1;
l = new Linear();
l.add(1, "x" + cd.get(0).toString());
p.add(l, Operator.EQ, 1);
l = new Linear();
l.add(1, "y" + cd.get(1).toString());
p.add(l, Operator.EQ, 1);
break;
}
}
}
/**
* converts the Java-ILP result in a solution (place representation) and
* adds it to the set of found solutions
*
* @param result
*/
protected void addSolution(Result result) {
if (result != null) {
solutions.add(makeSolution(result));
}
}
/**
* converts the Java-ILP result in a solution (place representation)
*
* @param result
* @return the converted solution
*/
protected ILPMinerSolution makeSolution(Result result) {
double[] x = new double[trans];
double[] y = new double[trans];
for (int t = 0; t < trans; t++) {
x[t] = result.get("x" + t).doubleValue();
y[t] = result.get("y" + t).doubleValue();
}
double c = result.get("c").doubleValue();
return new ILPMinerSolution(x, y, c);
}
}
|
155206_5 | package mJAM;
/**
* Defines names and sizes of mJAM instructions and primitives
* @author prins
* @version COMP 520 V2.3
*/
public final class Machine {
/**
* mJAM instructions
*/
public enum Op {
LOAD,
LOADA,
LOADI,
LOADL,
STORE,
STOREI,
CALL, // direct call of instance method
CALLI, // indirect call of instance method
CALLD, // dynamic call of instance method
RETURN,
PUSH,
POP,
JUMP,
JUMPI,
JUMPIF,
HALT;
}
public static Op [] intToOp = Op.values();
/**
* mJAM registers
*/
public enum Reg {
ZR, // zero, not used
CB, // code base
CT, // code top
CP, // code pointer
PB, // primitives base
PT, // primitives top
SB, // execution stack base
ST, // execution stack top
LB, // locals base (frame pointer)
HB, // heap base
HT, // heap top
OB; // object base (instance pointer)
}
public static Reg [] intToReg = Reg.values();
/**
* mJAM primitives
*/
public enum Prim {
id,
not,
and,
or,
succ,
pred,
neg,
add,
sub,
mult,
div,
mod,
lt,
le,
ge,
gt,
eq,
ne,
eol,
eof,
get,
put,
geteol,
puteol,
getint,
putint,
putintnl,
alloc,
dispose,
newobj,
newarr,
arraylen,
arrayref,
arrayupd,
fieldref,
fieldupd;
}
public static Prim [] intToPrim = Prim.values();
// range for int constants
public final static long
minintRep = -2147483648,
maxintRep = 2147483647;
// CODE STORE REGISTERS
public final static int CB = 0; // start of code space
public final static int PB = 1024; // size of code space reserved for instructions
public final static int PT = PB + Prim.values().length; // code space reserved for primitives
// CODE STORE
public static Instruction[] code = new Instruction[PB];
public static int CT = CB;
public static void initCodeGen() {
CT = CB;
}
/**
* Places an instruction, with the given fields, into the next position in the code store
* @param op - operation
* @param n - length
* @param r - register
* @param d - displacement
*/
public static void emit(Op op, int n, Reg r, Prim d) {
emit(op.ordinal(), n, r.ordinal(), d.ordinal());
}
/**
* emit operation with single literal argument d (n,r not used). These are
* operations like LOADL 44, PUSH 3, and CALLD 1
*/
public static void emit(Op op, int d) {
emit(op.ordinal(), 0, 0, d);
}
/**
* emit "call primitive operation" (operation built-in to mJAM). This
* generates CALL primitiveop[PB]
*/
public static void emit(Prim d) {
emit(Op.CALL.ordinal(), 0, Machine.Reg.PB.ordinal(), d.ordinal());
}
/**
* emit operations without arguments. These are operations like
* LOADI and STOREI
*/
public static void emit(Op op) {
emit(op, 0, 0, 0);
}
/**
* emit operation with register r and integer displacement. These are
* operations like JUMP 25[CB] and LOAD 6[LB]
*/
public static void emit(Op op, Reg r, int d) {
emit(op.ordinal(), 0, r.ordinal(), d);
}
/**
* emit operation with n field, and register r and integer displacement. These are
* operations like JUMPIF (1) 25[CB]. In the assembly code the value of n is shown
* in parens.
*/
public static void emit(Op op, int n, Reg r, int d) {
emit(op.ordinal(), n, r.ordinal(), d);
}
/**
* emit operation with integer n, r, d. These are operations
* like RETURN (1) 3 and HALT (4) 0. For RETURN the value
* of d is the number of caller args to pop off the callers
* stack and n is the number of values to return at caller stack
* top. n must be 0 or 1.
*/
public static void emit(Op op, int n, int r, int d) {
emit(op.ordinal(), n, r, d);
}
/**
* helper operation for emit using integer values
*/
private static void emit (int op, int n, int r, int d) {
if (n > 255) {
System.out.println("length of operand can't exceed 255 words");
n = 255; // to allow code generation to continue
}
if (CT >= Machine.PB)
System.out.println("mJAM: code segment capacity exceeded");
Instruction nextInstr = new Instruction(op, n, r, d);
Machine.code[CT] = nextInstr;
CT = CT + 1;
}
/**
* @return address (relative to CB) of next instruction to be generated
*/
public static int nextInstrAddr() {
return CT;
}
/**
* Update the displacement component of the (JUMP or CALL) instruction at addr
* @param addr
* @param displacement
*/
public static void patch(int addr, int displacement) {
if (addr < 0 || addr >= CT) {
System.out.println("patch: address of instruction to be patched is out of range");
return;
}
if (displacement < 0 || displacement > CT) {
System.out.println("patch: target address of patch is out of range");
return;
}
Machine.code[addr].d = displacement;
return;
}
// DATA REPRESENTATION
public final static int
booleanSize = 1,
characterSize = 1,
integerSize = 1,
addressSize = 1,
linkDataSize = 3 * addressSize, // caller's LB, OB, RA
falseRep = 0,
trueRep = 1,
nullRep = 0;
}
| ragibson/miniJava-compiler | mJAM/Machine.java | 2,003 | /**
* mJAM registers
*/ | block_comment | nl | package mJAM;
/**
* Defines names and sizes of mJAM instructions and primitives
* @author prins
* @version COMP 520 V2.3
*/
public final class Machine {
/**
* mJAM instructions
*/
public enum Op {
LOAD,
LOADA,
LOADI,
LOADL,
STORE,
STOREI,
CALL, // direct call of instance method
CALLI, // indirect call of instance method
CALLD, // dynamic call of instance method
RETURN,
PUSH,
POP,
JUMP,
JUMPI,
JUMPIF,
HALT;
}
public static Op [] intToOp = Op.values();
/**
* mJAM registers
<SUF>*/
public enum Reg {
ZR, // zero, not used
CB, // code base
CT, // code top
CP, // code pointer
PB, // primitives base
PT, // primitives top
SB, // execution stack base
ST, // execution stack top
LB, // locals base (frame pointer)
HB, // heap base
HT, // heap top
OB; // object base (instance pointer)
}
public static Reg [] intToReg = Reg.values();
/**
* mJAM primitives
*/
public enum Prim {
id,
not,
and,
or,
succ,
pred,
neg,
add,
sub,
mult,
div,
mod,
lt,
le,
ge,
gt,
eq,
ne,
eol,
eof,
get,
put,
geteol,
puteol,
getint,
putint,
putintnl,
alloc,
dispose,
newobj,
newarr,
arraylen,
arrayref,
arrayupd,
fieldref,
fieldupd;
}
public static Prim [] intToPrim = Prim.values();
// range for int constants
public final static long
minintRep = -2147483648,
maxintRep = 2147483647;
// CODE STORE REGISTERS
public final static int CB = 0; // start of code space
public final static int PB = 1024; // size of code space reserved for instructions
public final static int PT = PB + Prim.values().length; // code space reserved for primitives
// CODE STORE
public static Instruction[] code = new Instruction[PB];
public static int CT = CB;
public static void initCodeGen() {
CT = CB;
}
/**
* Places an instruction, with the given fields, into the next position in the code store
* @param op - operation
* @param n - length
* @param r - register
* @param d - displacement
*/
public static void emit(Op op, int n, Reg r, Prim d) {
emit(op.ordinal(), n, r.ordinal(), d.ordinal());
}
/**
* emit operation with single literal argument d (n,r not used). These are
* operations like LOADL 44, PUSH 3, and CALLD 1
*/
public static void emit(Op op, int d) {
emit(op.ordinal(), 0, 0, d);
}
/**
* emit "call primitive operation" (operation built-in to mJAM). This
* generates CALL primitiveop[PB]
*/
public static void emit(Prim d) {
emit(Op.CALL.ordinal(), 0, Machine.Reg.PB.ordinal(), d.ordinal());
}
/**
* emit operations without arguments. These are operations like
* LOADI and STOREI
*/
public static void emit(Op op) {
emit(op, 0, 0, 0);
}
/**
* emit operation with register r and integer displacement. These are
* operations like JUMP 25[CB] and LOAD 6[LB]
*/
public static void emit(Op op, Reg r, int d) {
emit(op.ordinal(), 0, r.ordinal(), d);
}
/**
* emit operation with n field, and register r and integer displacement. These are
* operations like JUMPIF (1) 25[CB]. In the assembly code the value of n is shown
* in parens.
*/
public static void emit(Op op, int n, Reg r, int d) {
emit(op.ordinal(), n, r.ordinal(), d);
}
/**
* emit operation with integer n, r, d. These are operations
* like RETURN (1) 3 and HALT (4) 0. For RETURN the value
* of d is the number of caller args to pop off the callers
* stack and n is the number of values to return at caller stack
* top. n must be 0 or 1.
*/
public static void emit(Op op, int n, int r, int d) {
emit(op.ordinal(), n, r, d);
}
/**
* helper operation for emit using integer values
*/
private static void emit (int op, int n, int r, int d) {
if (n > 255) {
System.out.println("length of operand can't exceed 255 words");
n = 255; // to allow code generation to continue
}
if (CT >= Machine.PB)
System.out.println("mJAM: code segment capacity exceeded");
Instruction nextInstr = new Instruction(op, n, r, d);
Machine.code[CT] = nextInstr;
CT = CT + 1;
}
/**
* @return address (relative to CB) of next instruction to be generated
*/
public static int nextInstrAddr() {
return CT;
}
/**
* Update the displacement component of the (JUMP or CALL) instruction at addr
* @param addr
* @param displacement
*/
public static void patch(int addr, int displacement) {
if (addr < 0 || addr >= CT) {
System.out.println("patch: address of instruction to be patched is out of range");
return;
}
if (displacement < 0 || displacement > CT) {
System.out.println("patch: target address of patch is out of range");
return;
}
Machine.code[addr].d = displacement;
return;
}
// DATA REPRESENTATION
public final static int
booleanSize = 1,
characterSize = 1,
integerSize = 1,
addressSize = 1,
linkDataSize = 3 * addressSize, // caller's LB, OB, RA
falseRep = 0,
trueRep = 1,
nullRep = 0;
}
|
159341_5 | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.health.check;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
/**
* Configuration class for retry policies used in health check operations.
*
* @author ydoksanbir
*/
@Configuration
@Component
public class RetryConfig {
/** The backoff period in milliseconds to wait between retry attempts. */
@Value("${retry.backoff.period:2000}")
private long backOffPeriod;
/** The maximum number of retry attempts for health check operations. */
@Value("${retry.max.attempts:3}")
private int maxAttempts;
/**
* Creates a retry template with the configured backoff period and maximum number of attempts.
*
* @return a retry template
*/
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(backOffPeriod); // wait 2 seconds between retries
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts); // retry a max of 3 attempts
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
}
| rajprins/java-design-patterns | health-check/src/main/java/com/iluwatar/health/check/RetryConfig.java | 804 | // wait 2 seconds between retries | line_comment | nl | /*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.health.check;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.backoff.FixedBackOffPolicy;
import org.springframework.retry.policy.SimpleRetryPolicy;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.stereotype.Component;
/**
* Configuration class for retry policies used in health check operations.
*
* @author ydoksanbir
*/
@Configuration
@Component
public class RetryConfig {
/** The backoff period in milliseconds to wait between retry attempts. */
@Value("${retry.backoff.period:2000}")
private long backOffPeriod;
/** The maximum number of retry attempts for health check operations. */
@Value("${retry.max.attempts:3}")
private int maxAttempts;
/**
* Creates a retry template with the configured backoff period and maximum number of attempts.
*
* @return a retry template
*/
@Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(backOffPeriod); // wait 2<SUF>
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(maxAttempts); // retry a max of 3 attempts
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
}
}
|
74310_2 | package school.management.system;
/**
* Created by Rakshith on 4/3/2017.
* This class is responsible for keeping the
* track of students fees, name ,grade & fees
* paid.
*
*/
public class Student {
private int id;
private String name;
private int grade;
private int feesPaid;
private int feesTotal;
/**
* To create a new student by initializing.
* Fees for every student is $30,000.
* Fees paid initially is 0.
* @param id id for the student: unique.
* @param name name of the student.
* @param grade grade of the student.
*/
public Student(int id, String name,int grade){
this.feesPaid=0;
this.feesTotal=30000;
this.id=id;
this.name=name;
this.grade=grade;
}
//Not going to alter student's name, student's id.
/**
* Used to update the student's grade.
* @param grade new grade of the student.
*/
public void setGrade(int grade){
this.grade=grade;
}
/**
* Keep adding the fees to feesPaid Field.
* Add the fees to the fees paid.
* The school is going receive the funds.
*
* @param fees the fees that the student pays.
*/
public void payFees(int fees){
feesPaid+=fees;
School.updateTotalMoneyEarned(feesPaid);
}
/**
*
* @return id of the student.
*/
public int getId() {
return id;
}
/**
*
* @return name of the student.
*/
public String getName() {
return name;
}
/**
*
* @return the grade of the student.
*/
public int getGrade() {
return grade;
}
/**
*
* @return fees paid by the student.
*/
public int getFeesPaid() {
return feesPaid;
}
/**
*
* @return the total fees of the student.
*/
public int getFeesTotal() {
return feesTotal;
}
/**
*
* @return the remaining fees.
*/
public int getRemainingFees(){
return feesTotal-feesPaid;
}
@Override
public String toString() {
return "Student's name :"+name+
" Total fees paid so far $"+ feesPaid;
}
}
| rakshithvasudev/Java-Basic-Tutorials | src/school/management/system/Student.java | 681 | //Not going to alter student's name, student's id. | line_comment | nl | package school.management.system;
/**
* Created by Rakshith on 4/3/2017.
* This class is responsible for keeping the
* track of students fees, name ,grade & fees
* paid.
*
*/
public class Student {
private int id;
private String name;
private int grade;
private int feesPaid;
private int feesTotal;
/**
* To create a new student by initializing.
* Fees for every student is $30,000.
* Fees paid initially is 0.
* @param id id for the student: unique.
* @param name name of the student.
* @param grade grade of the student.
*/
public Student(int id, String name,int grade){
this.feesPaid=0;
this.feesTotal=30000;
this.id=id;
this.name=name;
this.grade=grade;
}
//Not going<SUF>
/**
* Used to update the student's grade.
* @param grade new grade of the student.
*/
public void setGrade(int grade){
this.grade=grade;
}
/**
* Keep adding the fees to feesPaid Field.
* Add the fees to the fees paid.
* The school is going receive the funds.
*
* @param fees the fees that the student pays.
*/
public void payFees(int fees){
feesPaid+=fees;
School.updateTotalMoneyEarned(feesPaid);
}
/**
*
* @return id of the student.
*/
public int getId() {
return id;
}
/**
*
* @return name of the student.
*/
public String getName() {
return name;
}
/**
*
* @return the grade of the student.
*/
public int getGrade() {
return grade;
}
/**
*
* @return fees paid by the student.
*/
public int getFeesPaid() {
return feesPaid;
}
/**
*
* @return the total fees of the student.
*/
public int getFeesTotal() {
return feesTotal;
}
/**
*
* @return the remaining fees.
*/
public int getRemainingFees(){
return feesTotal-feesPaid;
}
@Override
public String toString() {
return "Student's name :"+name+
" Total fees paid so far $"+ feesPaid;
}
}
|
160742_1 | package ch.rasc.webpush;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ch.rasc.webpush.ChuckNorrisJokeService.Joke;
import ch.rasc.webpush.dto.PushMessage;
import ch.rasc.webpush.dto.Subscription;
import ch.rasc.webpush.dto.SubscriptionEndpoint;
@RestController
public class PushController {
private final ServerKeys serverKeys;
private final CryptoService cryptoService;
private final Map<String, Subscription> subscriptions = new ConcurrentHashMap<>();
private String lastNumbersAPIFact = "";
private final HttpClient httpClient;
private final Algorithm jwtAlgorithm;
private final ObjectMapper objectMapper;
private final ChuckNorrisJokeService service;
public PushController(ServerKeys serverKeys, CryptoService cryptoService,
ObjectMapper objectMapper) {
this.serverKeys = serverKeys;
this.cryptoService = cryptoService;
this.httpClient = HttpClient.newHttpClient();
this.objectMapper = objectMapper;
this.jwtAlgorithm = Algorithm.ECDSA256(this.serverKeys.getPublicKey(),
this.serverKeys.getPrivateKey());
WebClient client = WebClient.builder().baseUrl("https://api.chucknorris.io").build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builder(WebClientAdapter.forClient(client)).build();
this.service = factory.createClient(ChuckNorrisJokeService.class);
}
@GetMapping(path = "/publicSigningKey", produces = "application/octet-stream")
public byte[] publicSigningKey() {
return this.serverKeys.getPublicKeyUncompressed();
}
@PostMapping("/subscribe")
@ResponseStatus(HttpStatus.CREATED)
public void subscribe(@RequestBody Subscription subscription) {
this.subscriptions.put(subscription.getEndpoint(), subscription);
}
@PostMapping("/unsubscribe")
public void unsubscribe(@RequestBody SubscriptionEndpoint subscription) {
this.subscriptions.remove(subscription.getEndpoint());
}
@PostMapping("/isSubscribed")
public boolean isSubscribed(@RequestBody SubscriptionEndpoint subscription) {
return this.subscriptions.containsKey(subscription.getEndpoint());
}
@GetMapping(path = "/lastNumbersAPIFact")
public String lastNumbersAPIFact() {
return this.lastNumbersAPIFact;
}
@Scheduled(fixedDelay = 20_000)
public void numberFact() {
if (this.subscriptions.isEmpty()) {
return;
}
try {
HttpResponse<String> response = this.httpClient.send(
HttpRequest.newBuilder(URI.create("http://numbersapi.com/random/date")).build(),
BodyHandlers.ofString());
if (response.statusCode() == 200) {
this.lastNumbersAPIFact = response.body();
sendPushMessageToAllSubscribersWithoutPayload();
}
}
catch (IOException | InterruptedException e) {
Application.logger.error("fetch number fact", e);
}
}
@Scheduled(fixedDelay = 30_000)
public void chuckNorrisJoke() {
if (this.subscriptions.isEmpty()) {
return;
}
try {
Joke joke = this.service.getRandomJoke();
sendPushMessageToAllSubscribers(this.subscriptions,
new PushMessage("Chuck Norris Joke: " + joke.id(), joke.value()));
}
catch (IOException e) {
Application.logger.error("sending chuck norris joke failed", e);
}
}
private void sendPushMessageToAllSubscribersWithoutPayload() {
Set<String> failedSubscriptions = new HashSet<>();
for (Subscription subscription : this.subscriptions.values()) {
boolean remove = sendPushMessage(subscription, null);
if (remove) {
failedSubscriptions.add(subscription.getEndpoint());
}
}
failedSubscriptions.forEach(this.subscriptions::remove);
}
private void sendPushMessageToAllSubscribers(Map<String, Subscription> subs,
Object message) throws JsonProcessingException {
Set<String> failedSubscriptions = new HashSet<>();
for (Subscription subscription : subs.values()) {
try {
byte[] result = this.cryptoService.encrypt(
this.objectMapper.writeValueAsString(message),
subscription.getKeys().getP256dh(), subscription.getKeys().getAuth(), 0);
boolean remove = sendPushMessage(subscription, result);
if (remove) {
failedSubscriptions.add(subscription.getEndpoint());
}
}
catch (InvalidKeyException | NoSuchAlgorithmException
| InvalidAlgorithmParameterException | IllegalStateException
| InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException
| BadPaddingException e) {
Application.logger.error("send encrypted message", e);
}
}
failedSubscriptions.forEach(subs::remove);
}
/**
* @return true if the subscription is no longer valid and can be removed, false if
* everything is okay
*/
private boolean sendPushMessage(Subscription subscription, byte[] body) {
String origin = null;
try {
URL url = new URL(subscription.getEndpoint());
origin = url.getProtocol() + "://" + url.getHost();
}
catch (MalformedURLException e) {
Application.logger.error("create origin", e);
return true;
}
Date today = new Date();
Date expires = new Date(today.getTime() + 12 * 60 * 60 * 1000);
String token = JWT.create().withAudience(origin).withExpiresAt(expires)
.withSubject("mailto:[email protected]").sign(this.jwtAlgorithm);
URI endpointURI = URI.create(subscription.getEndpoint());
Builder httpRequestBuilder = HttpRequest.newBuilder();
if (body != null) {
httpRequestBuilder.POST(BodyPublishers.ofByteArray(body))
.header("Content-Type", "application/octet-stream")
.header("Content-Encoding", "aes128gcm");
}
else {
httpRequestBuilder.POST(BodyPublishers.ofString(""));
// httpRequestBuilder.header("Content-Length", "0");
}
HttpRequest request = httpRequestBuilder.uri(endpointURI).header("TTL", "180")
.header("Authorization",
"vapid t=" + token + ", k=" + this.serverKeys.getPublicKeyBase64())
.build();
try {
HttpResponse<Void> response = this.httpClient.send(request,
BodyHandlers.discarding());
switch (response.statusCode()) {
case 201:
Application.logger.info("Push message successfully sent: {}",
subscription.getEndpoint());
break;
case 404:
case 410:
Application.logger.warn("Subscription not found or gone: {}",
subscription.getEndpoint());
// remove subscription from our collection of subscriptions
return true;
case 429:
Application.logger.error("Too many requests: {}", request);
break;
case 400:
Application.logger.error("Invalid request: {}", request);
break;
case 413:
Application.logger.error("Payload size too large: {}", request);
break;
default:
Application.logger.error("Unhandled status code: {} / {}", response.statusCode(),
request);
}
}
catch (IOException | InterruptedException e) {
Application.logger.error("send push message", e);
}
return false;
}
} | ralscha/blog2019 | webpush/src/main/java/ch/rasc/webpush/PushController.java | 2,624 | //" + url.getHost();
| line_comment | nl | package ch.rasc.webpush;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import ch.rasc.webpush.ChuckNorrisJokeService.Joke;
import ch.rasc.webpush.dto.PushMessage;
import ch.rasc.webpush.dto.Subscription;
import ch.rasc.webpush.dto.SubscriptionEndpoint;
@RestController
public class PushController {
private final ServerKeys serverKeys;
private final CryptoService cryptoService;
private final Map<String, Subscription> subscriptions = new ConcurrentHashMap<>();
private String lastNumbersAPIFact = "";
private final HttpClient httpClient;
private final Algorithm jwtAlgorithm;
private final ObjectMapper objectMapper;
private final ChuckNorrisJokeService service;
public PushController(ServerKeys serverKeys, CryptoService cryptoService,
ObjectMapper objectMapper) {
this.serverKeys = serverKeys;
this.cryptoService = cryptoService;
this.httpClient = HttpClient.newHttpClient();
this.objectMapper = objectMapper;
this.jwtAlgorithm = Algorithm.ECDSA256(this.serverKeys.getPublicKey(),
this.serverKeys.getPrivateKey());
WebClient client = WebClient.builder().baseUrl("https://api.chucknorris.io").build();
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builder(WebClientAdapter.forClient(client)).build();
this.service = factory.createClient(ChuckNorrisJokeService.class);
}
@GetMapping(path = "/publicSigningKey", produces = "application/octet-stream")
public byte[] publicSigningKey() {
return this.serverKeys.getPublicKeyUncompressed();
}
@PostMapping("/subscribe")
@ResponseStatus(HttpStatus.CREATED)
public void subscribe(@RequestBody Subscription subscription) {
this.subscriptions.put(subscription.getEndpoint(), subscription);
}
@PostMapping("/unsubscribe")
public void unsubscribe(@RequestBody SubscriptionEndpoint subscription) {
this.subscriptions.remove(subscription.getEndpoint());
}
@PostMapping("/isSubscribed")
public boolean isSubscribed(@RequestBody SubscriptionEndpoint subscription) {
return this.subscriptions.containsKey(subscription.getEndpoint());
}
@GetMapping(path = "/lastNumbersAPIFact")
public String lastNumbersAPIFact() {
return this.lastNumbersAPIFact;
}
@Scheduled(fixedDelay = 20_000)
public void numberFact() {
if (this.subscriptions.isEmpty()) {
return;
}
try {
HttpResponse<String> response = this.httpClient.send(
HttpRequest.newBuilder(URI.create("http://numbersapi.com/random/date")).build(),
BodyHandlers.ofString());
if (response.statusCode() == 200) {
this.lastNumbersAPIFact = response.body();
sendPushMessageToAllSubscribersWithoutPayload();
}
}
catch (IOException | InterruptedException e) {
Application.logger.error("fetch number fact", e);
}
}
@Scheduled(fixedDelay = 30_000)
public void chuckNorrisJoke() {
if (this.subscriptions.isEmpty()) {
return;
}
try {
Joke joke = this.service.getRandomJoke();
sendPushMessageToAllSubscribers(this.subscriptions,
new PushMessage("Chuck Norris Joke: " + joke.id(), joke.value()));
}
catch (IOException e) {
Application.logger.error("sending chuck norris joke failed", e);
}
}
private void sendPushMessageToAllSubscribersWithoutPayload() {
Set<String> failedSubscriptions = new HashSet<>();
for (Subscription subscription : this.subscriptions.values()) {
boolean remove = sendPushMessage(subscription, null);
if (remove) {
failedSubscriptions.add(subscription.getEndpoint());
}
}
failedSubscriptions.forEach(this.subscriptions::remove);
}
private void sendPushMessageToAllSubscribers(Map<String, Subscription> subs,
Object message) throws JsonProcessingException {
Set<String> failedSubscriptions = new HashSet<>();
for (Subscription subscription : subs.values()) {
try {
byte[] result = this.cryptoService.encrypt(
this.objectMapper.writeValueAsString(message),
subscription.getKeys().getP256dh(), subscription.getKeys().getAuth(), 0);
boolean remove = sendPushMessage(subscription, result);
if (remove) {
failedSubscriptions.add(subscription.getEndpoint());
}
}
catch (InvalidKeyException | NoSuchAlgorithmException
| InvalidAlgorithmParameterException | IllegalStateException
| InvalidKeySpecException | NoSuchPaddingException | IllegalBlockSizeException
| BadPaddingException e) {
Application.logger.error("send encrypted message", e);
}
}
failedSubscriptions.forEach(subs::remove);
}
/**
* @return true if the subscription is no longer valid and can be removed, false if
* everything is okay
*/
private boolean sendPushMessage(Subscription subscription, byte[] body) {
String origin = null;
try {
URL url = new URL(subscription.getEndpoint());
origin = url.getProtocol() + "://" +<SUF>
}
catch (MalformedURLException e) {
Application.logger.error("create origin", e);
return true;
}
Date today = new Date();
Date expires = new Date(today.getTime() + 12 * 60 * 60 * 1000);
String token = JWT.create().withAudience(origin).withExpiresAt(expires)
.withSubject("mailto:[email protected]").sign(this.jwtAlgorithm);
URI endpointURI = URI.create(subscription.getEndpoint());
Builder httpRequestBuilder = HttpRequest.newBuilder();
if (body != null) {
httpRequestBuilder.POST(BodyPublishers.ofByteArray(body))
.header("Content-Type", "application/octet-stream")
.header("Content-Encoding", "aes128gcm");
}
else {
httpRequestBuilder.POST(BodyPublishers.ofString(""));
// httpRequestBuilder.header("Content-Length", "0");
}
HttpRequest request = httpRequestBuilder.uri(endpointURI).header("TTL", "180")
.header("Authorization",
"vapid t=" + token + ", k=" + this.serverKeys.getPublicKeyBase64())
.build();
try {
HttpResponse<Void> response = this.httpClient.send(request,
BodyHandlers.discarding());
switch (response.statusCode()) {
case 201:
Application.logger.info("Push message successfully sent: {}",
subscription.getEndpoint());
break;
case 404:
case 410:
Application.logger.warn("Subscription not found or gone: {}",
subscription.getEndpoint());
// remove subscription from our collection of subscriptions
return true;
case 429:
Application.logger.error("Too many requests: {}", request);
break;
case 400:
Application.logger.error("Invalid request: {}", request);
break;
case 413:
Application.logger.error("Payload size too large: {}", request);
break;
default:
Application.logger.error("Unhandled status code: {} / {}", response.statusCode(),
request);
}
}
catch (IOException | InterruptedException e) {
Application.logger.error("send push message", e);
}
return false;
}
} |
180952_6 | package com.example.ChallangeMe_v1;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Criteria;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by ConstantijnSchepens on 25/03/14.
*/
public class GPS extends Service implements LocationListener {
/** Variables **/
private static final String TAG = "SensorApp";
public static final String BROADCAST_ACTION = "com.example.Sensor.broadcastGPS"; //identifies broadcast
private final Handler handler = new Handler(); //handler to broadcast within thread
Intent intent;
boolean isGPSEnabled = false; //GPS status flag
boolean isNetworkEnabled = false; //Network status flag
boolean canGetLocation = false; //GPS status
Location currentLoc; //stores full location
double latitude; //lat
double longitude; //long
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; //1m
private static final long MIN_TIME_BW_UPDATES = 1; //1ms
protected LocationManager locationManager; //location manager declaration
Criteria c;
/** Lifecyle Methods" **/
@Override
public void onCreate(){
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
//startup code
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_LOW); //TODO fine?
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//TODO use pending intent?
// locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
// locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0,0.0F,this);
locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),0,0.0F,this);
Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
// Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show();
} catch (Exception e){
Log.e(TAG, "Unable to start GPS", e);
Toast.makeText(this, "Unable to start GPS: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
//called when started
currentLoc = locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true));
if(currentLoc != null){
latitude = currentLoc.getLatitude();
longitude = currentLoc.getLongitude();
/** Ensure app doesn't crash on start with in first location **/
intent = new Intent(BROADCAST_ACTION); //clear intent
intent.putExtra("latitude", (float)currentLoc.getLatitude());
intent.putExtra("longitude", (float)currentLoc.getLongitude());
sendBroadcast(intent);
} else {
Toast.makeText(this, "current==NULL", Toast.LENGTH_SHORT).show();
}
return 1;
}
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider){
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onLocationChanged(Location location) {
//TODO
if(locationManager != null){
currentLoc = location;
// locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true));
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if(status != 2){ //2 means available
/** Always use the best provider**/
locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true), MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
/** Method to handle handler update**/
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
//sendData();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void sendData() {
Log.d(TAG, "entered DisplayLoggingInfo");
if(currentLoc != null){
intent = new Intent(BROADCAST_ACTION); //clear intent
intent.putExtra("latitude", (float)currentLoc.getLatitude());
intent.putExtra("longitude", (float)currentLoc.getLongitude());
//sendBroadcast(intent);
}
}
} | ram535ii/ChallengeMe | ChallangeMe_integrated_v1/src/com/example/ChallangeMe_v1/GPS.java | 1,553 | //TODO use pending intent? | line_comment | nl | package com.example.ChallangeMe_v1;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Criteria;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by ConstantijnSchepens on 25/03/14.
*/
public class GPS extends Service implements LocationListener {
/** Variables **/
private static final String TAG = "SensorApp";
public static final String BROADCAST_ACTION = "com.example.Sensor.broadcastGPS"; //identifies broadcast
private final Handler handler = new Handler(); //handler to broadcast within thread
Intent intent;
boolean isGPSEnabled = false; //GPS status flag
boolean isNetworkEnabled = false; //Network status flag
boolean canGetLocation = false; //GPS status
Location currentLoc; //stores full location
double latitude; //lat
double longitude; //long
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; //1m
private static final long MIN_TIME_BW_UPDATES = 1; //1ms
protected LocationManager locationManager; //location manager declaration
Criteria c;
/** Lifecyle Methods" **/
@Override
public void onCreate(){
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
//startup code
try {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_LOW); //TODO fine?
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
//TODO use<SUF>
// locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
// locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0,0.0F,this);
locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),0,0.0F,this);
Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
// Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show();
} catch (Exception e){
Log.e(TAG, "Unable to start GPS", e);
Toast.makeText(this, "Unable to start GPS: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
//called when started
currentLoc = locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true));
if(currentLoc != null){
latitude = currentLoc.getLatitude();
longitude = currentLoc.getLongitude();
/** Ensure app doesn't crash on start with in first location **/
intent = new Intent(BROADCAST_ACTION); //clear intent
intent.putExtra("latitude", (float)currentLoc.getLatitude());
intent.putExtra("longitude", (float)currentLoc.getLongitude());
sendBroadcast(intent);
} else {
Toast.makeText(this, "current==NULL", Toast.LENGTH_SHORT).show();
}
return 1;
}
@Override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider){
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onLocationChanged(Location location) {
//TODO
if(locationManager != null){
currentLoc = location;
// locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true));
if(location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
if(status != 2){ //2 means available
/** Always use the best provider**/
locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true), MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
/** Method to handle handler update**/
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
//sendData();
handler.postDelayed(this, 1000); // 1 seconds
}
};
private void sendData() {
Log.d(TAG, "entered DisplayLoggingInfo");
if(currentLoc != null){
intent = new Intent(BROADCAST_ACTION); //clear intent
intent.putExtra("latitude", (float)currentLoc.getLatitude());
intent.putExtra("longitude", (float)currentLoc.getLongitude());
//sendBroadcast(intent);
}
}
} |
147890_3 | package com.ramjava.transactioneel.bufferend.service;
import com.ramjava.transactioneel.bufferend.entity.Afdeling;
import com.ramjava.transactioneel.bufferend.entity.Medewerker;
import com.ramjava.transactioneel.bufferend.repository.AfdelingsRepo;
import com.ramjava.transactioneel.bufferend.repository.MedewerkersRepo;
import com.ramjava.transactioneel.bufferend.valueobject.MedewerkerRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MedewerkersDienst {
@Autowired
private MedewerkersRepo medewerkersRepo;
@Autowired
private AfdelingsRepo afdelingsRepo;
// If there are any exceptions, @Transactional will roll backed on both medewerker/afdeling tables,
// otherwise, commit if successful
@Transactional
public String saveMedewerker(MedewerkerRequestVO medewerkerRequestVO) {
// Receive info from request vo
var afdeling = new Afdeling();
afdeling.setDepName(medewerkerRequestVO.getDepName());
afdeling.setDepCode(medewerkerRequestVO.getDepName());
Long depId = afdelingsRepo.save(afdeling).getDepId();
// Set depId to medewerker object
var medewerker = new Medewerker();
//Medewerker medewerker1 = null; // Will throw NullPointerException
medewerker.setEmpName(medewerkerRequestVO.getEmpName());
medewerker.setEmail(medewerkerRequestVO.getEmail());
medewerker.setDepId(depId);
medewerkersRepo.save(medewerker);
//medewerkersRepo.save(medewerker1);
return "Medewerker is saved with Emp ID : " + medewerker.getEmpId();
}
}
| ramjay11/java-prosjekter3 | transactioneel-bufferend/src/main/java/com/ramjava/transactioneel/bufferend/service/MedewerkersDienst.java | 551 | // Set depId to medewerker object | line_comment | nl | package com.ramjava.transactioneel.bufferend.service;
import com.ramjava.transactioneel.bufferend.entity.Afdeling;
import com.ramjava.transactioneel.bufferend.entity.Medewerker;
import com.ramjava.transactioneel.bufferend.repository.AfdelingsRepo;
import com.ramjava.transactioneel.bufferend.repository.MedewerkersRepo;
import com.ramjava.transactioneel.bufferend.valueobject.MedewerkerRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class MedewerkersDienst {
@Autowired
private MedewerkersRepo medewerkersRepo;
@Autowired
private AfdelingsRepo afdelingsRepo;
// If there are any exceptions, @Transactional will roll backed on both medewerker/afdeling tables,
// otherwise, commit if successful
@Transactional
public String saveMedewerker(MedewerkerRequestVO medewerkerRequestVO) {
// Receive info from request vo
var afdeling = new Afdeling();
afdeling.setDepName(medewerkerRequestVO.getDepName());
afdeling.setDepCode(medewerkerRequestVO.getDepName());
Long depId = afdelingsRepo.save(afdeling).getDepId();
// Set depId<SUF>
var medewerker = new Medewerker();
//Medewerker medewerker1 = null; // Will throw NullPointerException
medewerker.setEmpName(medewerkerRequestVO.getEmpName());
medewerker.setEmail(medewerkerRequestVO.getEmail());
medewerker.setDepId(depId);
medewerkersRepo.save(medewerker);
//medewerkersRepo.save(medewerker1);
return "Medewerker is saved with Emp ID : " + medewerker.getEmpId();
}
}
|
20784_0 | package View;
import Controller.AccountController;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
public class MyScene extends Scene {
private Pane root;
private AccountController accountController;
public MyScene() {
super(new Pane());
root = new Pane();
// root.getChildren().add(new LoginView(this));
root.getChildren().add(new GameView());
// root.getChildren().add(new WindowPatternView());
this.setRoot(root);
// Maak een AccountController-object
accountController = new AccountController();
root.getChildren().add(new LoginView(this, accountController)); // Pass the accountController instance to LoginView constructor
}
public void goToLobby() {
root.getChildren().set(0, new LobbyView());
root.getChildren().add(new MenuBarView(this));
}
public void openLoginView() {
root.getChildren().remove(1);
root.getChildren().set(0,new LoginView(this, accountController)); // Pass the accountController instance to LoginView constructor
}
}
| ramonluteijn/Sagrada | src/View/MyScene.java | 308 | // Maak een AccountController-object | line_comment | nl | package View;
import Controller.AccountController;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
public class MyScene extends Scene {
private Pane root;
private AccountController accountController;
public MyScene() {
super(new Pane());
root = new Pane();
// root.getChildren().add(new LoginView(this));
root.getChildren().add(new GameView());
// root.getChildren().add(new WindowPatternView());
this.setRoot(root);
// Maak een<SUF>
accountController = new AccountController();
root.getChildren().add(new LoginView(this, accountController)); // Pass the accountController instance to LoginView constructor
}
public void goToLobby() {
root.getChildren().set(0, new LobbyView());
root.getChildren().add(new MenuBarView(this));
}
public void openLoginView() {
root.getChildren().remove(1);
root.getChildren().set(0,new LoginView(this, accountController)); // Pass the accountController instance to LoginView constructor
}
}
|
11184_1 | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie op. */
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
| ramononis/project-rollit | weeky7/src/ss/week7/cmdline/Client.java | 568 | /** Start een Client-applicatie op. */ | block_comment | nl | package ss.week7.cmdline;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* Client class for a simple client-server application
* @author Theo Ruys
* @version 2005.02.21
*/
public class Client {
private static final String USAGE = "usage: java week4.cmdline.Client <name> <address> <port>";
/** Start een Client-applicatie<SUF>*/
public static void main(String[] args) {
if (args.length != 3) {
System.out.println(USAGE);
System.exit(0);
}
String name = args[0];
InetAddress addr = null;
int port = 0;
Socket sock = null;
// check args[1] - the IP-adress
try {
addr = InetAddress.getByName(args[1]);
} catch (UnknownHostException e) {
System.out.println(USAGE);
System.out.println("ERROR: host " + args[1] + " unknown");
System.exit(0);
}
// parse args[2] - the port
try {
port = Integer.parseInt(args[2]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.out.println("ERROR: port " + args[2] + " is not an integer");
System.exit(0);
}
// try to open a Socket to the server
try {
sock = new Socket(addr, port);
} catch (IOException e) {
System.out.println("ERROR: could not create a socket on " + addr
+ " and port " + port);
}
// create Peer object and start the two-way communication
try {
Peer client = new Peer(name, sock);
Thread streamInputHandler = new Thread(client);
streamInputHandler.start();
client.handleTerminalInput();
System.out.println("komt ie heir?");
client.shutDown();
} catch (IOException e) {
e.printStackTrace();
}
}
} // end of class Client
|
133854_0 | package vechterspel.ui;
import vechterspel.domain.*;
public class SpelUI {
public static void main(String[] args) {
Spel spel = new Spel();
//voeg actoren toe aan spel
try {
spel.voegActortoe(new Elf("elfje"));
spel.voegActortoe(new Elf("twaalfje"));
spel.voegActortoe(new Rover("elfje", 200));
spel.voegActortoe(new Rover("Maurice", 300));
spel.voegActortoe(new Rover("Lowie", 4000));
spel.voegActortoe(new Rover("Twan", 500));
spel.voegActortoe(new Rover("Jakke", 200, 2000));
spel.voegActortoe(new Vampier("Toon", 300));
spel.voegActortoe(new Vampier("Uno", 300, 1500));
spel.voegActortoe(new Vampier("Dos", 50));
} catch (DomainException e) {System.out.println(e.getMessage());}
System.out.println("Actoren in spel\n"+spel);
//speel spel
for (int i = 1; i <= 10; i++) {
// get random vechter
Vechter aanvaller = spel.getRandomVechter();
if (aanvaller == null) break;
// get random tegenstander
Actor tegenstander = spel.getRandomActor(aanvaller);
if (tegenstander == null) break;
// aanvaller valt tegenstander aan
try{
System.out.println("-----------------------------------------------------");
System.out.println("🎲 Round " + i);
System.out.println(aanvaller + " \nvs\n" + tegenstander);
spel.valAan(aanvaller,tegenstander);
} catch (DomainException e) {
System.out.println(e.getMessage());
}
}
System.out.println("-----------------------------------------------------");
System.out.println("Actoren in spel\n" + spel);
System.out.println("Aantal levende vechters na aanvallen: " + spel.getLevendeVechters().size());
spel.reincarneerDodeActoren();
System.out.println("Aantal levende vechters na reincarnatie: " + spel.getLevendeVechters().size());
}
}
| randmon/ucl_ti_ooo | labo0/src/vechterspel/ui/SpelUI.java | 676 | //voeg actoren toe aan spel | line_comment | nl | package vechterspel.ui;
import vechterspel.domain.*;
public class SpelUI {
public static void main(String[] args) {
Spel spel = new Spel();
//voeg actoren<SUF>
try {
spel.voegActortoe(new Elf("elfje"));
spel.voegActortoe(new Elf("twaalfje"));
spel.voegActortoe(new Rover("elfje", 200));
spel.voegActortoe(new Rover("Maurice", 300));
spel.voegActortoe(new Rover("Lowie", 4000));
spel.voegActortoe(new Rover("Twan", 500));
spel.voegActortoe(new Rover("Jakke", 200, 2000));
spel.voegActortoe(new Vampier("Toon", 300));
spel.voegActortoe(new Vampier("Uno", 300, 1500));
spel.voegActortoe(new Vampier("Dos", 50));
} catch (DomainException e) {System.out.println(e.getMessage());}
System.out.println("Actoren in spel\n"+spel);
//speel spel
for (int i = 1; i <= 10; i++) {
// get random vechter
Vechter aanvaller = spel.getRandomVechter();
if (aanvaller == null) break;
// get random tegenstander
Actor tegenstander = spel.getRandomActor(aanvaller);
if (tegenstander == null) break;
// aanvaller valt tegenstander aan
try{
System.out.println("-----------------------------------------------------");
System.out.println("🎲 Round " + i);
System.out.println(aanvaller + " \nvs\n" + tegenstander);
spel.valAan(aanvaller,tegenstander);
} catch (DomainException e) {
System.out.println(e.getMessage());
}
}
System.out.println("-----------------------------------------------------");
System.out.println("Actoren in spel\n" + spel);
System.out.println("Aantal levende vechters na aanvallen: " + spel.getLevendeVechters().size());
spel.reincarneerDodeActoren();
System.out.println("Aantal levende vechters na reincarnatie: " + spel.getLevendeVechters().size());
}
}
|
146071_7 | /*
* 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.commons.rng.sampling.distribution;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
/**
* List of samplers.
*/
public class ContinuousSamplersList {
/** List of all RNGs implemented in the library. */
private static final List<ContinuousSamplerTestData[]> LIST =
new ArrayList<ContinuousSamplerTestData[]>();
static {
try {
// List of distributions to test.
// Gaussian ("inverse method").
final double meanNormal = -123.45;
final double sigmaNormal = 6.789;
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
RandomSource.create(RandomSource.KISS));
// Gaussian (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal));
// Gaussian ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)),
meanNormal, sigmaNormal));
// Gaussian ("Box-Muller" with rejection).
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new GaussianSampler(new BoxMullerWithRejectionNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)),
meanNormal, sigmaNormal));
// Beta ("inverse method").
final double alphaBeta = 4.3;
final double betaBeta = 2.1;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta),
RandomSource.create(RandomSource.ISAAC));
// Beta ("Cheng").
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta),
new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBeta, alphaBeta),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta));
// Beta ("Cheng", alternate algorithm).
final double alphaBetaAlt = 0.5678;
final double betaBetaAlt = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBetaAlt, betaBetaAlt),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBetaAlt, alphaBetaAlt),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt));
// Cauchy ("inverse method").
final double medianCauchy = 0.123;
final double scaleCauchy = 4.5;
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(medianCauchy, scaleCauchy),
RandomSource.create(RandomSource.WELL_19937_C));
// Chi-square ("inverse method").
final int dofChi2 = 12;
add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(dofChi2),
RandomSource.create(RandomSource.WELL_19937_A));
// Exponential ("inverse method").
final double meanExp = 3.45;
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp),
RandomSource.create(RandomSource.WELL_44497_A));
// Exponential.
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp),
new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp));
// F ("inverse method").
final int numDofF = 4;
final int denomDofF = 7;
add(LIST, new org.apache.commons.math3.distribution.FDistribution(numDofF, denomDofF),
RandomSource.create(RandomSource.MT_64));
// Gamma ("inverse method").
final double thetaGammaSmallerThanOne = 0.1234;
final double thetaGammaLargerThanOne = 2.345;
final double alphaGamma = 3.456;
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma),
RandomSource.create(RandomSource.SPLIT_MIX_64));
// Gamma (theta < 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaSmallerThanOne, alphaGamma),
new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S),
alphaGamma, thetaGammaSmallerThanOne));
// Gamma (theta > 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma),
new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B),
alphaGamma, thetaGammaLargerThanOne));
// Gumbel ("inverse method").
final double muGumbel = -4.56;
final double betaGumbel = 0.123;
add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(muGumbel, betaGumbel),
RandomSource.create(RandomSource.WELL_1024_A));
// Laplace ("inverse method").
final double muLaplace = 12.3;
final double betaLaplace = 5.6;
add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(muLaplace, betaLaplace),
RandomSource.create(RandomSource.MWC_256));
// Levy ("inverse method").
final double muLevy = -1.098;
final double cLevy = 0.76;
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(muLevy, cLevy),
RandomSource.create(RandomSource.TWO_CMRES));
// Log normal ("inverse method").
final double scaleLogNormal = 23.45;
final double shapeLogNormal = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal),
RandomSource.create(RandomSource.KISS));
// Log normal ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal),
new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal));
// Logistic ("inverse method").
final double muLogistic = -123.456;
final double sLogistic = 7.89;
add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(muLogistic, sLogistic),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6));
// Nakagami ("inverse method").
final double muNakagami = 78.9;
final double omegaNakagami = 23.4;
add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(muNakagami, omegaNakagami),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3));
// Pareto ("inverse method").
final double scalePareto = 23.45;
final double shapePareto = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11));
// Pareto.
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto),
new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto));
// T ("inverse method").
final double dofT = 0.76543;
add(LIST, new org.apache.commons.math3.distribution.TDistribution(dofT),
RandomSource.create(RandomSource.ISAAC));
// Triangular ("inverse method").
final double aTriangle = -0.76543;
final double cTriangle = -0.65432;
final double bTriangle = -0.54321;
add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(aTriangle, cTriangle, bTriangle),
RandomSource.create(RandomSource.MT));
// Uniform ("inverse method").
final double loUniform = -1.098;
final double hiUniform = 0.76;
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform),
RandomSource.create(RandomSource.TWO_CMRES));
// Uniform.
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform),
new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform));
// Weibull ("inverse method").
final double alphaWeibull = 678.9;
final double betaWeibull = 98.76;
add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(alphaWeibull, betaWeibull),
RandomSource.create(RandomSource.WELL_44497_B));
} catch (Exception e) {
System.err.println("Unexpected exception while creating the list of samplers: " + e);
e.printStackTrace(System.err);
throw new RuntimeException(e);
}
}
/**
* Class contains only static methods.
*/
private ContinuousSamplersList() {}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param rng Generator of uniformly distributed sequences.
*/
private static void add(List<ContinuousSamplerTestData[]> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
UniformRandomProvider rng) {
final ContinuousSampler inverseMethodSampler =
new InverseTransformContinuousSampler(rng,
new ContinuousInverseCumulativeProbabilityFunction() {
@Override
public double inverseCumulativeProbability(double p) {
return dist.inverseCumulativeProbability(p);
}
@Override
public String toString() {
return dist.toString();
}
});
list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler,
getDeciles(dist)) });
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData[]> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler,
getDeciles(dist)) });
}
/**
* Subclasses that are "parametric" tests can forward the call to
* the "@Parameters"-annotated method to this method.
*
* @return the list of all generators.
*/
public static Iterable<ContinuousSamplerTestData[]> list() {
return Collections.unmodifiableList(LIST);
}
/**
* @param dist Distribution.
* @return the deciles of the given distribution.
*/
private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) {
final int last = 9;
final double[] deciles = new double[last];
final double ten = 10;
for (int i = 0; i < last; i++) {
deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten);
}
return deciles;
}
}
| randoop/commons-rng | commons-rng-sampling/src/test/java/org/apache/commons/rng/sampling/distribution/ContinuousSamplersList.java | 3,857 | // Beta ("inverse method"). | line_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.commons.rng.sampling.distribution;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.commons.rng.UniformRandomProvider;
import org.apache.commons.rng.simple.RandomSource;
/**
* List of samplers.
*/
public class ContinuousSamplersList {
/** List of all RNGs implemented in the library. */
private static final List<ContinuousSamplerTestData[]> LIST =
new ArrayList<ContinuousSamplerTestData[]>();
static {
try {
// List of distributions to test.
// Gaussian ("inverse method").
final double meanNormal = -123.45;
final double sigmaNormal = 6.789;
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
RandomSource.create(RandomSource.KISS));
// Gaussian (DEPRECATED "Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new BoxMullerGaussianSampler(RandomSource.create(RandomSource.MT), meanNormal, sigmaNormal));
// Gaussian ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new GaussianSampler(new BoxMullerNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)),
meanNormal, sigmaNormal));
// Gaussian ("Box-Muller" with rejection).
add(LIST, new org.apache.commons.math3.distribution.NormalDistribution(meanNormal, sigmaNormal),
new GaussianSampler(new BoxMullerWithRejectionNormalizedGaussianSampler(RandomSource.create(RandomSource.MT)),
meanNormal, sigmaNormal));
// Beta ("inverse<SUF>
final double alphaBeta = 4.3;
final double betaBeta = 2.1;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta),
RandomSource.create(RandomSource.ISAAC));
// Beta ("Cheng").
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBeta, betaBeta),
new ChengBetaSampler(RandomSource.create(RandomSource.MWC_256), alphaBeta, betaBeta));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBeta, alphaBeta),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_A), betaBeta, alphaBeta));
// Beta ("Cheng", alternate algorithm).
final double alphaBetaAlt = 0.5678;
final double betaBetaAlt = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(alphaBetaAlt, betaBetaAlt),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_512_A), alphaBetaAlt, betaBetaAlt));
add(LIST, new org.apache.commons.math3.distribution.BetaDistribution(betaBetaAlt, alphaBetaAlt),
new ChengBetaSampler(RandomSource.create(RandomSource.WELL_19937_C), betaBetaAlt, alphaBetaAlt));
// Cauchy ("inverse method").
final double medianCauchy = 0.123;
final double scaleCauchy = 4.5;
add(LIST, new org.apache.commons.math3.distribution.CauchyDistribution(medianCauchy, scaleCauchy),
RandomSource.create(RandomSource.WELL_19937_C));
// Chi-square ("inverse method").
final int dofChi2 = 12;
add(LIST, new org.apache.commons.math3.distribution.ChiSquaredDistribution(dofChi2),
RandomSource.create(RandomSource.WELL_19937_A));
// Exponential ("inverse method").
final double meanExp = 3.45;
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp),
RandomSource.create(RandomSource.WELL_44497_A));
// Exponential.
add(LIST, new org.apache.commons.math3.distribution.ExponentialDistribution(meanExp),
new AhrensDieterExponentialSampler(RandomSource.create(RandomSource.MT), meanExp));
// F ("inverse method").
final int numDofF = 4;
final int denomDofF = 7;
add(LIST, new org.apache.commons.math3.distribution.FDistribution(numDofF, denomDofF),
RandomSource.create(RandomSource.MT_64));
// Gamma ("inverse method").
final double thetaGammaSmallerThanOne = 0.1234;
final double thetaGammaLargerThanOne = 2.345;
final double alphaGamma = 3.456;
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma),
RandomSource.create(RandomSource.SPLIT_MIX_64));
// Gamma (theta < 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaSmallerThanOne, alphaGamma),
new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S),
alphaGamma, thetaGammaSmallerThanOne));
// Gamma (theta > 1).
add(LIST, new org.apache.commons.math3.distribution.GammaDistribution(thetaGammaLargerThanOne, alphaGamma),
new AhrensDieterMarsagliaTsangGammaSampler(RandomSource.create(RandomSource.WELL_44497_B),
alphaGamma, thetaGammaLargerThanOne));
// Gumbel ("inverse method").
final double muGumbel = -4.56;
final double betaGumbel = 0.123;
add(LIST, new org.apache.commons.math3.distribution.GumbelDistribution(muGumbel, betaGumbel),
RandomSource.create(RandomSource.WELL_1024_A));
// Laplace ("inverse method").
final double muLaplace = 12.3;
final double betaLaplace = 5.6;
add(LIST, new org.apache.commons.math3.distribution.LaplaceDistribution(muLaplace, betaLaplace),
RandomSource.create(RandomSource.MWC_256));
// Levy ("inverse method").
final double muLevy = -1.098;
final double cLevy = 0.76;
add(LIST, new org.apache.commons.math3.distribution.LevyDistribution(muLevy, cLevy),
RandomSource.create(RandomSource.TWO_CMRES));
// Log normal ("inverse method").
final double scaleLogNormal = 23.45;
final double shapeLogNormal = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal),
RandomSource.create(RandomSource.KISS));
// Log normal ("Box-Muller").
add(LIST, new org.apache.commons.math3.distribution.LogNormalDistribution(scaleLogNormal, shapeLogNormal),
new BoxMullerLogNormalSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scaleLogNormal, shapeLogNormal));
// Logistic ("inverse method").
final double muLogistic = -123.456;
final double sLogistic = 7.89;
add(LIST, new org.apache.commons.math3.distribution.LogisticDistribution(muLogistic, sLogistic),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 2, 6));
// Nakagami ("inverse method").
final double muNakagami = 78.9;
final double omegaNakagami = 23.4;
add(LIST, new org.apache.commons.math3.distribution.NakagamiDistribution(muNakagami, omegaNakagami),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 5, 3));
// Pareto ("inverse method").
final double scalePareto = 23.45;
final double shapePareto = 0.1234;
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto),
RandomSource.create(RandomSource.TWO_CMRES_SELECT, null, 9, 11));
// Pareto.
add(LIST, new org.apache.commons.math3.distribution.ParetoDistribution(scalePareto, shapePareto),
new InverseTransformParetoSampler(RandomSource.create(RandomSource.XOR_SHIFT_1024_S), scalePareto, shapePareto));
// T ("inverse method").
final double dofT = 0.76543;
add(LIST, new org.apache.commons.math3.distribution.TDistribution(dofT),
RandomSource.create(RandomSource.ISAAC));
// Triangular ("inverse method").
final double aTriangle = -0.76543;
final double cTriangle = -0.65432;
final double bTriangle = -0.54321;
add(LIST, new org.apache.commons.math3.distribution.TriangularDistribution(aTriangle, cTriangle, bTriangle),
RandomSource.create(RandomSource.MT));
// Uniform ("inverse method").
final double loUniform = -1.098;
final double hiUniform = 0.76;
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform),
RandomSource.create(RandomSource.TWO_CMRES));
// Uniform.
add(LIST, new org.apache.commons.math3.distribution.UniformRealDistribution(loUniform, hiUniform),
new ContinuousUniformSampler(RandomSource.create(RandomSource.MT_64), loUniform, hiUniform));
// Weibull ("inverse method").
final double alphaWeibull = 678.9;
final double betaWeibull = 98.76;
add(LIST, new org.apache.commons.math3.distribution.WeibullDistribution(alphaWeibull, betaWeibull),
RandomSource.create(RandomSource.WELL_44497_B));
} catch (Exception e) {
System.err.println("Unexpected exception while creating the list of samplers: " + e);
e.printStackTrace(System.err);
throw new RuntimeException(e);
}
}
/**
* Class contains only static methods.
*/
private ContinuousSamplersList() {}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param rng Generator of uniformly distributed sequences.
*/
private static void add(List<ContinuousSamplerTestData[]> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
UniformRandomProvider rng) {
final ContinuousSampler inverseMethodSampler =
new InverseTransformContinuousSampler(rng,
new ContinuousInverseCumulativeProbabilityFunction() {
@Override
public double inverseCumulativeProbability(double p) {
return dist.inverseCumulativeProbability(p);
}
@Override
public String toString() {
return dist.toString();
}
});
list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(inverseMethodSampler,
getDeciles(dist)) });
}
/**
* @param list List of data (one the "parameters" tested by the Junit parametric test).
* @param dist Distribution to which the samples are supposed to conform.
* @param sampler Sampler.
*/
private static void add(List<ContinuousSamplerTestData[]> list,
final org.apache.commons.math3.distribution.RealDistribution dist,
final ContinuousSampler sampler) {
list.add(new ContinuousSamplerTestData[] { new ContinuousSamplerTestData(sampler,
getDeciles(dist)) });
}
/**
* Subclasses that are "parametric" tests can forward the call to
* the "@Parameters"-annotated method to this method.
*
* @return the list of all generators.
*/
public static Iterable<ContinuousSamplerTestData[]> list() {
return Collections.unmodifiableList(LIST);
}
/**
* @param dist Distribution.
* @return the deciles of the given distribution.
*/
private static double[] getDeciles(org.apache.commons.math3.distribution.RealDistribution dist) {
final int last = 9;
final double[] deciles = new double[last];
final double ten = 10;
for (int i = 0; i < last; i++) {
deciles[i] = dist.inverseCumulativeProbability((i + 1) / ten);
}
return deciles;
}
}
|
105899_6 | /*
* (c) Copyright 2006-2020 by rapiddweller GmbH & Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from rapiddweller GmbH & Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. 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 shop;
import static org.junit.Assert.*;
import com.rapiddweller.benerator.engine.DefaultBeneratorContext;
import com.rapiddweller.benerator.main.Benerator;
import com.rapiddweller.benerator.parser.DefaultEntryConverter;
import com.rapiddweller.common.IOUtil;
import com.rapiddweller.common.Validator;
import com.rapiddweller.model.data.Entity;
import com.rapiddweller.platform.db.DBSystem;
import org.databene.webdecs.DataContainer;
import org.databene.webdecs.DataIterator;
import org.junit.Test;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
import java.util.Map;
/**
* Tests the shop demo on all supported database systems.<br/>
* <br/>
* Created: 20.11.2007 13:24:13
*/
public class ShopDBTest {
private static final String BENERATOR_FILE = "demo/shop/shop.ben.xml";
private static final Logger logger = LogManager.getLogger(ShopDBTest.class);
/**
* Test hsql in mem.
*
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
*/
/*
public void testDB2() throws IOException, InterruptedException {
checkGeneration("db2");
}
public void testDerby() throws IOException, InterruptedException {
checkGeneration("derby");
}
*/
@Test
public void testHSQLInMem() throws IOException, InterruptedException {
checkGeneration("hsqlmem");
}
/**
* Test firebird.
*
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
*/
@Test
public void testFirebird() throws IOException, InterruptedException {
checkGeneration("firebird");
}
/*
public void testHSQL() throws IOException, InterruptedException {
checkGeneration("hsql");
}
public void testSQLServer() throws IOException, InterruptedException {
checkGeneration("ms_sql_server");
}
public void testMySQL() throws IOException, InterruptedException {
checkGeneration("mysql");
}
public void testOracle() throws IOException, InterruptedException {
checkGeneration("oracle");
}
public void testPostgres() throws IOException, InterruptedException {
checkGeneration("postgres");
}
*/
// private helpers -------------------------------------------------------------------------------------------------
private void checkGeneration(String database)
throws IOException, InterruptedException {
//checkGeneration(database, true);
checkGeneration(database, "test", false);
}
private void checkGeneration(String database, String stage, boolean shell)
throws IOException, InterruptedException {
if (shell) {
runFromCommandLine(BENERATOR_FILE, database, "test");
} else {
runAsClass(BENERATOR_FILE, database, "test");
}
// connect to database
Map<String, String> dbCfg = IOUtil.readProperties(
"demo/shop/" + database + "/shop." + database + ".properties");
DefaultBeneratorContext context = new DefaultBeneratorContext();
DBSystem db =
new DBSystem("db", dbCfg.get("dbUri"), dbCfg.get("dbDriver"),
dbCfg.get("dbUser"), dbCfg.get("dbPassword"),
context.getDataModel());
// check generation results
Map<String, Object> genCfg =
IOUtil.readProperties("demo/shop/shop." + stage + ".properties",
new DefaultEntryConverter(context));
int expectedProductCount = 6 + (Integer) genCfg.get("product_count");
int expectedCustomerCount = 1 + (Integer) genCfg.get("customer_count");
int expectedUserCount = 3 + expectedCustomerCount;
int ordersPerCustomer = (Integer) genCfg.get("orders_per_customer");
int expectedOrderCount =
(expectedCustomerCount - 1) * ordersPerCustomer + 1;
int itemsPerOrder = (Integer) genCfg.get("items_per_order");
int expectedOrderItemCount =
(expectedOrderCount - 1) * itemsPerOrder + 1;
checkEntities("db_category", new CategoryValidator("db_category"), 28,
db);
checkEntities("db_product", new ProductValidator("db_product"),
expectedProductCount, db);
checkEntities("db_user", new UserValidator("db_user"),
expectedUserCount, db);
checkEntities("db_customer", new CustomerValidator("db_customer"),
expectedCustomerCount, db);
checkEntities("db_order", new OrderValidator("db_order"),
expectedOrderCount, db);
checkEntities("db_order_item", new OrderItemValidator("db_order_item"),
expectedOrderItemCount, db);
}
private void checkEntities(String entityName, Validator<Entity> validator,
int expectedCount, DBSystem db) {
assertEquals("Wrong number of '" + entityName + "' instances.",
expectedCount, db.countEntities(entityName));
DataIterator<Entity> iterator =
db.queryEntities(entityName, null, null).iterator();
DataContainer<Entity> container = new DataContainer<Entity>();
while ((container = iterator.next(container)) != null) {
Entity entity = container.getData();
assertTrue("Invalid entity: " + entity, validator.valid(entity));
}
}
private void runAsClass(String file, String database, String stage)
throws IOException {
System.setProperty("stage", stage);
System.setProperty("database", database);
Benerator.main(new String[] {file});
}
private void runFromCommandLine(String file, String database, String stage)
throws IOException, InterruptedException {
String command =
"benerator -Ddatabase=" + database + " -Dstage=" + stage + " " +
file;
if (logger.isDebugEnabled()) {
logger.debug(command);
}
Process process = Runtime.getRuntime().exec(command);
IOUtil.transfer(process.getInputStream(), System.out);
process.waitFor();
if (logger.isDebugEnabled()) {
logger.debug(String.valueOf(process.exitValue()));
}
}
}
| rapiddweller/rapiddweller-benerator-ce | src/demo/java/shop/ShopDBTest.java | 2,146 | // private helpers ------------------------------------------------------------------------------------------------- | line_comment | nl | /*
* (c) Copyright 2006-2020 by rapiddweller GmbH & Volker Bergmann. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, is permitted under the terms of the
* GNU General Public License.
*
* For redistributing this software or a derivative work under a license other
* than the GPL-compatible Free Software License as defined by the Free
* Software Foundation or approved by OSI, you must first obtain a commercial
* license to this software product from rapiddweller GmbH & Volker Bergmann.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* WITHOUT A WARRANTY OF ANY KIND. ALL EXPRESS OR IMPLIED CONDITIONS,
* REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE
* HEREBY EXCLUDED. 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 shop;
import static org.junit.Assert.*;
import com.rapiddweller.benerator.engine.DefaultBeneratorContext;
import com.rapiddweller.benerator.main.Benerator;
import com.rapiddweller.benerator.parser.DefaultEntryConverter;
import com.rapiddweller.common.IOUtil;
import com.rapiddweller.common.Validator;
import com.rapiddweller.model.data.Entity;
import com.rapiddweller.platform.db.DBSystem;
import org.databene.webdecs.DataContainer;
import org.databene.webdecs.DataIterator;
import org.junit.Test;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.io.IOException;
import java.util.Map;
/**
* Tests the shop demo on all supported database systems.<br/>
* <br/>
* Created: 20.11.2007 13:24:13
*/
public class ShopDBTest {
private static final String BENERATOR_FILE = "demo/shop/shop.ben.xml";
private static final Logger logger = LogManager.getLogger(ShopDBTest.class);
/**
* Test hsql in mem.
*
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
*/
/*
public void testDB2() throws IOException, InterruptedException {
checkGeneration("db2");
}
public void testDerby() throws IOException, InterruptedException {
checkGeneration("derby");
}
*/
@Test
public void testHSQLInMem() throws IOException, InterruptedException {
checkGeneration("hsqlmem");
}
/**
* Test firebird.
*
* @throws IOException the io exception
* @throws InterruptedException the interrupted exception
*/
@Test
public void testFirebird() throws IOException, InterruptedException {
checkGeneration("firebird");
}
/*
public void testHSQL() throws IOException, InterruptedException {
checkGeneration("hsql");
}
public void testSQLServer() throws IOException, InterruptedException {
checkGeneration("ms_sql_server");
}
public void testMySQL() throws IOException, InterruptedException {
checkGeneration("mysql");
}
public void testOracle() throws IOException, InterruptedException {
checkGeneration("oracle");
}
public void testPostgres() throws IOException, InterruptedException {
checkGeneration("postgres");
}
*/
// private helpers<SUF>
private void checkGeneration(String database)
throws IOException, InterruptedException {
//checkGeneration(database, true);
checkGeneration(database, "test", false);
}
private void checkGeneration(String database, String stage, boolean shell)
throws IOException, InterruptedException {
if (shell) {
runFromCommandLine(BENERATOR_FILE, database, "test");
} else {
runAsClass(BENERATOR_FILE, database, "test");
}
// connect to database
Map<String, String> dbCfg = IOUtil.readProperties(
"demo/shop/" + database + "/shop." + database + ".properties");
DefaultBeneratorContext context = new DefaultBeneratorContext();
DBSystem db =
new DBSystem("db", dbCfg.get("dbUri"), dbCfg.get("dbDriver"),
dbCfg.get("dbUser"), dbCfg.get("dbPassword"),
context.getDataModel());
// check generation results
Map<String, Object> genCfg =
IOUtil.readProperties("demo/shop/shop." + stage + ".properties",
new DefaultEntryConverter(context));
int expectedProductCount = 6 + (Integer) genCfg.get("product_count");
int expectedCustomerCount = 1 + (Integer) genCfg.get("customer_count");
int expectedUserCount = 3 + expectedCustomerCount;
int ordersPerCustomer = (Integer) genCfg.get("orders_per_customer");
int expectedOrderCount =
(expectedCustomerCount - 1) * ordersPerCustomer + 1;
int itemsPerOrder = (Integer) genCfg.get("items_per_order");
int expectedOrderItemCount =
(expectedOrderCount - 1) * itemsPerOrder + 1;
checkEntities("db_category", new CategoryValidator("db_category"), 28,
db);
checkEntities("db_product", new ProductValidator("db_product"),
expectedProductCount, db);
checkEntities("db_user", new UserValidator("db_user"),
expectedUserCount, db);
checkEntities("db_customer", new CustomerValidator("db_customer"),
expectedCustomerCount, db);
checkEntities("db_order", new OrderValidator("db_order"),
expectedOrderCount, db);
checkEntities("db_order_item", new OrderItemValidator("db_order_item"),
expectedOrderItemCount, db);
}
private void checkEntities(String entityName, Validator<Entity> validator,
int expectedCount, DBSystem db) {
assertEquals("Wrong number of '" + entityName + "' instances.",
expectedCount, db.countEntities(entityName));
DataIterator<Entity> iterator =
db.queryEntities(entityName, null, null).iterator();
DataContainer<Entity> container = new DataContainer<Entity>();
while ((container = iterator.next(container)) != null) {
Entity entity = container.getData();
assertTrue("Invalid entity: " + entity, validator.valid(entity));
}
}
private void runAsClass(String file, String database, String stage)
throws IOException {
System.setProperty("stage", stage);
System.setProperty("database", database);
Benerator.main(new String[] {file});
}
private void runFromCommandLine(String file, String database, String stage)
throws IOException, InterruptedException {
String command =
"benerator -Ddatabase=" + database + " -Dstage=" + stage + " " +
file;
if (logger.isDebugEnabled()) {
logger.debug(command);
}
Process process = Runtime.getRuntime().exec(command);
IOUtil.transfer(process.getInputStream(), System.out);
process.waitFor();
if (logger.isDebugEnabled()) {
logger.debug(String.valueOf(process.exitValue()));
}
}
}
|
150500_9 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.renderer;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.operator.IOObject;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.WebServiceTools;
/**
* The renderer service is the basic provider for all registered renderers. All {@link IOObject}s which want to provide
* a Renderer for visualization and reporting must place an entry in the
* <code>ioobjects.xml</xml> file in order to allow
* for renderer retrieval.
*
* @author Ingo Mierswa, Nils Woehler
*/
public class RendererService {
/** Used in {@link RendererService#class2IconMap}. */
private static class IconData {
private final String iconName;
private final Icon icon;
public IconData(String iconName, Icon icon) {
this.iconName = iconName;
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
return iconName;
}
}
private static final IconData ICON_DEFAULT = new IconData("data.png", SwingTools.createIcon("16/data.png"));
private static Set<String> objectNames = new TreeSet<String>();
/**
* Maps names of IOObjects to lists of renderers that can render this object. These instances are shared!
*/
private static Map<String, List<Renderer>> objectRenderers = new HashMap<String, List<Renderer>>();
/** Maps names of IOObjects to lists of renderer classes that can render this object. */
private static Map<String, Map<String, Class<? extends Renderer>>> rendererNameToRendererClasses = new HashMap<String, Map<String, Class<? extends Renderer>>>();
private static Map<String, Class<? extends IOObject>> objectClasses = new HashMap<String, Class<? extends IOObject>>();
/** Set of names of reportable objects. */
private static Set<String> reportableMap = new HashSet<String>();
private static Map<Class<?>, String> class2NameMap = new HashMap<Class<?>, String>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap = new HashMap<Class<? extends IOObject>, IconData>();
private static boolean isInitialized = false;
public static void init() {
URL url = Tools.getResource("ioobjects.xml");
init(url);
init("ioobjects.xml", url, RendererService.class.getClassLoader());
}
public static void init(URL ioObjectsURL) {
init(ioObjectsURL.getFile(), ioObjectsURL, RendererService.class.getClassLoader());
}
public static void init(String name, InputStream in) {
init(name, in, RendererService.class.getClassLoader());
}
public static void init(String name, URL ioObjectsURL, ClassLoader classLoader) {
InputStream in = null;
try {
if (ioObjectsURL != null) {
in = WebServiceTools.openStreamFromURL(ioObjectsURL);
init(name, in, classLoader);
}
} catch (IOException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_from_plugin_error",
name, e),
e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
public static void init(String rendererFileName, InputStream in, ClassLoader classLoader) {
LogService.getRoot().log(Level.CONFIG, "com.rapidminer.gui.renderer.RendererService.loading_renderers", rendererFileName);
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
Element ioObjectsElement = document.getDocumentElement();
if (ioObjectsElement.getTagName().equals("ioobjects")) {
NodeList ioObjectNodes = ioObjectsElement.getElementsByTagName("ioobject");
for (int i = 0; i < ioObjectNodes.getLength(); i++) {
Node ioObjectNode = ioObjectNodes.item(i);
if (ioObjectNode instanceof Element) {
Element ioObjectElement = (Element) ioObjectNode;
String name = ioObjectElement.getAttribute("name");
String className = ioObjectElement.getAttribute("class");
String reportableString = "true";
if (ioObjectElement.hasAttribute("reportable")) {
reportableString = ioObjectElement.getAttribute("reportable");
}
boolean reportable = Tools.booleanValue(reportableString, true);
String icon = null;
if (ioObjectElement.hasAttribute("icon")) {
icon = ioObjectElement.getAttribute("icon");
}
NodeList rendererNodes = ioObjectElement.getElementsByTagName("renderer");
List<String> renderers = new LinkedList<String>();
for (int k = 0; k < rendererNodes.getLength(); k++) {
Node rendererNode = rendererNodes.item(k);
if (rendererNode instanceof Element) {
Element rendererElement = (Element) rendererNode;
String rendererName = rendererElement.getTextContent();
renderers.add(rendererName);
}
}
registerRenderers(name, className, reportable, icon, renderers, classLoader);
}
}
isInitialized = true;
} else {
LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_tag_error");
}
} catch (IOException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
e),
e);
} catch (javax.xml.parsers.ParserConfigurationException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_error",
e),
e);
} catch (SAXException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
e),
e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
/**
* This method remains for compatibility reasons. But one should use
* {@link #registerRenderers(String, String, boolean, String, List, ClassLoader)} in order to assign an icon to the
* ioobject class.
*/
@Deprecated
public static void registerRenderers(String reportableNames, String className, boolean reportable, List<String> rendererClassNames, ClassLoader classLoader) {
registerRenderers(reportableNames, className, reportable, null, rendererClassNames, classLoader);
}
@SuppressWarnings("unchecked")
public static void registerRenderers(String reportableName, String className, boolean reportable, String iconName, List<String> rendererClassNames, ClassLoader classLoader) {
objectNames.add(reportableName);
try {
Class<? extends IOObject> clazz = (Class<? extends IOObject>) Class.forName(className, true, classLoader);
List<Renderer> renderers = new LinkedList<Renderer>();
Map<String, Class<? extends Renderer>> rendererClassMap = new HashMap<String, Class<? extends Renderer>>();
for (String rendererClassName : rendererClassNames) {
Class<? extends Renderer> rendererClass;
try {
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, true, classLoader);
} catch (Exception e) { // should be unnecessary in most cases, because plugin loader contains core
// classes
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName);
}
Renderer renderer = rendererClass.newInstance();
renderers.add(renderer);
rendererClassMap.put(renderer.getName(), rendererClass);
}
rendererNameToRendererClasses.put(reportableName, rendererClassMap);
objectRenderers.put(reportableName, renderers);
objectClasses.put(reportableName, clazz);
class2NameMap.put(clazz, reportableName);
if (reportable) {
reportableMap.add(reportableName);
}
// try to create icon
if (iconName != null && !iconName.isEmpty()) {
ImageIcon icon = SwingTools.createIcon("16/" + iconName);
if (icon != null)
class2IconMap.put(clazz, new IconData(iconName, icon));
}
} catch (Throwable e) {
//LogService.getRoot().log(Level.WARNING, "Cannot register renderer: " + e, e);
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.registering_renderer_error",
e),
e);
}
}
public static Set<String> getAllRenderableObjectNames() {
return objectNames;
}
public static Set<String> getAllReportableObjectNames() {
Set<String> result = new TreeSet<String>();
for (String name : objectNames) {
if (reportableMap.contains(name)) {
result.add(name);
}
}
return result;
}
/**
* Returns the Reportable name for objects of the given class.
*
* @return the name of the IOObject as specified in the ioobjectsXXX.xml file. Returns null if the object is not registered
*/
public static String getName(Class<?> clazz) {
String result = class2NameMap.get(clazz);
if (result == null) {
Set<Class<?>> candidates = new HashSet<Class<?>>();
//fetch candidates
for (Class<?> candidate : class2NameMap.keySet()) {
if (candidate.isAssignableFrom(clazz)) {
candidates.add(candidate);
}
}
//iterate over candidates and extract candidates for renderables
boolean dominatedClassesFound = true;
while (dominatedClassesFound) {
dominatedClassesFound = false;
List<Class<?>> dominatedList = new LinkedList<Class<?>>();
//iterate over all candidate pairs and add all candidates that are dominated by other candidates into a list
for (Class<?> candidate : candidates) {
for (Class<?> comperable : candidates) {
if (candidate != comperable) {
if (!candidate.isAssignableFrom(comperable)) {
dominatedList.add(candidate);
dominatedClassesFound = true;
}
}
}
}
//if dominates classes have been found set them as new candidates for the next iteration
if (dominatedClassesFound) {
candidates.clear();
candidates.addAll(dominatedList);
}
}
//this loop should break with only one candidate left, BUT: theoretically there can be more than one
//if this is the case, log an error...
if (candidates.size() > 1) {
LogService.getRoot().log(Level.INFO, "com.rapidminer.gui.renderer.RendererService.more_than_one_renderable_candidate_for_the_result_of_classname", clazz.getName());
}
//and show the first candidate found
if (candidates.isEmpty()) {
return null;
} else {
return class2NameMap.get(candidates.toArray()[0]);
}
}
return result;
}
/**
* This returns the highest super class of the report type with the given name.
*/
public static Class<? extends IOObject> getClass(String name) {
return objectClasses.get(name);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object). It is recommended to use {@link #getRenderers(IOObject)} instead.
* */
public static List<Renderer> getRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null)
return renderers;
return new LinkedList<Renderer>();
}
/** Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject. */
public static List<Renderer> getRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderers(reportableName);
}
public static Renderer getRenderer(String reportableName, String rendererName) {
List<Renderer> renderers = getRenderers(reportableName);
for (Renderer renderer : renderers) {
if (renderer.getName().equals(rendererName)) {
return renderer;
}
}
return null;
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been registered.
*/
public static Icon getIcon(Class<? extends IOObject> objectClass) {
return getIconData(objectClass).getIcon();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has been registered.
*/
public static String getIconName(Class<? extends IOObject> objectClass) {
return getIconData(objectClass).getIconName();
}
private static IconData getIconData(Class<? extends IOObject> objectClass) {
if (objectClass == null)
return ICON_DEFAULT;
IconData icon = class2IconMap.get(objectClass);
if (icon == null) {
for (Entry<Class<? extends IOObject>, IconData> renderableClassEntry : class2IconMap.entrySet()) {
if (renderableClassEntry.getKey().isAssignableFrom(objectClass)) {
class2IconMap.put(objectClass, renderableClassEntry.getValue());
return renderableClassEntry.getValue();
}
}
return ICON_DEFAULT;
}
return icon;
}
/**
* Creates a new renderer for the given object.
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Renderer createRenderer(IOObject ioobject, String rendererName) {
String reportableName = getName(ioobject.getClass());
Map<String, Class<? extends Renderer>> rendererClassMap = rendererNameToRendererClasses.get(reportableName);
if (rendererClassMap == null) {
throw new IllegalArgumentException("Illegal reportable name: " + rendererName);
}
Class<? extends Renderer> rendererClass = rendererClassMap.get(rendererName);
if (rendererClass == null) {
throw new IllegalArgumentException("Illegal renderer name: " + rendererName);
}
try {
return rendererClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create renderer: " + e, e);
}
}
/**
* This returns whether the {@link RendererService} has already been initialized at least once.
* This holds true even if only the core objects have been registered.
*/
public static boolean isInitialized() {
return isInitialized;
}
}
| rapidminer/rapidminer-5 | src/com/rapidminer/gui/renderer/RendererService.java | 4,769 | //LogService.getRoot().log(Level.WARNING, "Cannot register renderer: " + e, e); | line_comment | nl | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.renderer;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.operator.IOObject;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.WebServiceTools;
/**
* The renderer service is the basic provider for all registered renderers. All {@link IOObject}s which want to provide
* a Renderer for visualization and reporting must place an entry in the
* <code>ioobjects.xml</xml> file in order to allow
* for renderer retrieval.
*
* @author Ingo Mierswa, Nils Woehler
*/
public class RendererService {
/** Used in {@link RendererService#class2IconMap}. */
private static class IconData {
private final String iconName;
private final Icon icon;
public IconData(String iconName, Icon icon) {
this.iconName = iconName;
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
return iconName;
}
}
private static final IconData ICON_DEFAULT = new IconData("data.png", SwingTools.createIcon("16/data.png"));
private static Set<String> objectNames = new TreeSet<String>();
/**
* Maps names of IOObjects to lists of renderers that can render this object. These instances are shared!
*/
private static Map<String, List<Renderer>> objectRenderers = new HashMap<String, List<Renderer>>();
/** Maps names of IOObjects to lists of renderer classes that can render this object. */
private static Map<String, Map<String, Class<? extends Renderer>>> rendererNameToRendererClasses = new HashMap<String, Map<String, Class<? extends Renderer>>>();
private static Map<String, Class<? extends IOObject>> objectClasses = new HashMap<String, Class<? extends IOObject>>();
/** Set of names of reportable objects. */
private static Set<String> reportableMap = new HashSet<String>();
private static Map<Class<?>, String> class2NameMap = new HashMap<Class<?>, String>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap = new HashMap<Class<? extends IOObject>, IconData>();
private static boolean isInitialized = false;
public static void init() {
URL url = Tools.getResource("ioobjects.xml");
init(url);
init("ioobjects.xml", url, RendererService.class.getClassLoader());
}
public static void init(URL ioObjectsURL) {
init(ioObjectsURL.getFile(), ioObjectsURL, RendererService.class.getClassLoader());
}
public static void init(String name, InputStream in) {
init(name, in, RendererService.class.getClassLoader());
}
public static void init(String name, URL ioObjectsURL, ClassLoader classLoader) {
InputStream in = null;
try {
if (ioObjectsURL != null) {
in = WebServiceTools.openStreamFromURL(ioObjectsURL);
init(name, in, classLoader);
}
} catch (IOException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_from_plugin_error",
name, e),
e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
public static void init(String rendererFileName, InputStream in, ClassLoader classLoader) {
LogService.getRoot().log(Level.CONFIG, "com.rapidminer.gui.renderer.RendererService.loading_renderers", rendererFileName);
try {
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(in);
Element ioObjectsElement = document.getDocumentElement();
if (ioObjectsElement.getTagName().equals("ioobjects")) {
NodeList ioObjectNodes = ioObjectsElement.getElementsByTagName("ioobject");
for (int i = 0; i < ioObjectNodes.getLength(); i++) {
Node ioObjectNode = ioObjectNodes.item(i);
if (ioObjectNode instanceof Element) {
Element ioObjectElement = (Element) ioObjectNode;
String name = ioObjectElement.getAttribute("name");
String className = ioObjectElement.getAttribute("class");
String reportableString = "true";
if (ioObjectElement.hasAttribute("reportable")) {
reportableString = ioObjectElement.getAttribute("reportable");
}
boolean reportable = Tools.booleanValue(reportableString, true);
String icon = null;
if (ioObjectElement.hasAttribute("icon")) {
icon = ioObjectElement.getAttribute("icon");
}
NodeList rendererNodes = ioObjectElement.getElementsByTagName("renderer");
List<String> renderers = new LinkedList<String>();
for (int k = 0; k < rendererNodes.getLength(); k++) {
Node rendererNode = rendererNodes.item(k);
if (rendererNode instanceof Element) {
Element rendererElement = (Element) rendererNode;
String rendererName = rendererElement.getTextContent();
renderers.add(rendererName);
}
}
registerRenderers(name, className, reportable, icon, renderers, classLoader);
}
}
isInitialized = true;
} else {
LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_tag_error");
}
} catch (IOException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
e),
e);
} catch (javax.xml.parsers.ParserConfigurationException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_error",
e),
e);
} catch (SAXException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
e),
e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
/**
* This method remains for compatibility reasons. But one should use
* {@link #registerRenderers(String, String, boolean, String, List, ClassLoader)} in order to assign an icon to the
* ioobject class.
*/
@Deprecated
public static void registerRenderers(String reportableNames, String className, boolean reportable, List<String> rendererClassNames, ClassLoader classLoader) {
registerRenderers(reportableNames, className, reportable, null, rendererClassNames, classLoader);
}
@SuppressWarnings("unchecked")
public static void registerRenderers(String reportableName, String className, boolean reportable, String iconName, List<String> rendererClassNames, ClassLoader classLoader) {
objectNames.add(reportableName);
try {
Class<? extends IOObject> clazz = (Class<? extends IOObject>) Class.forName(className, true, classLoader);
List<Renderer> renderers = new LinkedList<Renderer>();
Map<String, Class<? extends Renderer>> rendererClassMap = new HashMap<String, Class<? extends Renderer>>();
for (String rendererClassName : rendererClassNames) {
Class<? extends Renderer> rendererClass;
try {
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, true, classLoader);
} catch (Exception e) { // should be unnecessary in most cases, because plugin loader contains core
// classes
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName);
}
Renderer renderer = rendererClass.newInstance();
renderers.add(renderer);
rendererClassMap.put(renderer.getName(), rendererClass);
}
rendererNameToRendererClasses.put(reportableName, rendererClassMap);
objectRenderers.put(reportableName, renderers);
objectClasses.put(reportableName, clazz);
class2NameMap.put(clazz, reportableName);
if (reportable) {
reportableMap.add(reportableName);
}
// try to create icon
if (iconName != null && !iconName.isEmpty()) {
ImageIcon icon = SwingTools.createIcon("16/" + iconName);
if (icon != null)
class2IconMap.put(clazz, new IconData(iconName, icon));
}
} catch (Throwable e) {
//LogService.getRoot().log(Level.WARNING, "Cannot<SUF>
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.registering_renderer_error",
e),
e);
}
}
public static Set<String> getAllRenderableObjectNames() {
return objectNames;
}
public static Set<String> getAllReportableObjectNames() {
Set<String> result = new TreeSet<String>();
for (String name : objectNames) {
if (reportableMap.contains(name)) {
result.add(name);
}
}
return result;
}
/**
* Returns the Reportable name for objects of the given class.
*
* @return the name of the IOObject as specified in the ioobjectsXXX.xml file. Returns null if the object is not registered
*/
public static String getName(Class<?> clazz) {
String result = class2NameMap.get(clazz);
if (result == null) {
Set<Class<?>> candidates = new HashSet<Class<?>>();
//fetch candidates
for (Class<?> candidate : class2NameMap.keySet()) {
if (candidate.isAssignableFrom(clazz)) {
candidates.add(candidate);
}
}
//iterate over candidates and extract candidates for renderables
boolean dominatedClassesFound = true;
while (dominatedClassesFound) {
dominatedClassesFound = false;
List<Class<?>> dominatedList = new LinkedList<Class<?>>();
//iterate over all candidate pairs and add all candidates that are dominated by other candidates into a list
for (Class<?> candidate : candidates) {
for (Class<?> comperable : candidates) {
if (candidate != comperable) {
if (!candidate.isAssignableFrom(comperable)) {
dominatedList.add(candidate);
dominatedClassesFound = true;
}
}
}
}
//if dominates classes have been found set them as new candidates for the next iteration
if (dominatedClassesFound) {
candidates.clear();
candidates.addAll(dominatedList);
}
}
//this loop should break with only one candidate left, BUT: theoretically there can be more than one
//if this is the case, log an error...
if (candidates.size() > 1) {
LogService.getRoot().log(Level.INFO, "com.rapidminer.gui.renderer.RendererService.more_than_one_renderable_candidate_for_the_result_of_classname", clazz.getName());
}
//and show the first candidate found
if (candidates.isEmpty()) {
return null;
} else {
return class2NameMap.get(candidates.toArray()[0]);
}
}
return result;
}
/**
* This returns the highest super class of the report type with the given name.
*/
public static Class<? extends IOObject> getClass(String name) {
return objectClasses.get(name);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object). It is recommended to use {@link #getRenderers(IOObject)} instead.
* */
public static List<Renderer> getRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null)
return renderers;
return new LinkedList<Renderer>();
}
/** Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject. */
public static List<Renderer> getRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderers(reportableName);
}
public static Renderer getRenderer(String reportableName, String rendererName) {
List<Renderer> renderers = getRenderers(reportableName);
for (Renderer renderer : renderers) {
if (renderer.getName().equals(rendererName)) {
return renderer;
}
}
return null;
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been registered.
*/
public static Icon getIcon(Class<? extends IOObject> objectClass) {
return getIconData(objectClass).getIcon();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has been registered.
*/
public static String getIconName(Class<? extends IOObject> objectClass) {
return getIconData(objectClass).getIconName();
}
private static IconData getIconData(Class<? extends IOObject> objectClass) {
if (objectClass == null)
return ICON_DEFAULT;
IconData icon = class2IconMap.get(objectClass);
if (icon == null) {
for (Entry<Class<? extends IOObject>, IconData> renderableClassEntry : class2IconMap.entrySet()) {
if (renderableClassEntry.getKey().isAssignableFrom(objectClass)) {
class2IconMap.put(objectClass, renderableClassEntry.getValue());
return renderableClassEntry.getValue();
}
}
return ICON_DEFAULT;
}
return icon;
}
/**
* Creates a new renderer for the given object.
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Renderer createRenderer(IOObject ioobject, String rendererName) {
String reportableName = getName(ioobject.getClass());
Map<String, Class<? extends Renderer>> rendererClassMap = rendererNameToRendererClasses.get(reportableName);
if (rendererClassMap == null) {
throw new IllegalArgumentException("Illegal reportable name: " + rendererName);
}
Class<? extends Renderer> rendererClass = rendererClassMap.get(rendererName);
if (rendererClass == null) {
throw new IllegalArgumentException("Illegal renderer name: " + rendererName);
}
try {
return rendererClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create renderer: " + e, e);
}
}
/**
* This returns whether the {@link RendererService} has already been initialized at least once.
* This holds true even if only the core objects have been registered.
*/
public static boolean isInitialized() {
return isInitialized;
}
}
|
150495_10 | /**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.renderer;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.rapidminer.gui.MainFrame;
import com.rapidminer.gui.new_plotter.integration.ExpertDataTableRenderer;
import com.rapidminer.gui.renderer.data.ExampleSetPlotRenderer;
import com.rapidminer.gui.renderer.math.NumericalMatrixPlotRenderer;
import com.rapidminer.gui.renderer.models.KernelModelPlotRenderer;
import com.rapidminer.gui.renderer.weights.AttributeWeightsPlotRenderer;
import com.rapidminer.gui.tools.IconSize;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.operator.IOObject;
import com.rapidminer.tools.DominatingClassFinder;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.WebServiceTools;
import com.rapidminer.tools.XMLParserException;
import com.rapidminer.tools.plugin.Plugin;
/**
* The renderer service is the basic provider for all registered renderers. All {@link IOObject}s
* which want to provide a Renderer for visualization and reporting must place an entry in the
* <code>ioobjects.xml</xml> file in order to allow
* for renderer retrieval.
*
* @author Ingo Mierswa, Nils Woehler
*/
public class RendererService {
/** Used in the icon maps */
private static class IconData {
private final String iconName;
private final Icon icon;
public IconData(String iconName, Icon icon) {
this.iconName = iconName;
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
return iconName;
}
}
private static final String CORE_IOOBJECTS_XML = "ioobjects.xml";
/**
* Contains all simple renderers that have been migrated to the new HTML5 Visualizations. Can be removed once the "show legacy simple charts" setting is removed.
*/
private static final Class<?>[] MIGRATED_SIMPLE_RENDERER_CLASSES = new Class<?>[] {ExampleSetPlotRenderer.class, AttributeWeightsPlotRenderer.class,
NumericalMatrixPlotRenderer.class, KernelModelPlotRenderer.class};
private static final IconData ICON_DEFAULT_16 = new IconData("data.png", SwingTools.createIcon("16/data.png"));
private static final IconData ICON_DEFAULT_24 = new IconData("data.png", SwingTools.createIcon("24/data.png"));
private static final IconData ICON_DEFAULT_48 = new IconData("data.png", SwingTools.createIcon("48/data.png"));
private static Set<String> objectNames = new TreeSet<>();
/**
* Maps names of IOObjects to lists of renderers that can render this object. These instances
* are shared!
*/
private static Map<String, List<Renderer>> objectRenderers = new HashMap<>();
/** Maps names of IOObjects to lists of renderer classes that can render this object. */
private static Map<String, Map<String, Class<? extends Renderer>>> rendererNameToRendererClasses = new HashMap<>();
private static Map<String, Class<? extends IOObject>> objectClassesByReportableName = new HashMap<>();
private static Map<String, Class<? extends IOObject>> objectClassesByClassName = new HashMap<>();
/** Set of names of reportable objects. */
private static Set<String> reportableMap = new HashSet<>();
private static Map<Class<?>, String> class2NameMap = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap16x16 = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap24x24 = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap48x48 = new HashMap<>();
private static boolean isInitialized = false;
public static void init() {
init(CORE_IOOBJECTS_XML, Tools.getResource(CORE_IOOBJECTS_XML), RendererService.class.getClassLoader());
}
public static void init(String name, URL ioObjectsURL, ClassLoader classLoader) {
InputStream in = null;
try {
if (ioObjectsURL != null) {
in = WebServiceTools.openStreamFromURL(ioObjectsURL);
init(name, in, classLoader);
}
} catch (IOException e) {
LogService
.getRoot()
.log(Level.WARNING,
I18N.getMessage(
LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_from_plugin_error",
name, e), e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
public static void init(String rendererFileName, InputStream in, ClassLoader classLoader) {
LogService.getRoot().log(Level.CONFIG, "com.rapidminer.gui.renderer.RendererService.loading_renderers",
rendererFileName);
try {
Document document = XMLTools.createDocumentBuilder().parse(in);
Element ioObjectsElement = document.getDocumentElement();
if (ioObjectsElement.getTagName().equals("ioobjects")) {
NodeList ioObjectNodes = ioObjectsElement.getElementsByTagName("ioobject");
for (int i = 0; i < ioObjectNodes.getLength(); i++) {
Node ioObjectNode = ioObjectNodes.item(i);
if (ioObjectNode instanceof Element) {
Element ioObjectElement = (Element) ioObjectNode;
String name = ioObjectElement.getAttribute("name");
String className = ioObjectElement.getAttribute("class");
String reportableString = "true";
if (ioObjectElement.hasAttribute("reportable")) {
reportableString = ioObjectElement.getAttribute("reportable");
}
boolean reportable = Tools.booleanValue(reportableString, true);
String icon = null;
if (ioObjectElement.hasAttribute("icon")) {
icon = ioObjectElement.getAttribute("icon");
}
NodeList rendererNodes = ioObjectElement.getElementsByTagName("renderer");
List<String> renderers = new LinkedList<>();
for (int k = 0; k < rendererNodes.getLength(); k++) {
Node rendererNode = rendererNodes.item(k);
if (rendererNode instanceof Element) {
Element rendererElement = (Element) rendererNode;
String rendererName = rendererElement.getTextContent();
renderers.add(rendererName);
}
}
registerRenderers(name, className, reportable, icon, renderers, classLoader);
}
}
isInitialized = true;
} else {
LogService.getRoot().log(Level.WARNING,
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_tag_error");
}
} catch (XMLParserException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_error",
rendererFileName), e);
} catch (IOException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
rendererFileName), e);
} catch (SAXException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
rendererFileName), e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
/**
* This method remains for compatibility reasons. But one should use
* {@link #registerRenderers(String, String, boolean, String, List, ClassLoader)} in order to
* assign an icon to the ioobject class.
*/
@Deprecated
public static void registerRenderers(String reportableNames, String className, boolean reportable,
List<String> rendererClassNames, ClassLoader classLoader) {
registerRenderers(reportableNames, className, reportable, null, rendererClassNames, classLoader);
}
@SuppressWarnings("unchecked")
public static void registerRenderers(String reportableName, String className, boolean reportable, String iconName,
List<String> rendererClassNames, ClassLoader classLoader) {
objectNames.add(reportableName);
try {
Class<? extends IOObject> clazz = (Class<? extends IOObject>) Class.forName(className, true, classLoader);
List<Renderer> renderers = new LinkedList<>();
Map<String, Class<? extends Renderer>> rendererClassMap = new HashMap<>();
for (String rendererClassName : rendererClassNames) {
Class<? extends Renderer> rendererClass;
try {
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, true, classLoader);
} catch (Exception e) {
// let's try with the plugin classloader (some Core renderers are now in bundled extensions)
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, false, Plugin.getMajorClassLoader());
}
if (rendererClass != null) {
Renderer renderer = rendererClass.newInstance();
renderers.add(renderer);
rendererClassMap.put(renderer.getName(), rendererClass);
}
}
rendererNameToRendererClasses.put(reportableName, rendererClassMap);
objectRenderers.put(reportableName, renderers);
objectClassesByReportableName.put(reportableName, clazz);
objectClassesByClassName.put(className, clazz);
class2NameMap.put(clazz, reportableName);
if (reportable) {
reportableMap.add(reportableName);
}
// try to create icons
if (iconName != null && !iconName.isEmpty()) {
// 16x16
ImageIcon icon = SwingTools.createIcon("16/" + iconName);
if (icon != null) {
class2IconMap16x16.put(clazz, new IconData(iconName, icon));
}
// 24x24
icon = SwingTools.createIcon("24/" + iconName);
if (icon != null) {
class2IconMap24x24.put(clazz, new IconData(iconName, icon));
}
// 48x48
icon = SwingTools.createIcon("48/" + iconName);
if (icon != null) {
class2IconMap48x48.put(clazz, new IconData(iconName, icon));
}
}
} catch (Throwable e) {
// LogService.getRoot().log(Level.WARNING, "Cannot register renderer: " + e, e);
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.registering_renderer_error", e), e);
}
}
public static Set<String> getAllRenderableObjectNames() {
return objectNames;
}
public static Set<String> getAllReportableObjectNames() {
Set<String> result = new TreeSet<>();
for (String name : objectNames) {
if (reportableMap.contains(name)) {
result.add(name);
}
}
return result;
}
/**
* Returns the Reportable name for objects of the given class.
*
* @return the name of the IOObject as specified in the ioobjectsXXX.xml file. Returns null if
* the object is not registered
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String getName(Class<?> clazz) {
String result = class2NameMap.get(clazz);
if (result == null) {
Class<?> parentClass = new DominatingClassFinder().findNextDominatingClass(clazz, class2NameMap.keySet());
if (parentClass == null) {
return null;
} else {
return class2NameMap.get(parentClass);
}
}
return result;
}
/**
* This returns the highest super class of the report type with the given reportable name.
*/
public static Class<? extends IOObject> getClass(String reportableName) {
return objectClassesByReportableName.get(reportableName);
}
/**
* This returns the highest super class of the report type with the given class name.
*/
public static Class<? extends IOObject> getClassByClassName(String className) {
return objectClassesByClassName.get(className);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object). It is recommended to use {@link #getRenderers(IOObject)} instead.
*
* @deprecated since 9.2.0 use {@link #getRenderersExcludingLegacyRenderers(String)}
*/
@Deprecated
public static List<Renderer> getRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null) {
return renderers;
}
return new LinkedList<>();
}
/**
* Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject.
* @deprecated since 9.2.0 use {@link #getRenderersExcludingLegacyRenderers(IOObject)} instead
*/
@Deprecated
public static List<Renderer> getRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderers(reportableName);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object), WITHOUT legacy renderers. This
*
* @since 9.2.0
*/
public static List<Renderer> getRenderersExcludingLegacyRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null) {
boolean showLegacySimpleCharts = Boolean.parseBoolean(ParameterService.getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_SHOW_LEGACY_SIMPLE_CHARTS));
boolean showLegacyAdvancedCharts = Boolean.parseBoolean(ParameterService.getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_SHOW_LEGACY_ADVANCED_CHARTS));
// filter old charts and old advanced charts unless user has activated them in settings
return renderers.stream().filter(renderer -> {
if (isMigratedSimpleRendererClass(renderer.getClass())) {
return showLegacySimpleCharts;
} else if (renderer.getClass().isAssignableFrom(ExpertDataTableRenderer.class)) {
return showLegacyAdvancedCharts;
} else {
return true;
}
}).collect(Collectors.toList());
}
return new LinkedList<>();
}
/**
* Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject, WITHOUT legacy renderers.
*
* @since 9.2.0
*/
public static List<Renderer> getRenderersExcludingLegacyRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderersExcludingLegacyRenderers(reportableName);
}
/**
* Returns the given renderer, will also return legay renderers.
*/
public static Renderer getRenderer(String reportableName, String rendererName) {
List<Renderer> renderers = getRenderers(reportableName);
for (Renderer renderer : renderers) {
if (renderer.getName().equals(rendererName)) {
return renderer;
}
}
return null;
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been
* registered. Returns size {@link IconSize#SMALL}.
*/
public static Icon getIcon(Class<? extends IOObject> objectClass) {
return getIconData(objectClass, IconSize.SMALL).getIcon();
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been
* registered. Returns the specified {@link IconSize}.
*
* @since 8.1
*/
public static Icon getIcon(Class<? extends IOObject> objectClass, IconSize iconSize) {
return getIconData(objectClass, iconSize).getIcon();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has
* been registered. Returns size {@link IconSize#SMALL}.
*/
public static String getIconName(Class<? extends IOObject> objectClass) {
return getIconData(objectClass, IconSize.SMALL).getIconName();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has
* been registered. Returns the specified {@link IconSize}.
*
* @since 8.1
*/
public static String getIconName(Class<? extends IOObject> objectClass, IconSize iconSize) {
return getIconData(objectClass, iconSize).getIconName();
}
private static IconData getIconData(Class<? extends IOObject> objectClass, IconSize iconSize) {
IconData icon = null;
Map<Class<? extends IOObject>, IconData> iconMap;
IconData defaultIcon;
switch (iconSize) {
case HUGE:
iconMap = class2IconMap48x48;
defaultIcon = ICON_DEFAULT_48;
break;
case LARGE:
iconMap = class2IconMap24x24;
defaultIcon = ICON_DEFAULT_24;
break;
case SMALL:
default:
iconMap = class2IconMap16x16;
defaultIcon = ICON_DEFAULT_16;
break;
}
if (objectClass != null) {
icon = iconMap.get(objectClass);
if (icon == null) {
icon = updateIconData(objectClass, iconMap);
}
}
return icon != null ? icon : defaultIcon;
}
/**
* Creates a new renderer for the given object.
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Renderer createRenderer(IOObject ioobject, String rendererName) {
String reportableName = getName(ioobject.getClass());
Map<String, Class<? extends Renderer>> rendererClassMap = rendererNameToRendererClasses.get(reportableName);
if (rendererClassMap == null) {
throw new IllegalArgumentException("Illegal reportable name: " + rendererName);
}
Class<? extends Renderer> rendererClass = rendererClassMap.get(rendererName);
if (rendererClass == null) {
throw new IllegalArgumentException("Illegal renderer name: " + rendererName);
}
try {
return rendererClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create renderer: " + e, e);
}
}
/**
* This returns whether the {@link RendererService} has already been initialized at least once.
* This holds true even if only the core objects have been registered.
*/
public static boolean isInitialized() {
return isInitialized;
}
/**
* Try to find the icon of a superclass and set it as the new type icon.
*
* @return the icon or {@code null}
*/
private static IconData updateIconData(Class<? extends IOObject> objectClass, Map<Class<? extends IOObject>, IconData> class2IconMap) {
IconData icon = null;
Map<Class<? extends IOObject>, IconData> clonedMap;
synchronized (class2IconMap) {
clonedMap = new HashMap<>(class2IconMap);
}
for (Entry<Class<? extends IOObject>, IconData> renderableClassEntry : clonedMap.entrySet()) {
if (renderableClassEntry.getKey().isAssignableFrom(objectClass)) {
class2IconMap.put(objectClass, renderableClassEntry.getValue());
icon = renderableClassEntry.getValue();
}
}
return icon;
}
/**
* Checks if the given simple renderer class was already migrated to the new HTML5 visualizations.
*
* @param rendererClass
* the renderer class in question, never {@code null}
* @return {@code true} if the given renderer was migrated; {@code false} otherwise
*/
private static boolean isMigratedSimpleRendererClass(Class<?> rendererClass) {
for (Class<?> migratedClass : MIGRATED_SIMPLE_RENDERER_CLASSES) {
if (rendererClass.isAssignableFrom(migratedClass)) {
return true;
}
}
return false;
}
}
| rapidminer/rapidminer-studio | src/main/java/com/rapidminer/gui/renderer/RendererService.java | 6,588 | // LogService.getRoot().log(Level.WARNING, "Cannot register renderer: " + e, e);
| line_comment | nl | /**
* Copyright (C) 2001-2020 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.renderer;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.rapidminer.gui.MainFrame;
import com.rapidminer.gui.new_plotter.integration.ExpertDataTableRenderer;
import com.rapidminer.gui.renderer.data.ExampleSetPlotRenderer;
import com.rapidminer.gui.renderer.math.NumericalMatrixPlotRenderer;
import com.rapidminer.gui.renderer.models.KernelModelPlotRenderer;
import com.rapidminer.gui.renderer.weights.AttributeWeightsPlotRenderer;
import com.rapidminer.gui.tools.IconSize;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.operator.IOObject;
import com.rapidminer.tools.DominatingClassFinder;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.Tools;
import com.rapidminer.tools.WebServiceTools;
import com.rapidminer.tools.XMLParserException;
import com.rapidminer.tools.plugin.Plugin;
/**
* The renderer service is the basic provider for all registered renderers. All {@link IOObject}s
* which want to provide a Renderer for visualization and reporting must place an entry in the
* <code>ioobjects.xml</xml> file in order to allow
* for renderer retrieval.
*
* @author Ingo Mierswa, Nils Woehler
*/
public class RendererService {
/** Used in the icon maps */
private static class IconData {
private final String iconName;
private final Icon icon;
public IconData(String iconName, Icon icon) {
this.iconName = iconName;
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
return iconName;
}
}
private static final String CORE_IOOBJECTS_XML = "ioobjects.xml";
/**
* Contains all simple renderers that have been migrated to the new HTML5 Visualizations. Can be removed once the "show legacy simple charts" setting is removed.
*/
private static final Class<?>[] MIGRATED_SIMPLE_RENDERER_CLASSES = new Class<?>[] {ExampleSetPlotRenderer.class, AttributeWeightsPlotRenderer.class,
NumericalMatrixPlotRenderer.class, KernelModelPlotRenderer.class};
private static final IconData ICON_DEFAULT_16 = new IconData("data.png", SwingTools.createIcon("16/data.png"));
private static final IconData ICON_DEFAULT_24 = new IconData("data.png", SwingTools.createIcon("24/data.png"));
private static final IconData ICON_DEFAULT_48 = new IconData("data.png", SwingTools.createIcon("48/data.png"));
private static Set<String> objectNames = new TreeSet<>();
/**
* Maps names of IOObjects to lists of renderers that can render this object. These instances
* are shared!
*/
private static Map<String, List<Renderer>> objectRenderers = new HashMap<>();
/** Maps names of IOObjects to lists of renderer classes that can render this object. */
private static Map<String, Map<String, Class<? extends Renderer>>> rendererNameToRendererClasses = new HashMap<>();
private static Map<String, Class<? extends IOObject>> objectClassesByReportableName = new HashMap<>();
private static Map<String, Class<? extends IOObject>> objectClassesByClassName = new HashMap<>();
/** Set of names of reportable objects. */
private static Set<String> reportableMap = new HashSet<>();
private static Map<Class<?>, String> class2NameMap = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap16x16 = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap24x24 = new HashMap<>();
private static Map<Class<? extends IOObject>, IconData> class2IconMap48x48 = new HashMap<>();
private static boolean isInitialized = false;
public static void init() {
init(CORE_IOOBJECTS_XML, Tools.getResource(CORE_IOOBJECTS_XML), RendererService.class.getClassLoader());
}
public static void init(String name, URL ioObjectsURL, ClassLoader classLoader) {
InputStream in = null;
try {
if (ioObjectsURL != null) {
in = WebServiceTools.openStreamFromURL(ioObjectsURL);
init(name, in, classLoader);
}
} catch (IOException e) {
LogService
.getRoot()
.log(Level.WARNING,
I18N.getMessage(
LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_from_plugin_error",
name, e), e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
public static void init(String rendererFileName, InputStream in, ClassLoader classLoader) {
LogService.getRoot().log(Level.CONFIG, "com.rapidminer.gui.renderer.RendererService.loading_renderers",
rendererFileName);
try {
Document document = XMLTools.createDocumentBuilder().parse(in);
Element ioObjectsElement = document.getDocumentElement();
if (ioObjectsElement.getTagName().equals("ioobjects")) {
NodeList ioObjectNodes = ioObjectsElement.getElementsByTagName("ioobject");
for (int i = 0; i < ioObjectNodes.getLength(); i++) {
Node ioObjectNode = ioObjectNodes.item(i);
if (ioObjectNode instanceof Element) {
Element ioObjectElement = (Element) ioObjectNode;
String name = ioObjectElement.getAttribute("name");
String className = ioObjectElement.getAttribute("class");
String reportableString = "true";
if (ioObjectElement.hasAttribute("reportable")) {
reportableString = ioObjectElement.getAttribute("reportable");
}
boolean reportable = Tools.booleanValue(reportableString, true);
String icon = null;
if (ioObjectElement.hasAttribute("icon")) {
icon = ioObjectElement.getAttribute("icon");
}
NodeList rendererNodes = ioObjectElement.getElementsByTagName("renderer");
List<String> renderers = new LinkedList<>();
for (int k = 0; k < rendererNodes.getLength(); k++) {
Node rendererNode = rendererNodes.item(k);
if (rendererNode instanceof Element) {
Element rendererElement = (Element) rendererNode;
String rendererName = rendererElement.getTextContent();
renderers.add(rendererName);
}
}
registerRenderers(name, className, reportable, icon, renderers, classLoader);
}
}
isInitialized = true;
} else {
LogService.getRoot().log(Level.WARNING,
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_tag_error");
}
} catch (XMLParserException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_error",
rendererFileName), e);
} catch (IOException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
rendererFileName), e);
} catch (SAXException e) {
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.initializing_io_object_description_parsing_error",
rendererFileName), e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
}
}
/**
* This method remains for compatibility reasons. But one should use
* {@link #registerRenderers(String, String, boolean, String, List, ClassLoader)} in order to
* assign an icon to the ioobject class.
*/
@Deprecated
public static void registerRenderers(String reportableNames, String className, boolean reportable,
List<String> rendererClassNames, ClassLoader classLoader) {
registerRenderers(reportableNames, className, reportable, null, rendererClassNames, classLoader);
}
@SuppressWarnings("unchecked")
public static void registerRenderers(String reportableName, String className, boolean reportable, String iconName,
List<String> rendererClassNames, ClassLoader classLoader) {
objectNames.add(reportableName);
try {
Class<? extends IOObject> clazz = (Class<? extends IOObject>) Class.forName(className, true, classLoader);
List<Renderer> renderers = new LinkedList<>();
Map<String, Class<? extends Renderer>> rendererClassMap = new HashMap<>();
for (String rendererClassName : rendererClassNames) {
Class<? extends Renderer> rendererClass;
try {
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, true, classLoader);
} catch (Exception e) {
// let's try with the plugin classloader (some Core renderers are now in bundled extensions)
rendererClass = (Class<? extends Renderer>) Class.forName(rendererClassName, false, Plugin.getMajorClassLoader());
}
if (rendererClass != null) {
Renderer renderer = rendererClass.newInstance();
renderers.add(renderer);
rendererClassMap.put(renderer.getName(), rendererClass);
}
}
rendererNameToRendererClasses.put(reportableName, rendererClassMap);
objectRenderers.put(reportableName, renderers);
objectClassesByReportableName.put(reportableName, clazz);
objectClassesByClassName.put(className, clazz);
class2NameMap.put(clazz, reportableName);
if (reportable) {
reportableMap.add(reportableName);
}
// try to create icons
if (iconName != null && !iconName.isEmpty()) {
// 16x16
ImageIcon icon = SwingTools.createIcon("16/" + iconName);
if (icon != null) {
class2IconMap16x16.put(clazz, new IconData(iconName, icon));
}
// 24x24
icon = SwingTools.createIcon("24/" + iconName);
if (icon != null) {
class2IconMap24x24.put(clazz, new IconData(iconName, icon));
}
// 48x48
icon = SwingTools.createIcon("48/" + iconName);
if (icon != null) {
class2IconMap48x48.put(clazz, new IconData(iconName, icon));
}
}
} catch (Throwable e) {
// LogService.getRoot().log(Level.WARNING, "Cannot<SUF>
LogService.getRoot().log(
Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapidminer.gui.renderer.RendererService.registering_renderer_error", e), e);
}
}
public static Set<String> getAllRenderableObjectNames() {
return objectNames;
}
public static Set<String> getAllReportableObjectNames() {
Set<String> result = new TreeSet<>();
for (String name : objectNames) {
if (reportableMap.contains(name)) {
result.add(name);
}
}
return result;
}
/**
* Returns the Reportable name for objects of the given class.
*
* @return the name of the IOObject as specified in the ioobjectsXXX.xml file. Returns null if
* the object is not registered
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String getName(Class<?> clazz) {
String result = class2NameMap.get(clazz);
if (result == null) {
Class<?> parentClass = new DominatingClassFinder().findNextDominatingClass(clazz, class2NameMap.keySet());
if (parentClass == null) {
return null;
} else {
return class2NameMap.get(parentClass);
}
}
return result;
}
/**
* This returns the highest super class of the report type with the given reportable name.
*/
public static Class<? extends IOObject> getClass(String reportableName) {
return objectClassesByReportableName.get(reportableName);
}
/**
* This returns the highest super class of the report type with the given class name.
*/
public static Class<? extends IOObject> getClassByClassName(String className) {
return objectClassesByClassName.get(className);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object). It is recommended to use {@link #getRenderers(IOObject)} instead.
*
* @deprecated since 9.2.0 use {@link #getRenderersExcludingLegacyRenderers(String)}
*/
@Deprecated
public static List<Renderer> getRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null) {
return renderers;
}
return new LinkedList<>();
}
/**
* Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject.
* @deprecated since 9.2.0 use {@link #getRenderersExcludingLegacyRenderers(IOObject)} instead
*/
@Deprecated
public static List<Renderer> getRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderers(reportableName);
}
/**
* Returns a list of renderers defined for this IOObject name (as returned by {@link #getName(Class)} for the
* respective object), WITHOUT legacy renderers. This
*
* @since 9.2.0
*/
public static List<Renderer> getRenderersExcludingLegacyRenderers(String reportableName) {
List<Renderer> renderers = objectRenderers.get(reportableName);
if (renderers != null) {
boolean showLegacySimpleCharts = Boolean.parseBoolean(ParameterService.getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_SHOW_LEGACY_SIMPLE_CHARTS));
boolean showLegacyAdvancedCharts = Boolean.parseBoolean(ParameterService.getParameterValue(MainFrame.PROPERTY_RAPIDMINER_GUI_PLOTTER_SHOW_LEGACY_ADVANCED_CHARTS));
// filter old charts and old advanced charts unless user has activated them in settings
return renderers.stream().filter(renderer -> {
if (isMigratedSimpleRendererClass(renderer.getClass())) {
return showLegacySimpleCharts;
} else if (renderer.getClass().isAssignableFrom(ExpertDataTableRenderer.class)) {
return showLegacyAdvancedCharts;
} else {
return true;
}
}).collect(Collectors.toList());
}
return new LinkedList<>();
}
/**
* Returns a list of shared (i.e. not thread-safe!) renderers defined for this IOObject, WITHOUT legacy renderers.
*
* @since 9.2.0
*/
public static List<Renderer> getRenderersExcludingLegacyRenderers(IOObject ioo) {
String reportableName = RendererService.getName(ioo.getClass());
return getRenderersExcludingLegacyRenderers(reportableName);
}
/**
* Returns the given renderer, will also return legay renderers.
*/
public static Renderer getRenderer(String reportableName, String rendererName) {
List<Renderer> renderers = getRenderers(reportableName);
for (Renderer renderer : renderers) {
if (renderer.getName().equals(rendererName)) {
return renderer;
}
}
return null;
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been
* registered. Returns size {@link IconSize#SMALL}.
*/
public static Icon getIcon(Class<? extends IOObject> objectClass) {
return getIconData(objectClass, IconSize.SMALL).getIcon();
}
/**
* This returns the icon registered for the given class or a default icon, if nothing has been
* registered. Returns the specified {@link IconSize}.
*
* @since 8.1
*/
public static Icon getIcon(Class<? extends IOObject> objectClass, IconSize iconSize) {
return getIconData(objectClass, iconSize).getIcon();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has
* been registered. Returns size {@link IconSize#SMALL}.
*/
public static String getIconName(Class<? extends IOObject> objectClass) {
return getIconData(objectClass, IconSize.SMALL).getIconName();
}
/**
* This returns the icon name registered for the given class or a default icon, if nothing has
* been registered. Returns the specified {@link IconSize}.
*
* @since 8.1
*/
public static String getIconName(Class<? extends IOObject> objectClass, IconSize iconSize) {
return getIconData(objectClass, iconSize).getIconName();
}
private static IconData getIconData(Class<? extends IOObject> objectClass, IconSize iconSize) {
IconData icon = null;
Map<Class<? extends IOObject>, IconData> iconMap;
IconData defaultIcon;
switch (iconSize) {
case HUGE:
iconMap = class2IconMap48x48;
defaultIcon = ICON_DEFAULT_48;
break;
case LARGE:
iconMap = class2IconMap24x24;
defaultIcon = ICON_DEFAULT_24;
break;
case SMALL:
default:
iconMap = class2IconMap16x16;
defaultIcon = ICON_DEFAULT_16;
break;
}
if (objectClass != null) {
icon = iconMap.get(objectClass);
if (icon == null) {
icon = updateIconData(objectClass, iconMap);
}
}
return icon != null ? icon : defaultIcon;
}
/**
* Creates a new renderer for the given object.
*
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Renderer createRenderer(IOObject ioobject, String rendererName) {
String reportableName = getName(ioobject.getClass());
Map<String, Class<? extends Renderer>> rendererClassMap = rendererNameToRendererClasses.get(reportableName);
if (rendererClassMap == null) {
throw new IllegalArgumentException("Illegal reportable name: " + rendererName);
}
Class<? extends Renderer> rendererClass = rendererClassMap.get(rendererName);
if (rendererClass == null) {
throw new IllegalArgumentException("Illegal renderer name: " + rendererName);
}
try {
return rendererClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("Failed to create renderer: " + e, e);
}
}
/**
* This returns whether the {@link RendererService} has already been initialized at least once.
* This holds true even if only the core objects have been registered.
*/
public static boolean isInitialized() {
return isInitialized;
}
/**
* Try to find the icon of a superclass and set it as the new type icon.
*
* @return the icon or {@code null}
*/
private static IconData updateIconData(Class<? extends IOObject> objectClass, Map<Class<? extends IOObject>, IconData> class2IconMap) {
IconData icon = null;
Map<Class<? extends IOObject>, IconData> clonedMap;
synchronized (class2IconMap) {
clonedMap = new HashMap<>(class2IconMap);
}
for (Entry<Class<? extends IOObject>, IconData> renderableClassEntry : clonedMap.entrySet()) {
if (renderableClassEntry.getKey().isAssignableFrom(objectClass)) {
class2IconMap.put(objectClass, renderableClassEntry.getValue());
icon = renderableClassEntry.getValue();
}
}
return icon;
}
/**
* Checks if the given simple renderer class was already migrated to the new HTML5 visualizations.
*
* @param rendererClass
* the renderer class in question, never {@code null}
* @return {@code true} if the given renderer was migrated; {@code false} otherwise
*/
private static boolean isMigratedSimpleRendererClass(Class<?> rendererClass) {
for (Class<?> migratedClass : MIGRATED_SIMPLE_RENDERER_CLASSES) {
if (rendererClass.isAssignableFrom(migratedClass)) {
return true;
}
}
return false;
}
}
|
66301_6 | /*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| 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. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendarview.swing;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.swing.scaling.IRowScale;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/** Komponente, welche eine beliebige anzahl von Slot-komponenten zusammenfasst.
* die slots koennen zur laufzeit hinzugefuegt oder auch dynamisch bei bedarf
*erzeugt werden. sie werden horizontal nebeneinander angeordnet.
*/
class LargeDaySlot extends AbstractDaySlot
{
private static final long serialVersionUID = 1L;
public static Color THICK_LINE_COLOR = Color.black;
public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa);
public static Color WORKTIME_BACKGROUND = Color.white;
public static Color NON_WORKTIME_BACKGROUND = new Color(0xcc, 0xcc, 0xcc);
private final List<Slot> slots= new ArrayList<>();
private int slotxsize;
private int selectionStart = -1;
private int selectionEnd = -1;
private int oldSelectionStart = -1;
private int oldSelectionEnd = -1;
BoxLayout boxLayout1 = new BoxLayout(this, BoxLayout.X_AXIS);
int right_gap = 8;
int left_gap = 5;
int slot_space = 3;
JComponent header;
IRowScale rowScale;
private final BlockListener blockListener = new BlockListener();
/**
es muss auch noch setTimeIntervall() aufgerufen werden, um die initialisierung
fertig zu stellen (wie beim konstruktor von Slot).
slotxsize ist die breite der einzelnen slots.
"date" legt das Datum fest, fuer welches das Slot anzeigt (Uhrzeit bleibt unberuecksichtigt)
*/
public LargeDaySlot(
int slotxsize
,IRowScale rowScale
,JComponent header) {
this.slotxsize= slotxsize;
this.rowScale = rowScale;
this.header = header;
setLayout(boxLayout1);
this.add(Box.createHorizontalStrut(left_gap));
addSlot();
setBackground(getBackground());
setAlignmentX(0);
setAlignmentY(TOP_ALIGNMENT);
this.setBackground(Color.white);
}
public boolean isBorderVisible() {
return true;
// return getBackground() != Color.white;
}
public int getSlotCount()
{
return slots.size();
}
public boolean isSelected()
{
return selectionStart >=0 ;
}
public void setVisible(boolean b) {
super.setVisible(b);
header.setVisible(b);
}
public JComponent getHeader() {
return header;
}
public int calcSlot(int x) {
int slot = ((x - left_gap) / (slotxsize + slot_space));
//System.out.println ( x + " slot " + slot);
if (slot<0)
slot = 0;
if (slot >= slots.size())
slot = slots.size() -1;
return slot;
}
public Collection<Block> getBlocks() {
ArrayList<Block> list = new ArrayList<>();
for (int i=0;i<slots.size();i++)
list.addAll(slots.get(i).getBlocks());
return list;
}
public void select(int start,int end) {
if (start == selectionStart && end == selectionEnd)
return;
selectionStart = start;
selectionEnd = end;
invalidateSelection();
}
public void unselectAll() {
if (selectionStart == -1 || selectionEnd == -1)
return;
selectionStart = -1;
selectionEnd = -1;
invalidateSelection();
}
public void setTimeIntervall() {
Iterator<Slot> it= slots.iterator();
while (it.hasNext()) {
Slot slot = it.next();
slot.setTimeIntervall();
}
}
private int addSlot() {
Slot slot= new Slot();
slot.setTimeIntervall();
slots.add(slot);
this.add(slot);
this.add(Box.createHorizontalStrut(slot_space));
updateHeaderSize();
return slots.size()-1;
}
public void updateHeaderSize() {
Dimension size = header.getPreferredSize();
int width = slotxsize * slots.size() //Slotwidth and border
+ slot_space * slots.size() //Space between Slots
+ left_gap + right_gap; // left and right gap
Dimension newSize = new Dimension(width
, (int)size.getHeight());
header.setPreferredSize(newSize);
header.setMaximumSize(newSize);
header.invalidate();
}
/**
fuegt einen block im gewuenschten slot ein
(konflikte werden ignoriert).
*/
public void putBlock(SwingBlock bl, int slotnr) {
while (true) {
final int size = slots.size();
if (slotnr >= size)
{
addSlot();
}
else
{
break;
}
}
slots.get(slotnr).putBlock(bl);
// The blockListener can be shared among all blocks,
// as long es we can only click on one block simultanously
bl.getView().addMouseListener(blockListener);
bl.getView().addMouseMotionListener(blockListener);
blockViewMapper.put(bl.getView(),bl);
}
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getMaximumSize() { return getPreferredSize(); }
Insets insets = new Insets(0,0,0, right_gap);
Insets slotInsets = new Insets(0,0,0,0);
public Insets getInsets() {
return insets;
}
SwingBlock getBlockFor(Object component) {
return blockViewMapper.get(component);
}
int getBlockCount() {
int count = 0;
Iterator<Slot> it = slots.iterator();
while (it.hasNext())
count += it.next().getBlockCount();
return count;
}
boolean isEmpty() {
return getBlockCount() == 0;
}
protected void invalidateDragging(Point oldPoint) {
int width = getSize().width;
int startRow = Math.min(calcRow(draggingY),calcRow(oldPoint.y ));
int endRow = Math.max(calcRow(draggingY),calcRow(oldPoint.y )) + 1;
repaint(0
, rowScale.getYCoordForRow(startRow) -10
, width
, rowScale.getSizeInPixelBetween(startRow, endRow) + draggingHeight + 20
);
}
private void invalidateSelection() {
int width = getSize().width;
int startRow = Math.min(selectionStart,oldSelectionStart);
int endRow = Math.max(selectionEnd,oldSelectionEnd) + 1;
repaint(0,rowScale.getYCoordForRow(startRow ), width, rowScale.getSizeInPixelBetween(startRow, endRow ));
// Update the values after calling repaint, because paint needs the old values.
oldSelectionStart = selectionStart;
oldSelectionEnd = selectionEnd;
}
public void paint(Graphics g) {
Dimension dim = getSize();
Rectangle rect = g.getClipBounds();
if (!isEditable()) {
g.setColor(Color.white);
g.fillRect(rect.x
,rect.y
,rect.width
,rect.height);
} else {
int starty = rowScale.getStartWorktimePixel();
int endy = rowScale.getEndWorktimePixel();
int height = rowScale.getSizeInPixel();
Color firstColor = NON_WORKTIME_BACKGROUND;
Color secondColor = WORKTIME_BACKGROUND;
if ( starty >= endy)
{
int c = starty;
starty = endy;
endy = c;
secondColor = NON_WORKTIME_BACKGROUND;
firstColor = WORKTIME_BACKGROUND;
}
if (rect.y - rect.height <= starty) {
g.setColor( firstColor );
g.fillRect(rect.x
,Math.max(rect.y,0)
,rect.width
,Math.min(rect.height,starty));
}
if (rect.y + rect.height >= starty && rect.y <= endy ) {
g.setColor( secondColor );
g.fillRect(rect.x
,Math.max(rect.y,starty)
,rect.width
,Math.min(rect.height,endy - starty));
}
if (rect.y + rect.height >= endy) {
g.setColor( firstColor );
g.fillRect(rect.x
,Math.max(rect.y,endy)
,rect.width
,Math.min(rect.height, height - endy));
}
}
if (isBorderVisible()) {
g.setColor(LINE_COLOR);
g.drawLine(0,rect.y,0,rect.y + rect.height);
g.drawLine(dim.width - 1,rect.y,dim.width - 1 ,rect.y + rect.height);
}
int max = rowScale.getMaxRows() ;
// Paint selection
for (int i=0; i < max ; i++) {
int rowSize = rowScale.getRowSizeForRow( i);
int y = rowScale.getYCoordForRow( i);
if ((y + rowSize) >= rect.y && y < (rect.y + rect.height)) {
if (i>= selectionStart && i<=selectionEnd) {
g.setColor(getSelectionColor());
g.fillRect(Math.max (rect.x,1)
, y
, Math.min (rect.width,dim.width - Math.max (rect.x,1) - 1)
, rowSize);
}
boolean bPaintRowThick = (rowScale.isPaintRowThick(i));
g.setColor((bPaintRowThick) ? THICK_LINE_COLOR : LINE_COLOR);
if (isEditable() || (bPaintRowThick && (i<max || isBorderVisible())))
g.drawLine(rect.x,y ,rect.x + rect.width , y);
if ( i == max -1 )
{
g.setColor( THICK_LINE_COLOR );
g.drawLine(rect.x,y+rowSize ,rect.x + rect.width , y+rowSize);
}
}
}
super.paintChildren(g);
if ( paintDraggingGrid ) {
int x = draggingSlot * (slotxsize + slot_space) + left_gap;
paintDraggingGrid(g, x , draggingY, slotxsize -1, draggingHeight);
}
}
/** grafische komponente, in die implementierungen von Block (genauer deren zugehoerige BlockViews) eingefuegt werden koennen.
* entsprechend start- und end-zeit des blocks wird der view
* im slot dargestellt. die views werden dabei vertikal angeordnet.
*/
class Slot extends JPanel
{
private static final long serialVersionUID = 1L;
private final Collection<Block> blocks= new ArrayList<>();
public Slot() {
setLayout(null);
setBackground(Color.white);
setOpaque(false);
}
/** legt fest, fuer welches zeitintervall das slot gelten soll.
(Beispiel 8:00 - 13:00)
min und max sind uhrzeiten in vollen stunden.
zur initialisierung der komponente muss diese methode mindestens einmal
aufgerufen werden.
*/
public void setTimeIntervall() {
int ysize= rowScale.getSizeInPixel() + 1;
setSize(slotxsize, ysize);
Dimension preferredSize = new Dimension(slotxsize, ysize );
setPreferredSize(preferredSize );
setMinimumSize(preferredSize );
}
/** fuegt b in den Slot ein. */
public void putBlock(SwingBlock b) {
blocks.add(b);
add(b.getView());
updateBounds(b);
}
public void updateBounds(SwingBlock b) {
if ( b == null)
{
return;
}
//update bounds
int y1= rowScale.getYCoord(b.getStart());
final int minimumSize = 15;
int y2 = rowScale.getYCoord(b.getEnd());
final int maxHeight = getMaximumSize().height;
if (y1 <0)
{
y1 += maxHeight;
}
if (y2 <0)
{
y2 += maxHeight;
}
if (y1> y2)
{
int swap = y1;
y1 = y2;
y2 = swap;
}
y2= Math.max( y1+minimumSize, y2);
if ( y1 < 0)
y1 = 0;
if ( y2 > maxHeight)
y2 = maxHeight;
b.getView().setBounds(0, y1, slotxsize, y2 - y1 + 1);
}
public int getBlockCount() {
return blocks.size();
}
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getMaximumSize() { return getPreferredSize(); }
public Insets getInsets() {
return slotInsets;
}
public Collection<Block> getBlocks() {
return blocks;
}
}
void updateSize(int slotsize)
{
this.slotxsize = slotsize;
for ( Slot slot:slots)
{
slot.setTimeIntervall();
for (Block block:slot.getBlocks())
{
slot.updateBounds((SwingBlock)block);
}
}
updateHeaderSize();
}
public int calcRow( int y )
{
return rowScale.calcRow( y);
}
}
| rapla/rapla | src/main/java/org/rapla/components/calendarview/swing/LargeDaySlot.java | 4,255 | //Space between Slots | line_comment | nl | /*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| 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. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.components.calendarview.swing;
import org.rapla.components.calendarview.Block;
import org.rapla.components.calendarview.swing.scaling.IRowScale;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/** Komponente, welche eine beliebige anzahl von Slot-komponenten zusammenfasst.
* die slots koennen zur laufzeit hinzugefuegt oder auch dynamisch bei bedarf
*erzeugt werden. sie werden horizontal nebeneinander angeordnet.
*/
class LargeDaySlot extends AbstractDaySlot
{
private static final long serialVersionUID = 1L;
public static Color THICK_LINE_COLOR = Color.black;
public static Color LINE_COLOR = new Color(0xaa, 0xaa, 0xaa);
public static Color WORKTIME_BACKGROUND = Color.white;
public static Color NON_WORKTIME_BACKGROUND = new Color(0xcc, 0xcc, 0xcc);
private final List<Slot> slots= new ArrayList<>();
private int slotxsize;
private int selectionStart = -1;
private int selectionEnd = -1;
private int oldSelectionStart = -1;
private int oldSelectionEnd = -1;
BoxLayout boxLayout1 = new BoxLayout(this, BoxLayout.X_AXIS);
int right_gap = 8;
int left_gap = 5;
int slot_space = 3;
JComponent header;
IRowScale rowScale;
private final BlockListener blockListener = new BlockListener();
/**
es muss auch noch setTimeIntervall() aufgerufen werden, um die initialisierung
fertig zu stellen (wie beim konstruktor von Slot).
slotxsize ist die breite der einzelnen slots.
"date" legt das Datum fest, fuer welches das Slot anzeigt (Uhrzeit bleibt unberuecksichtigt)
*/
public LargeDaySlot(
int slotxsize
,IRowScale rowScale
,JComponent header) {
this.slotxsize= slotxsize;
this.rowScale = rowScale;
this.header = header;
setLayout(boxLayout1);
this.add(Box.createHorizontalStrut(left_gap));
addSlot();
setBackground(getBackground());
setAlignmentX(0);
setAlignmentY(TOP_ALIGNMENT);
this.setBackground(Color.white);
}
public boolean isBorderVisible() {
return true;
// return getBackground() != Color.white;
}
public int getSlotCount()
{
return slots.size();
}
public boolean isSelected()
{
return selectionStart >=0 ;
}
public void setVisible(boolean b) {
super.setVisible(b);
header.setVisible(b);
}
public JComponent getHeader() {
return header;
}
public int calcSlot(int x) {
int slot = ((x - left_gap) / (slotxsize + slot_space));
//System.out.println ( x + " slot " + slot);
if (slot<0)
slot = 0;
if (slot >= slots.size())
slot = slots.size() -1;
return slot;
}
public Collection<Block> getBlocks() {
ArrayList<Block> list = new ArrayList<>();
for (int i=0;i<slots.size();i++)
list.addAll(slots.get(i).getBlocks());
return list;
}
public void select(int start,int end) {
if (start == selectionStart && end == selectionEnd)
return;
selectionStart = start;
selectionEnd = end;
invalidateSelection();
}
public void unselectAll() {
if (selectionStart == -1 || selectionEnd == -1)
return;
selectionStart = -1;
selectionEnd = -1;
invalidateSelection();
}
public void setTimeIntervall() {
Iterator<Slot> it= slots.iterator();
while (it.hasNext()) {
Slot slot = it.next();
slot.setTimeIntervall();
}
}
private int addSlot() {
Slot slot= new Slot();
slot.setTimeIntervall();
slots.add(slot);
this.add(slot);
this.add(Box.createHorizontalStrut(slot_space));
updateHeaderSize();
return slots.size()-1;
}
public void updateHeaderSize() {
Dimension size = header.getPreferredSize();
int width = slotxsize * slots.size() //Slotwidth and border
+ slot_space * slots.size() //Space between<SUF>
+ left_gap + right_gap; // left and right gap
Dimension newSize = new Dimension(width
, (int)size.getHeight());
header.setPreferredSize(newSize);
header.setMaximumSize(newSize);
header.invalidate();
}
/**
fuegt einen block im gewuenschten slot ein
(konflikte werden ignoriert).
*/
public void putBlock(SwingBlock bl, int slotnr) {
while (true) {
final int size = slots.size();
if (slotnr >= size)
{
addSlot();
}
else
{
break;
}
}
slots.get(slotnr).putBlock(bl);
// The blockListener can be shared among all blocks,
// as long es we can only click on one block simultanously
bl.getView().addMouseListener(blockListener);
bl.getView().addMouseMotionListener(blockListener);
blockViewMapper.put(bl.getView(),bl);
}
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getMaximumSize() { return getPreferredSize(); }
Insets insets = new Insets(0,0,0, right_gap);
Insets slotInsets = new Insets(0,0,0,0);
public Insets getInsets() {
return insets;
}
SwingBlock getBlockFor(Object component) {
return blockViewMapper.get(component);
}
int getBlockCount() {
int count = 0;
Iterator<Slot> it = slots.iterator();
while (it.hasNext())
count += it.next().getBlockCount();
return count;
}
boolean isEmpty() {
return getBlockCount() == 0;
}
protected void invalidateDragging(Point oldPoint) {
int width = getSize().width;
int startRow = Math.min(calcRow(draggingY),calcRow(oldPoint.y ));
int endRow = Math.max(calcRow(draggingY),calcRow(oldPoint.y )) + 1;
repaint(0
, rowScale.getYCoordForRow(startRow) -10
, width
, rowScale.getSizeInPixelBetween(startRow, endRow) + draggingHeight + 20
);
}
private void invalidateSelection() {
int width = getSize().width;
int startRow = Math.min(selectionStart,oldSelectionStart);
int endRow = Math.max(selectionEnd,oldSelectionEnd) + 1;
repaint(0,rowScale.getYCoordForRow(startRow ), width, rowScale.getSizeInPixelBetween(startRow, endRow ));
// Update the values after calling repaint, because paint needs the old values.
oldSelectionStart = selectionStart;
oldSelectionEnd = selectionEnd;
}
public void paint(Graphics g) {
Dimension dim = getSize();
Rectangle rect = g.getClipBounds();
if (!isEditable()) {
g.setColor(Color.white);
g.fillRect(rect.x
,rect.y
,rect.width
,rect.height);
} else {
int starty = rowScale.getStartWorktimePixel();
int endy = rowScale.getEndWorktimePixel();
int height = rowScale.getSizeInPixel();
Color firstColor = NON_WORKTIME_BACKGROUND;
Color secondColor = WORKTIME_BACKGROUND;
if ( starty >= endy)
{
int c = starty;
starty = endy;
endy = c;
secondColor = NON_WORKTIME_BACKGROUND;
firstColor = WORKTIME_BACKGROUND;
}
if (rect.y - rect.height <= starty) {
g.setColor( firstColor );
g.fillRect(rect.x
,Math.max(rect.y,0)
,rect.width
,Math.min(rect.height,starty));
}
if (rect.y + rect.height >= starty && rect.y <= endy ) {
g.setColor( secondColor );
g.fillRect(rect.x
,Math.max(rect.y,starty)
,rect.width
,Math.min(rect.height,endy - starty));
}
if (rect.y + rect.height >= endy) {
g.setColor( firstColor );
g.fillRect(rect.x
,Math.max(rect.y,endy)
,rect.width
,Math.min(rect.height, height - endy));
}
}
if (isBorderVisible()) {
g.setColor(LINE_COLOR);
g.drawLine(0,rect.y,0,rect.y + rect.height);
g.drawLine(dim.width - 1,rect.y,dim.width - 1 ,rect.y + rect.height);
}
int max = rowScale.getMaxRows() ;
// Paint selection
for (int i=0; i < max ; i++) {
int rowSize = rowScale.getRowSizeForRow( i);
int y = rowScale.getYCoordForRow( i);
if ((y + rowSize) >= rect.y && y < (rect.y + rect.height)) {
if (i>= selectionStart && i<=selectionEnd) {
g.setColor(getSelectionColor());
g.fillRect(Math.max (rect.x,1)
, y
, Math.min (rect.width,dim.width - Math.max (rect.x,1) - 1)
, rowSize);
}
boolean bPaintRowThick = (rowScale.isPaintRowThick(i));
g.setColor((bPaintRowThick) ? THICK_LINE_COLOR : LINE_COLOR);
if (isEditable() || (bPaintRowThick && (i<max || isBorderVisible())))
g.drawLine(rect.x,y ,rect.x + rect.width , y);
if ( i == max -1 )
{
g.setColor( THICK_LINE_COLOR );
g.drawLine(rect.x,y+rowSize ,rect.x + rect.width , y+rowSize);
}
}
}
super.paintChildren(g);
if ( paintDraggingGrid ) {
int x = draggingSlot * (slotxsize + slot_space) + left_gap;
paintDraggingGrid(g, x , draggingY, slotxsize -1, draggingHeight);
}
}
/** grafische komponente, in die implementierungen von Block (genauer deren zugehoerige BlockViews) eingefuegt werden koennen.
* entsprechend start- und end-zeit des blocks wird der view
* im slot dargestellt. die views werden dabei vertikal angeordnet.
*/
class Slot extends JPanel
{
private static final long serialVersionUID = 1L;
private final Collection<Block> blocks= new ArrayList<>();
public Slot() {
setLayout(null);
setBackground(Color.white);
setOpaque(false);
}
/** legt fest, fuer welches zeitintervall das slot gelten soll.
(Beispiel 8:00 - 13:00)
min und max sind uhrzeiten in vollen stunden.
zur initialisierung der komponente muss diese methode mindestens einmal
aufgerufen werden.
*/
public void setTimeIntervall() {
int ysize= rowScale.getSizeInPixel() + 1;
setSize(slotxsize, ysize);
Dimension preferredSize = new Dimension(slotxsize, ysize );
setPreferredSize(preferredSize );
setMinimumSize(preferredSize );
}
/** fuegt b in den Slot ein. */
public void putBlock(SwingBlock b) {
blocks.add(b);
add(b.getView());
updateBounds(b);
}
public void updateBounds(SwingBlock b) {
if ( b == null)
{
return;
}
//update bounds
int y1= rowScale.getYCoord(b.getStart());
final int minimumSize = 15;
int y2 = rowScale.getYCoord(b.getEnd());
final int maxHeight = getMaximumSize().height;
if (y1 <0)
{
y1 += maxHeight;
}
if (y2 <0)
{
y2 += maxHeight;
}
if (y1> y2)
{
int swap = y1;
y1 = y2;
y2 = swap;
}
y2= Math.max( y1+minimumSize, y2);
if ( y1 < 0)
y1 = 0;
if ( y2 > maxHeight)
y2 = maxHeight;
b.getView().setBounds(0, y1, slotxsize, y2 - y1 + 1);
}
public int getBlockCount() {
return blocks.size();
}
public Dimension getMinimumSize() { return getPreferredSize(); }
public Dimension getMaximumSize() { return getPreferredSize(); }
public Insets getInsets() {
return slotInsets;
}
public Collection<Block> getBlocks() {
return blocks;
}
}
void updateSize(int slotsize)
{
this.slotxsize = slotsize;
for ( Slot slot:slots)
{
slot.setTimeIntervall();
for (Block block:slot.getBlocks())
{
slot.updateBounds((SwingBlock)block);
}
}
updateHeaderSize();
}
public int calcRow( int y )
{
return rowScale.calcRow( y);
}
}
|
64765_10 | package controle;
import modelo.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Classe que define os atributos e metodos do objeto
* @author Vera Lucia Bezerra da Silva e Raquel Eucaria
* @version 1.0 (April 2022)
*/
public class ControleDados {
private Dados d = new Dados();
public ControleDados() {
d.preDados();
}
/**
* Valid os dodos inserir/editar de Usuario
* @param dadosUsuario exporta os dados de um novo Usuario
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
public boolean inserirEditarUsuario(String[] dadosUsuario) {
//0 - idUsuario; 1 - nome;2 - cpf; 3 - telefone; 4 - pagamento; 5 - endereco;
Usuario p = new Usuario(Integer.parseInt(dadosUsuario[0]), dadosUsuario[1], Integer.parseInt(dadosUsuario[2]),
new Telefone(Integer.parseInt(dadosUsuario[3]), Integer.parseInt(dadosUsuario[4])), //telefone
null, //pagamento
new Endereco(Integer.parseInt(dadosUsuario[9]), Integer.parseInt(dadosUsuario[8]), dadosUsuario[6], dadosUsuario[7])); //endere�o
return d.inserirEditarUsuario(p);
}
/**
*Metodo para remover um Usuario
* @param posicao refente a posicao do Usuario que vai ser reovido
* @return
*/
public boolean removerUsuario(int posicao) {
return this.getUsuarios().remove(this.getUsuarios().get(posicao));
}
/**
* Valida os dodos inserir/editar de Blusa
* @param dadosBlusa exporta os dados de um novo Usuario
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
public boolean inserirEditarBlusa(String[] dadosBlusa) {
Blusa p = new Blusa(Integer.parseInt(dadosBlusa[0]), //ID
dadosBlusa[1], //nome
dadosBlusa[2], //marca
Float.parseFloat(dadosBlusa[3]), //preco
dadosBlusa[4], //departamento
dadosBlusa[5], //descricao
dadosBlusa[6], //cor
dadosBlusa[7], //tamanho
dadosBlusa[8], //modeloblusa
null); //usuario(vendedor)
d.inserirEditarBlusa(p, Integer.parseInt(dadosBlusa[0]));
return true;
}
/**
* Método para remover uma blusa
* @param i posição da blusa que vai ser removido
* @return true se a blusa foi removido
*/
public boolean removerBlusa(int i) {
String blusaRemovida = d.getBlusas()[i].getNome();
if (i == (d.getQtdBlusas() - 1)) {
d.setQtdBlusas(d.getQtdBlusas() - 1);
d.getBlusas()[d.getQtdBlusas()] = null;
return true;
} else {
int cont = 0;
while (d.getBlusas()[cont].getNome().compareTo(blusaRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdBlusas() - 1; j++) {
d.getBlusas()[j] = null;
d.getBlusas()[j] = d.getBlusas()[j + 1];
}
d.getBlusas()[d.getQtdBlusas()] = null;
d.setQtdBlusas(d.getQtdBlusas() - 1);
return true;
}
}
/**
* Valida os dodos inserir/editar de calca
* @param dadosCalca exporta os dados de uma nova Calca
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
// CALCAS -------------
public boolean inserirEditarCalca(String[] dadosCalca) {
Calca p = new Calca(Integer.parseInt(dadosCalca[0]), dadosCalca[1], dadosCalca[2], Float.parseFloat(dadosCalca[3]), dadosCalca[4], dadosCalca[5], dadosCalca[6], dadosCalca[7], dadosCalca[8], null);
d.inserirEditarCalca(p, Integer.parseInt(dadosCalca[0]));
return true;
}
/**
* Método para remover uma calca
* @param i posição da calca que vai ser removido
* @return true se a calca foi removido
*/
public boolean removerCalca(int i) {
String calcaRemovida = d.getCalcas()[i].getNome();
if (i == (d.getQtdCalcas() - 1)) {
d.setQtdCalcas(d.getQtdCalcas() - 1);
d.getCalcas()[d.getQtdCalcas()] = null;
return true;
} else {
int cont = 0;
while (d.getCalcas()[cont].getNome().compareTo(calcaRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdCalcas() - 1; j++) {
d.getCalcas()[j] = null;
d.getCalcas()[j] = d.getCalcas()[j + 1];
}
d.getCalcas()[d.getQtdCalcas()] = null;
d.setQtdCalcas(d.getQtdCalcas() - 1);
return true;
}
}
/**
* Valid os dodos inserir/editar de bijuteria
* @param dadosBijus exporta os dados de uma nova bijuteria
* @return true quando for autorizado a inserir e/ou editar uma Bijuteria
*/
// BIJUS --------------
public boolean inserirEditarBijus(String[] dadosBijus) {
Bijuteria p = new Bijuteria(Integer.parseInt(dadosBijus[0]), dadosBijus[1], dadosBijus[2], Float.parseFloat(dadosBijus[3]), dadosBijus[4], dadosBijus[5], dadosBijus[6], dadosBijus[7], dadosBijus[8], null);
d.inserirEditarBiju(p, Integer.parseInt(dadosBijus[0]));
return true;
}
/**
* Método para remover uma Bijuteria
* @param i posição da bijuteria que vai ser removido
* @return true se a bijuteria foi removido
*/
public boolean removerBiju(int i) {
String bijuRemovida = d.getBijus()[i].getNome();
if (i == (d.getQtdBijus() - 1)) {
d.setQtdBijus(d.getQtdBijus() - 1);
d.getBijus()[d.getQtdBijus()] = null;
return true;
} else {
int cont = 0;
while (d.getBijus()[cont].getNome().compareTo(bijuRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdBijus() - 1; j++) {
d.getBijus()[j] = null;
d.getBijus()[j] = d.getBijus()[j + 1];
}
d.getBijus()[d.getQtdBijus()] = null;
d.setQtdBijus(d.getQtdBijus() - 1);
return true;
}
}
//-------------Gets e sets----------------
public Dados getDados() {
return d;
}
public void setDados(Dados d) {
this.d = d;
}
public List<Usuario> getUsuarios() {
return this.d.getUsuarios();
}
public Blusa[] getBlusas() {
return this.d.getBlusas();
}
public int getQtdBlusas() {
return this.d.getQtdBlusas();
}
public Bijuteria[] getBijus() {
return this.d.getBijus();
}
public int getQtdBijus() {
return this.d.getQtdBijus();
}
public Calca[] getCalcas() {
return this.d.getCalcas();
}
public int getQtdCalcas() {
return this.d.getQtdCalcas();
}
public Carrinho getCarrinho() {
return this.d.getCarrinho();
}
public int getQtdItensCarrs() {
return this.d.getQtdItensCarrs();
}
public List<Compra> getCompras() {
return this.d.getCompras();
}
public int getQtdCompras() {
return this.d.getQtdCompras();
}
} | raqueleucaria/Engenharia-de-Software-FGA | 3° Semestre/OO/Tp4/TP4/src/controle/ControleDados.java | 2,580 | //-------------Gets e sets---------------- | line_comment | nl | package controle;
import modelo.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* Classe que define os atributos e metodos do objeto
* @author Vera Lucia Bezerra da Silva e Raquel Eucaria
* @version 1.0 (April 2022)
*/
public class ControleDados {
private Dados d = new Dados();
public ControleDados() {
d.preDados();
}
/**
* Valid os dodos inserir/editar de Usuario
* @param dadosUsuario exporta os dados de um novo Usuario
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
public boolean inserirEditarUsuario(String[] dadosUsuario) {
//0 - idUsuario; 1 - nome;2 - cpf; 3 - telefone; 4 - pagamento; 5 - endereco;
Usuario p = new Usuario(Integer.parseInt(dadosUsuario[0]), dadosUsuario[1], Integer.parseInt(dadosUsuario[2]),
new Telefone(Integer.parseInt(dadosUsuario[3]), Integer.parseInt(dadosUsuario[4])), //telefone
null, //pagamento
new Endereco(Integer.parseInt(dadosUsuario[9]), Integer.parseInt(dadosUsuario[8]), dadosUsuario[6], dadosUsuario[7])); //endere�o
return d.inserirEditarUsuario(p);
}
/**
*Metodo para remover um Usuario
* @param posicao refente a posicao do Usuario que vai ser reovido
* @return
*/
public boolean removerUsuario(int posicao) {
return this.getUsuarios().remove(this.getUsuarios().get(posicao));
}
/**
* Valida os dodos inserir/editar de Blusa
* @param dadosBlusa exporta os dados de um novo Usuario
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
public boolean inserirEditarBlusa(String[] dadosBlusa) {
Blusa p = new Blusa(Integer.parseInt(dadosBlusa[0]), //ID
dadosBlusa[1], //nome
dadosBlusa[2], //marca
Float.parseFloat(dadosBlusa[3]), //preco
dadosBlusa[4], //departamento
dadosBlusa[5], //descricao
dadosBlusa[6], //cor
dadosBlusa[7], //tamanho
dadosBlusa[8], //modeloblusa
null); //usuario(vendedor)
d.inserirEditarBlusa(p, Integer.parseInt(dadosBlusa[0]));
return true;
}
/**
* Método para remover uma blusa
* @param i posição da blusa que vai ser removido
* @return true se a blusa foi removido
*/
public boolean removerBlusa(int i) {
String blusaRemovida = d.getBlusas()[i].getNome();
if (i == (d.getQtdBlusas() - 1)) {
d.setQtdBlusas(d.getQtdBlusas() - 1);
d.getBlusas()[d.getQtdBlusas()] = null;
return true;
} else {
int cont = 0;
while (d.getBlusas()[cont].getNome().compareTo(blusaRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdBlusas() - 1; j++) {
d.getBlusas()[j] = null;
d.getBlusas()[j] = d.getBlusas()[j + 1];
}
d.getBlusas()[d.getQtdBlusas()] = null;
d.setQtdBlusas(d.getQtdBlusas() - 1);
return true;
}
}
/**
* Valida os dodos inserir/editar de calca
* @param dadosCalca exporta os dados de uma nova Calca
* @return true quando for autorizado a inserir e/ou editar um Usuario
*/
// CALCAS -------------
public boolean inserirEditarCalca(String[] dadosCalca) {
Calca p = new Calca(Integer.parseInt(dadosCalca[0]), dadosCalca[1], dadosCalca[2], Float.parseFloat(dadosCalca[3]), dadosCalca[4], dadosCalca[5], dadosCalca[6], dadosCalca[7], dadosCalca[8], null);
d.inserirEditarCalca(p, Integer.parseInt(dadosCalca[0]));
return true;
}
/**
* Método para remover uma calca
* @param i posição da calca que vai ser removido
* @return true se a calca foi removido
*/
public boolean removerCalca(int i) {
String calcaRemovida = d.getCalcas()[i].getNome();
if (i == (d.getQtdCalcas() - 1)) {
d.setQtdCalcas(d.getQtdCalcas() - 1);
d.getCalcas()[d.getQtdCalcas()] = null;
return true;
} else {
int cont = 0;
while (d.getCalcas()[cont].getNome().compareTo(calcaRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdCalcas() - 1; j++) {
d.getCalcas()[j] = null;
d.getCalcas()[j] = d.getCalcas()[j + 1];
}
d.getCalcas()[d.getQtdCalcas()] = null;
d.setQtdCalcas(d.getQtdCalcas() - 1);
return true;
}
}
/**
* Valid os dodos inserir/editar de bijuteria
* @param dadosBijus exporta os dados de uma nova bijuteria
* @return true quando for autorizado a inserir e/ou editar uma Bijuteria
*/
// BIJUS --------------
public boolean inserirEditarBijus(String[] dadosBijus) {
Bijuteria p = new Bijuteria(Integer.parseInt(dadosBijus[0]), dadosBijus[1], dadosBijus[2], Float.parseFloat(dadosBijus[3]), dadosBijus[4], dadosBijus[5], dadosBijus[6], dadosBijus[7], dadosBijus[8], null);
d.inserirEditarBiju(p, Integer.parseInt(dadosBijus[0]));
return true;
}
/**
* Método para remover uma Bijuteria
* @param i posição da bijuteria que vai ser removido
* @return true se a bijuteria foi removido
*/
public boolean removerBiju(int i) {
String bijuRemovida = d.getBijus()[i].getNome();
if (i == (d.getQtdBijus() - 1)) {
d.setQtdBijus(d.getQtdBijus() - 1);
d.getBijus()[d.getQtdBijus()] = null;
return true;
} else {
int cont = 0;
while (d.getBijus()[cont].getNome().compareTo(bijuRemovida) != 0) {
cont++;
}
for (int j = cont; j < d.getQtdBijus() - 1; j++) {
d.getBijus()[j] = null;
d.getBijus()[j] = d.getBijus()[j + 1];
}
d.getBijus()[d.getQtdBijus()] = null;
d.setQtdBijus(d.getQtdBijus() - 1);
return true;
}
}
//-------------Gets e<SUF>
public Dados getDados() {
return d;
}
public void setDados(Dados d) {
this.d = d;
}
public List<Usuario> getUsuarios() {
return this.d.getUsuarios();
}
public Blusa[] getBlusas() {
return this.d.getBlusas();
}
public int getQtdBlusas() {
return this.d.getQtdBlusas();
}
public Bijuteria[] getBijus() {
return this.d.getBijus();
}
public int getQtdBijus() {
return this.d.getQtdBijus();
}
public Calca[] getCalcas() {
return this.d.getCalcas();
}
public int getQtdCalcas() {
return this.d.getQtdCalcas();
}
public Carrinho getCarrinho() {
return this.d.getCarrinho();
}
public int getQtdItensCarrs() {
return this.d.getQtdItensCarrs();
}
public List<Compra> getCompras() {
return this.d.getCompras();
}
public int getQtdCompras() {
return this.d.getQtdCompras();
}
} |
109751_18 | /*
* 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 lucene.core.util; // from org.apache.solr.util rev 555343
/** A variety of high efficiency bit twiddling routines.
* @lucene.internal
*/
public final class BitUtil {
// magic numbers for bit interleaving
private static final long MAGIC[] = {
0x5555555555555555L, 0x3333333333333333L,
0x0F0F0F0F0F0F0F0FL, 0x00FF00FF00FF00FFL,
0x0000FFFF0000FFFFL, 0x00000000FFFFFFFFL,
0xAAAAAAAAAAAAAAAAL
};
// shift values for bit interleaving
private static final short SHIFT[] = {1, 2, 4, 8, 16};
private BitUtil() {} // no instance
// The pop methods used to rely on bit-manipulation tricks for speed but it
// turns out that it is faster to use the Long.bitCount method (which is an
// intrinsic since Java 6u18) in a naive loop, see LUCENE-2221
/** Returns the number of set bits in an array of longs. */
public static long pop_array(long[] arr, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the two sets after an intersection.
* Neither array is modified. */
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the union of two sets.
* Neither array is modified. */
public static long pop_union(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] | arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of {@code A & ~B}.
* Neither array is modified. */
public static long pop_andnot(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & ~arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of A ^ B
* Neither array is modified. */
public static long pop_xor(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] ^ arr2[i]);
}
return popCount;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static int nextHighestPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static long nextHighestPowerOfTwo(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
/**
* Interleaves the first 32 bits of each long value
*
* Adapted from: http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
*/
public static long interleave(int even, int odd) {
long v1 = 0x00000000FFFFFFFFL & even;
long v2 = 0x00000000FFFFFFFFL & odd;
v1 = (v1 | (v1 << SHIFT[4])) & MAGIC[4];
v1 = (v1 | (v1 << SHIFT[3])) & MAGIC[3];
v1 = (v1 | (v1 << SHIFT[2])) & MAGIC[2];
v1 = (v1 | (v1 << SHIFT[1])) & MAGIC[1];
v1 = (v1 | (v1 << SHIFT[0])) & MAGIC[0];
v2 = (v2 | (v2 << SHIFT[4])) & MAGIC[4];
v2 = (v2 | (v2 << SHIFT[3])) & MAGIC[3];
v2 = (v2 | (v2 << SHIFT[2])) & MAGIC[2];
v2 = (v2 | (v2 << SHIFT[1])) & MAGIC[1];
v2 = (v2 | (v2 << SHIFT[0])) & MAGIC[0];
return (v2<<1) | v1;
}
/**
* Deinterleaves long value back to two concatenated 32bit values
*/
public static long deinterleave(long b) {
b &= MAGIC[0];
b = (b ^ (b >>> SHIFT[0])) & MAGIC[1];
b = (b ^ (b >>> SHIFT[1])) & MAGIC[2];
b = (b ^ (b >>> SHIFT[2])) & MAGIC[3];
b = (b ^ (b >>> SHIFT[3])) & MAGIC[4];
b = (b ^ (b >>> SHIFT[4])) & MAGIC[5];
return b;
}
/**
* flip flops odd with even bits
*/
public static final long flipFlop(final long b) {
return ((b & MAGIC[6]) >>> 1) | ((b & MAGIC[0]) << 1 );
}
/** Same as {@link #zigZagEncode(long)} but on integers. */
public static int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
public static long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
public static int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
public static long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
| rasoio/daon | daon-core/src/main/java/lucene/core/util/BitUtil.java | 2,235 | /** Same as {@link #zigZagEncode(long)} but on integers. */ | 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 lucene.core.util; // from org.apache.solr.util rev 555343
/** A variety of high efficiency bit twiddling routines.
* @lucene.internal
*/
public final class BitUtil {
// magic numbers for bit interleaving
private static final long MAGIC[] = {
0x5555555555555555L, 0x3333333333333333L,
0x0F0F0F0F0F0F0F0FL, 0x00FF00FF00FF00FFL,
0x0000FFFF0000FFFFL, 0x00000000FFFFFFFFL,
0xAAAAAAAAAAAAAAAAL
};
// shift values for bit interleaving
private static final short SHIFT[] = {1, 2, 4, 8, 16};
private BitUtil() {} // no instance
// The pop methods used to rely on bit-manipulation tricks for speed but it
// turns out that it is faster to use the Long.bitCount method (which is an
// intrinsic since Java 6u18) in a naive loop, see LUCENE-2221
/** Returns the number of set bits in an array of longs. */
public static long pop_array(long[] arr, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the two sets after an intersection.
* Neither array is modified. */
public static long pop_intersect(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of the union of two sets.
* Neither array is modified. */
public static long pop_union(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] | arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of {@code A & ~B}.
* Neither array is modified. */
public static long pop_andnot(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] & ~arr2[i]);
}
return popCount;
}
/** Returns the popcount or cardinality of A ^ B
* Neither array is modified. */
public static long pop_xor(long[] arr1, long[] arr2, int wordOffset, int numWords) {
long popCount = 0;
for (int i = wordOffset, end = wordOffset + numWords; i < end; ++i) {
popCount += Long.bitCount(arr1[i] ^ arr2[i]);
}
return popCount;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static int nextHighestPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
/** returns the next highest power of two, or the current value if it's already a power of two or zero*/
public static long nextHighestPowerOfTwo(long v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
/**
* Interleaves the first 32 bits of each long value
*
* Adapted from: http://graphics.stanford.edu/~seander/bithacks.html#InterleaveBMN
*/
public static long interleave(int even, int odd) {
long v1 = 0x00000000FFFFFFFFL & even;
long v2 = 0x00000000FFFFFFFFL & odd;
v1 = (v1 | (v1 << SHIFT[4])) & MAGIC[4];
v1 = (v1 | (v1 << SHIFT[3])) & MAGIC[3];
v1 = (v1 | (v1 << SHIFT[2])) & MAGIC[2];
v1 = (v1 | (v1 << SHIFT[1])) & MAGIC[1];
v1 = (v1 | (v1 << SHIFT[0])) & MAGIC[0];
v2 = (v2 | (v2 << SHIFT[4])) & MAGIC[4];
v2 = (v2 | (v2 << SHIFT[3])) & MAGIC[3];
v2 = (v2 | (v2 << SHIFT[2])) & MAGIC[2];
v2 = (v2 | (v2 << SHIFT[1])) & MAGIC[1];
v2 = (v2 | (v2 << SHIFT[0])) & MAGIC[0];
return (v2<<1) | v1;
}
/**
* Deinterleaves long value back to two concatenated 32bit values
*/
public static long deinterleave(long b) {
b &= MAGIC[0];
b = (b ^ (b >>> SHIFT[0])) & MAGIC[1];
b = (b ^ (b >>> SHIFT[1])) & MAGIC[2];
b = (b ^ (b >>> SHIFT[2])) & MAGIC[3];
b = (b ^ (b >>> SHIFT[3])) & MAGIC[4];
b = (b ^ (b >>> SHIFT[4])) & MAGIC[5];
return b;
}
/**
* flip flops odd with even bits
*/
public static final long flipFlop(final long b) {
return ((b & MAGIC[6]) >>> 1) | ((b & MAGIC[0]) << 1 );
}
/** Same as {@link<SUF>*/
public static int zigZagEncode(int i) {
return (i >> 31) ^ (i << 1);
}
/**
* <a href="https://developers.google.com/protocol-buffers/docs/encoding#types">Zig-zag</a>
* encode the provided long. Assuming the input is a signed long whose
* absolute value can be stored on <tt>n</tt> bits, the returned value will
* be an unsigned long that can be stored on <tt>n+1</tt> bits.
*/
public static long zigZagEncode(long l) {
return (l >> 63) ^ (l << 1);
}
/** Decode an int previously encoded with {@link #zigZagEncode(int)}. */
public static int zigZagDecode(int i) {
return ((i >>> 1) ^ -(i & 1));
}
/** Decode a long previously encoded with {@link #zigZagEncode(long)}. */
public static long zigZagDecode(long l) {
return ((l >>> 1) ^ -(l & 1));
}
}
|
145335_0 | package DP_OV_Chipkaart;
import DP_OV_Chipkaart.Connections.ConnectionDatabase;
import DP_OV_Chipkaart.Dao.AdresDao;
import DP_OV_Chipkaart.Dao.OvChipkaartDao;
import DP_OV_Chipkaart.Dao.ProductDao;
import DP_OV_Chipkaart.Dao.ReizigerDao;
import DP_OV_Chipkaart.DaoPsql.AdresDAOPsql;
import DP_OV_Chipkaart.DaoPsql.OvChipKaartDaoPsql;
import DP_OV_Chipkaart.DaoPsql.ProductDaoPsql;
import DP_OV_Chipkaart.DaoPsql.ReizigerDAOPsql;
import DP_OV_Chipkaart.Domain.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class Main {
public static void main(String [] args) throws Exception {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(sqlDate);
//P1
ConnectionDatabase.ConnectionDatabaseIsntance connection = new ConnectionDatabase.ConnectionDatabaseIsntance();
String q = "SELECT reiziger_id, voorletters, tussenvoegsel, achternaam, geboortedatum FROM reiziger";
PreparedStatement pst = connection.getConnection().prepareStatement(q);
ResultSet resultSet = pst.executeQuery();
while(resultSet.next()){
int reiziger_id = resultSet.getInt(1);
String voorletters = resultSet.getString(2);
String tussenvoegsel = resultSet.getString(3);
String achternaam = resultSet.getString(4);
java.sql.Date geboorteDatum = resultSet.getDate(5);
System.out.println(reiziger_id + " " + voorletters + " " + (tussenvoegsel == null ? "" : tussenvoegsel) + " " + achternaam + " (" + geboorteDatum + ")");
}
pst.close();
ProductDaoPsql productDao = new ProductDaoPsql(connection, null);
OvChipKaartDaoPsql ovChipkaartDao = new OvChipKaartDaoPsql(connection, productDao, null);
AdresDAOPsql adressDAOPsql = new AdresDAOPsql(connection);
ReizigerDAOPsql daoReiziger = new ReizigerDAOPsql(connection, adressDAOPsql, ovChipkaartDao);
productDao.setOvChipKaartDao(ovChipkaartDao);
adressDAOPsql.setReizigerDAOPsql(daoReiziger);
// testReizigerDAO(daoReiziger);
//testReizigerP3(daoReiziger, adressDAOPsql);
ovChipkaartDao.setReizigerDAOPsql(daoReiziger);
testp5(productDao, ovChipkaartDao);
connection.getConnection().close();
}
/**
* P2. Reiziger DAO: persistentie van een klasse
*
* Deze methode test de CRUD-functionaliteit van de Reiziger DAO
*
* @throws SQLException
*/
private static void testReizigerDAO(ReizigerDao rdao) throws Exception {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum), null);
System.out.println(sietske.toString());
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
System.out.println("het is zijn trouwdag en sietske krijgt een extra achernaam ");
sietske.setAchternaam("Broers-Oranje");
rdao.update(sietske);
System.out.println(rdao.findById(sietske.getId()));
reizigers = rdao.findAll();
System.out.println("reizigers voor ReizigerDAO.delete(): " + reizigers.size() + "\n");
rdao.delete(sietske);
reizigers = rdao.findAll();
System.out.println(" reizigers na ReizigerDAO.delete() : "+ reizigers.size() + " reizigers\n");
System.out.println(rdao.findById(sietske.getId()));
}
private static void testReizigerP3(ReizigerDao rdao, AdresDao adao) throws Exception {
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r.toString());
}
System.out.println();
Reiziger reiziger = rdao.findById(1);
System.out.println(reiziger);
Adres backupAdres = reiziger.getAdress();
System.out.println("De reiziger gaat naar Groot Britanie verhuizen");
Adres adres = new Adres(25, "1122BB", "22", "Diagon Alley", "London", reiziger);
reiziger.setAdress(adres);
rdao.update(reiziger);
reiziger = rdao.findById(1);
System.out.println(reiziger.toString());
System.out.print("De reiziger gaat wordt premie: ");
adres.setStraat("Downing street");
adao.update(adres);
reiziger = rdao.findById(1);
System.out.println(reiziger);
System.out.println("test adao.findByReiziger: " + adao.findByReiziger(reiziger));
//brexit, terug naar nederland dan maar weer
reiziger.setAdress(backupAdres);
rdao.update(reiziger);
System.out.println();
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:");
for (Adres a : adressen) {
System.out.println(a.toString());
}
System.out.println();
}
private static void testp5(ProductDao pdao, OvChipkaartDao ovChipkaartDao) throws Exception {
for(OvChipKaart ovChipKaart : ovChipkaartDao.findAll()){
System.out.println(ovChipKaart.toString());
}
for(Product product : pdao.findAll()){
System.out.println(product.toString());
}
}
}
| raubenravi/data-and-Persistence_ruben | src/DP_OV_Chipkaart/Main.java | 2,090 | /**
* P2. Reiziger DAO: persistentie van een klasse
*
* Deze methode test de CRUD-functionaliteit van de Reiziger DAO
*
* @throws SQLException
*/ | block_comment | nl | package DP_OV_Chipkaart;
import DP_OV_Chipkaart.Connections.ConnectionDatabase;
import DP_OV_Chipkaart.Dao.AdresDao;
import DP_OV_Chipkaart.Dao.OvChipkaartDao;
import DP_OV_Chipkaart.Dao.ProductDao;
import DP_OV_Chipkaart.Dao.ReizigerDao;
import DP_OV_Chipkaart.DaoPsql.AdresDAOPsql;
import DP_OV_Chipkaart.DaoPsql.OvChipKaartDaoPsql;
import DP_OV_Chipkaart.DaoPsql.ProductDaoPsql;
import DP_OV_Chipkaart.DaoPsql.ReizigerDAOPsql;
import DP_OV_Chipkaart.Domain.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
public class Main {
public static void main(String [] args) throws Exception {
java.util.Date utilDate = new java.util.Date();
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
System.out.println(sqlDate);
//P1
ConnectionDatabase.ConnectionDatabaseIsntance connection = new ConnectionDatabase.ConnectionDatabaseIsntance();
String q = "SELECT reiziger_id, voorletters, tussenvoegsel, achternaam, geboortedatum FROM reiziger";
PreparedStatement pst = connection.getConnection().prepareStatement(q);
ResultSet resultSet = pst.executeQuery();
while(resultSet.next()){
int reiziger_id = resultSet.getInt(1);
String voorletters = resultSet.getString(2);
String tussenvoegsel = resultSet.getString(3);
String achternaam = resultSet.getString(4);
java.sql.Date geboorteDatum = resultSet.getDate(5);
System.out.println(reiziger_id + " " + voorletters + " " + (tussenvoegsel == null ? "" : tussenvoegsel) + " " + achternaam + " (" + geboorteDatum + ")");
}
pst.close();
ProductDaoPsql productDao = new ProductDaoPsql(connection, null);
OvChipKaartDaoPsql ovChipkaartDao = new OvChipKaartDaoPsql(connection, productDao, null);
AdresDAOPsql adressDAOPsql = new AdresDAOPsql(connection);
ReizigerDAOPsql daoReiziger = new ReizigerDAOPsql(connection, adressDAOPsql, ovChipkaartDao);
productDao.setOvChipKaartDao(ovChipkaartDao);
adressDAOPsql.setReizigerDAOPsql(daoReiziger);
// testReizigerDAO(daoReiziger);
//testReizigerP3(daoReiziger, adressDAOPsql);
ovChipkaartDao.setReizigerDAOPsql(daoReiziger);
testp5(productDao, ovChipkaartDao);
connection.getConnection().close();
}
/**
* P2. Reiziger DAO:<SUF>*/
private static void testReizigerDAO(ReizigerDao rdao) throws Exception {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
System.out.println();
// Maak een nieuwe reiziger aan en persisteer deze in de database
String gbdatum = "1981-03-14";
Reiziger sietske = new Reiziger(77, "S", "", "Boers", java.sql.Date.valueOf(gbdatum), null);
System.out.println(sietske.toString());
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers\n");
System.out.println("het is zijn trouwdag en sietske krijgt een extra achernaam ");
sietske.setAchternaam("Broers-Oranje");
rdao.update(sietske);
System.out.println(rdao.findById(sietske.getId()));
reizigers = rdao.findAll();
System.out.println("reizigers voor ReizigerDAO.delete(): " + reizigers.size() + "\n");
rdao.delete(sietske);
reizigers = rdao.findAll();
System.out.println(" reizigers na ReizigerDAO.delete() : "+ reizigers.size() + " reizigers\n");
System.out.println(rdao.findById(sietske.getId()));
}
private static void testReizigerP3(ReizigerDao rdao, AdresDao adao) throws Exception {
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r.toString());
}
System.out.println();
Reiziger reiziger = rdao.findById(1);
System.out.println(reiziger);
Adres backupAdres = reiziger.getAdress();
System.out.println("De reiziger gaat naar Groot Britanie verhuizen");
Adres adres = new Adres(25, "1122BB", "22", "Diagon Alley", "London", reiziger);
reiziger.setAdress(adres);
rdao.update(reiziger);
reiziger = rdao.findById(1);
System.out.println(reiziger.toString());
System.out.print("De reiziger gaat wordt premie: ");
adres.setStraat("Downing street");
adao.update(adres);
reiziger = rdao.findById(1);
System.out.println(reiziger);
System.out.println("test adao.findByReiziger: " + adao.findByReiziger(reiziger));
//brexit, terug naar nederland dan maar weer
reiziger.setAdress(backupAdres);
rdao.update(reiziger);
System.out.println();
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:");
for (Adres a : adressen) {
System.out.println(a.toString());
}
System.out.println();
}
private static void testp5(ProductDao pdao, OvChipkaartDao ovChipkaartDao) throws Exception {
for(OvChipKaart ovChipKaart : ovChipkaartDao.findAll()){
System.out.println(ovChipKaart.toString());
}
for(Product product : pdao.findAll()){
System.out.println(product.toString());
}
}
}
|
192487_8 |
public class Loops {
public static void main(String[] args) {
// 1.
// Can't use incompatible data types in the initialization blocks
// (Syntax error on token "int", delete this token)
// for( long y=0, int x=0; y<6; y++) {
// }
// 2.
// Can't use a comma in the conditional block of for loop
// (Syntax error on token ",", . expected)
// int j=8;
// for( int i = 0; i<6, j>7; i++) {}
// 3.
// while in do-while should have braces
// boolean keepGoing = true;
// int result = 15, meters = 10;
// do{
// meters--;
// if(meters==8) keepGoing = false;
// result -= 2;
// } while keepGoing;
// System.out.println(result);
// 4.
// Normal brak logic
var ostrich = new Character[]{'A', 'B', 'C'};
var ostrich1 = new Character[]{'D', 'E', 'F'};
L1: for( var emu : ostrich ) {
System.out.println("outer " + emu);
L2: for( var emu1: ostrich1 ) {
System.out.println("Inner " + emu1);
break L2;
}
}
// 5.
// bad else and else if
if(true)
System.out.println("hell");
else
System.out.println("hell");
// else if ( false )
}
}
| ravi2519/JavaCertification | basics/Loops.java | 470 | // int result = 15, meters = 10;
| line_comment | nl |
public class Loops {
public static void main(String[] args) {
// 1.
// Can't use incompatible data types in the initialization blocks
// (Syntax error on token "int", delete this token)
// for( long y=0, int x=0; y<6; y++) {
// }
// 2.
// Can't use a comma in the conditional block of for loop
// (Syntax error on token ",", . expected)
// int j=8;
// for( int i = 0; i<6, j>7; i++) {}
// 3.
// while in do-while should have braces
// boolean keepGoing = true;
// int result<SUF>
// do{
// meters--;
// if(meters==8) keepGoing = false;
// result -= 2;
// } while keepGoing;
// System.out.println(result);
// 4.
// Normal brak logic
var ostrich = new Character[]{'A', 'B', 'C'};
var ostrich1 = new Character[]{'D', 'E', 'F'};
L1: for( var emu : ostrich ) {
System.out.println("outer " + emu);
L2: for( var emu1: ostrich1 ) {
System.out.println("Inner " + emu1);
break L2;
}
}
// 5.
// bad else and else if
if(true)
System.out.println("hell");
else
System.out.println("hell");
// else if ( false )
}
}
|
201647_7 |
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import Utility.Book;
import Utility.Patron;
import Utility.Librery;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//book title,authors and isbn10 in the form of array
String [] book_title = { "The Hunger Games" , "Harry Potter and the Philosopher's Stone" , "Twilight" , "To Kill a Mockingbird" , "The Great Gatsby" , "The Fault in Our Stars" , "The Hobbit or There and Back Again" , "The Catcher in the Rye" , "Angels & Demons " , "Pride and Prejudice" , "The Kite Runner " , "Divergent" , "Nineteen Eighty-Four" , "Animal Farm: A Fairy Story" , "Het Achterhuis: Dagboekbrieven 14 juni 1942 - 1 augustus 1944" , "Män som hatar kvinnor" , "Catching Fire" , "Harry Potter and the Prisoner of Azkaban" , " The Fellowship of the Ring" , "Mockingjay" };
String [] authors = { "Suzanne Collins" , "J.K. Rowling, Mary GrandPré" , "Stephenie Meyer" , "Harper Lee" , "F. Scott Fitzgerald" , "John Green" , "J.R.R. Tolkien" , "J.D. Salinger" , "Dan Brown" , "Jane Austen" , "Khaled Hosseini" , "Veronica Roth" , "George Orwell, Erich Fromm, Celâl Üster" , "George Orwell" , "Anne Frank, Eleanor Roosevelt, B.M. Mooyaart-Doubleday" , "Stieg Larsson, Reg Keeland" , "Suzanne Collins" , "J.K. Rowling, Mary GrandPré, Rufus Beck" , "J.R.R. Tolkien" , "Suzanne Collins" };
String [] isbn10 = { "439023483" , "439554934" , "316015849" , "61120081" , "743273567" , "525478817" , "618260307" , "316769177" , "1416524797" , "679783261" , "1594480001" , "62024035" , "451524934" , "452284244" , "553296981" , "307269752" , "439023491" , "043965548X" , "618346252" , "439023513" };
//lists to Book object
LinkedList<Book> bookDetails = new LinkedList<Book>();
for(int i=0;i < book_title.length;i++){
Book book = new Book();
book.setTitle( book_title[i]);
book.setAuthor(authors[i]);
book.setIsbn( isbn10[i]);
bookDetails.add(book);
}
//adding Books to librery
Librery librery = new Librery();
for(int i =0; i < bookDetails.size();i++){
librery.addBook(bookDetails.get(i));}
System.out.println(" Welcome to RK LIBRERY \n Explore the world of books, knowledge, and imagination!");
Scanner selector = new Scanner(System.in);
String flag = "run";
while (!(flag.equals("exit"))){
System.out.println("\n \nAre you librerian[L] or reader[R] or want exit[exit]?");
String selection = selector.nextLine();
flag = selection;
if(selection.equals("R")){
/*reader code */
System.out.println("Are you a member of this librery? [Y] or [N]");
String isMember = selector.nextLine();
if(isMember.equals("N")){
System.out.println("Take membership for this librery .");
/*new membership code */
Patron newPatron = new Patron();
System.out.println("Enter Your name :");
String new_name = selector.nextLine();
newPatron.setName(new_name);
int new_id = librery.patronList.size() + 1;
newPatron.setId(new_id);
librery.AddPatron(newPatron);
System.out.println("\nCongrats " + newPatron.getName() + "\nyou are a member of librery! you can lend books");
System.out.println("\nNote this id card for future use");
System.out.println(" RK LIBRERY \nName :" + new_name + "\nId : " + newPatron.getId());
}else if(isMember.equals("Y")){
/*check membership */
System.out.println("Give Your name and id");
String name_string = selector.nextLine();
int id_number = selector.nextInt();
if(id_number <= librery.patronList.size()){
//verified patron code
int verified_id = librery.checkPatron(name_string,id_number);
if(verified_id > 0){
Patron verified = librery.patronList.get(verified_id - 1);
System.out.println("\nYou are verified!\n");
System.out.println("Select option \n 1 : for lending book\n 2 : for return book");
int memberAction = selector.nextInt();
if(memberAction == 1){
//book lending
System.out.println("\nSelect the book:");
librery.showBookShelf();
int selected_book_id = selector.nextInt();
selector.nextLine();
if(selected_book_id <= librery.bookShelf.size()){
Book selected_book = librery.bookShelf.get(selected_book_id - 1);
System.out.println("\n \nYou picked the book!");
selected_book.display();
librery.lendBook(selected_book,verified);
verified.borrowBook(selected_book);
System.out.println("\nThe book " + selected_book.getTitle() + " is lended to " + verified.getName());
System.out.println("Happy reading!");
}else{
System.out.println("Enter a valied Number ");}
}else if(memberAction == 2){
//book return code
System.out.println("\n \nWhich book you want to return?");
int count = 1;
for(Book book:verified.borrowedBooks){
System.out.println(count + " : for " +book.getTitle());
count++;
}
int returnBookIndex = selector.nextInt();
selector.nextLine();
Book returningBook = verified.borrowedBooks.get(returnBookIndex - 1);
verified.returnBook(returningBook);
librery.acceptBook(returningBook);
System.out.println("The book "+ returningBook.getTitle() + " is accepted from " + verified.getName() );
System.out.println("I hope you enjoyed the book!");
}
}else{
System.out.println("Enter valied Information or get menbership");
}
}
}
}else if (selection.equals("L")){
//librerian code
System.out.println("Select options: \n 1 : Add book \n 2 : View Bookshelf");
String LibrerianChoice = selector.nextLine();
if(LibrerianChoice.equals("1")){
//add book code
System.out.println("Book title :");
String new_title = selector.nextLine();
System.out.println("Author :");
String new_author = selector.nextLine();
System.out.println("Isbn10 :");
String new_isbn = selector.nextLine();
Book new_book = new Book();
new_book.setTitle(new_title);
new_book.setAuthor(new_author);
new_book.setIsbn(new_isbn);
librery.addBook(new_book);
System.out.println(new_book.getTitle() + "is added succusfully");
}else if(LibrerianChoice.equals("2")){
librery.showBookShelf();
}
}
}//while loop ends here
selector.close();
}
} | ravibalebilalu/librery_management | App.java | 2,286 | //while loop ends here | line_comment | nl |
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import Utility.Book;
import Utility.Patron;
import Utility.Librery;
import java.util.Scanner;
public class App {
public static void main(String[] args) {
//book title,authors and isbn10 in the form of array
String [] book_title = { "The Hunger Games" , "Harry Potter and the Philosopher's Stone" , "Twilight" , "To Kill a Mockingbird" , "The Great Gatsby" , "The Fault in Our Stars" , "The Hobbit or There and Back Again" , "The Catcher in the Rye" , "Angels & Demons " , "Pride and Prejudice" , "The Kite Runner " , "Divergent" , "Nineteen Eighty-Four" , "Animal Farm: A Fairy Story" , "Het Achterhuis: Dagboekbrieven 14 juni 1942 - 1 augustus 1944" , "Män som hatar kvinnor" , "Catching Fire" , "Harry Potter and the Prisoner of Azkaban" , " The Fellowship of the Ring" , "Mockingjay" };
String [] authors = { "Suzanne Collins" , "J.K. Rowling, Mary GrandPré" , "Stephenie Meyer" , "Harper Lee" , "F. Scott Fitzgerald" , "John Green" , "J.R.R. Tolkien" , "J.D. Salinger" , "Dan Brown" , "Jane Austen" , "Khaled Hosseini" , "Veronica Roth" , "George Orwell, Erich Fromm, Celâl Üster" , "George Orwell" , "Anne Frank, Eleanor Roosevelt, B.M. Mooyaart-Doubleday" , "Stieg Larsson, Reg Keeland" , "Suzanne Collins" , "J.K. Rowling, Mary GrandPré, Rufus Beck" , "J.R.R. Tolkien" , "Suzanne Collins" };
String [] isbn10 = { "439023483" , "439554934" , "316015849" , "61120081" , "743273567" , "525478817" , "618260307" , "316769177" , "1416524797" , "679783261" , "1594480001" , "62024035" , "451524934" , "452284244" , "553296981" , "307269752" , "439023491" , "043965548X" , "618346252" , "439023513" };
//lists to Book object
LinkedList<Book> bookDetails = new LinkedList<Book>();
for(int i=0;i < book_title.length;i++){
Book book = new Book();
book.setTitle( book_title[i]);
book.setAuthor(authors[i]);
book.setIsbn( isbn10[i]);
bookDetails.add(book);
}
//adding Books to librery
Librery librery = new Librery();
for(int i =0; i < bookDetails.size();i++){
librery.addBook(bookDetails.get(i));}
System.out.println(" Welcome to RK LIBRERY \n Explore the world of books, knowledge, and imagination!");
Scanner selector = new Scanner(System.in);
String flag = "run";
while (!(flag.equals("exit"))){
System.out.println("\n \nAre you librerian[L] or reader[R] or want exit[exit]?");
String selection = selector.nextLine();
flag = selection;
if(selection.equals("R")){
/*reader code */
System.out.println("Are you a member of this librery? [Y] or [N]");
String isMember = selector.nextLine();
if(isMember.equals("N")){
System.out.println("Take membership for this librery .");
/*new membership code */
Patron newPatron = new Patron();
System.out.println("Enter Your name :");
String new_name = selector.nextLine();
newPatron.setName(new_name);
int new_id = librery.patronList.size() + 1;
newPatron.setId(new_id);
librery.AddPatron(newPatron);
System.out.println("\nCongrats " + newPatron.getName() + "\nyou are a member of librery! you can lend books");
System.out.println("\nNote this id card for future use");
System.out.println(" RK LIBRERY \nName :" + new_name + "\nId : " + newPatron.getId());
}else if(isMember.equals("Y")){
/*check membership */
System.out.println("Give Your name and id");
String name_string = selector.nextLine();
int id_number = selector.nextInt();
if(id_number <= librery.patronList.size()){
//verified patron code
int verified_id = librery.checkPatron(name_string,id_number);
if(verified_id > 0){
Patron verified = librery.patronList.get(verified_id - 1);
System.out.println("\nYou are verified!\n");
System.out.println("Select option \n 1 : for lending book\n 2 : for return book");
int memberAction = selector.nextInt();
if(memberAction == 1){
//book lending
System.out.println("\nSelect the book:");
librery.showBookShelf();
int selected_book_id = selector.nextInt();
selector.nextLine();
if(selected_book_id <= librery.bookShelf.size()){
Book selected_book = librery.bookShelf.get(selected_book_id - 1);
System.out.println("\n \nYou picked the book!");
selected_book.display();
librery.lendBook(selected_book,verified);
verified.borrowBook(selected_book);
System.out.println("\nThe book " + selected_book.getTitle() + " is lended to " + verified.getName());
System.out.println("Happy reading!");
}else{
System.out.println("Enter a valied Number ");}
}else if(memberAction == 2){
//book return code
System.out.println("\n \nWhich book you want to return?");
int count = 1;
for(Book book:verified.borrowedBooks){
System.out.println(count + " : for " +book.getTitle());
count++;
}
int returnBookIndex = selector.nextInt();
selector.nextLine();
Book returningBook = verified.borrowedBooks.get(returnBookIndex - 1);
verified.returnBook(returningBook);
librery.acceptBook(returningBook);
System.out.println("The book "+ returningBook.getTitle() + " is accepted from " + verified.getName() );
System.out.println("I hope you enjoyed the book!");
}
}else{
System.out.println("Enter valied Information or get menbership");
}
}
}
}else if (selection.equals("L")){
//librerian code
System.out.println("Select options: \n 1 : Add book \n 2 : View Bookshelf");
String LibrerianChoice = selector.nextLine();
if(LibrerianChoice.equals("1")){
//add book code
System.out.println("Book title :");
String new_title = selector.nextLine();
System.out.println("Author :");
String new_author = selector.nextLine();
System.out.println("Isbn10 :");
String new_isbn = selector.nextLine();
Book new_book = new Book();
new_book.setTitle(new_title);
new_book.setAuthor(new_author);
new_book.setIsbn(new_isbn);
librery.addBook(new_book);
System.out.println(new_book.getTitle() + "is added succusfully");
}else if(LibrerianChoice.equals("2")){
librery.showBookShelf();
}
}
}//while loop<SUF>
selector.close();
}
} |
142225_16 | /*
* Copyright 2015-2020 Ray Fowler
*
* Licensed under the GNU General Public License, Version 3 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0.html
*
* 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 rotp.model.ai;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import rotp.model.ai.interfaces.Diplomat;
import rotp.model.ai.interfaces.FleetCommander;
import rotp.model.ai.interfaces.General;
import rotp.model.ai.interfaces.Governor;
import rotp.model.ai.interfaces.Scientist;
import rotp.model.ai.interfaces.ShipCaptain;
import rotp.model.ai.interfaces.ShipDesigner;
import rotp.model.ai.interfaces.SpyMaster;
import rotp.model.ai.interfaces.Treasurer;
import rotp.model.colony.Colony;
import rotp.model.empires.Empire;
import rotp.model.empires.EmpireView;
import rotp.model.empires.SystemView;
import rotp.model.galaxy.IMappedObject;
import rotp.model.galaxy.ShipFleet;
import rotp.model.galaxy.StarSystem;
import rotp.model.planet.Planet;
import rotp.model.ships.ShipDesign;
import rotp.ui.UserPreferences;
import rotp.ui.notifications.BombardSystemNotification;
import rotp.ui.notifications.ColonizeSystemNotification;
import rotp.util.Base;
public class AI implements Base {
public static final int BASE = 0;
public static final int MODNAR = 1;
public static final int XILMI = 2;
private final Empire empire;
private final Diplomat diplomat;
private final General general;
private final FleetCommander fleetCommander;
private final Governor governor;
private final Scientist scientist;
private final ShipCaptain captain;
private final ShipDesigner shipDesigner;
private final SpyMaster spyMaster;
private final Treasurer treasurer;
public AI (Empire e, int aiType) {
empire = e;
switch(aiType) {
case MODNAR:
general = new rotp.model.ai.modnar.AIGeneral(empire);
captain = new rotp.model.ai.modnar.AIShipCaptain(empire);
governor = new rotp.model.ai.modnar.AIGovernor(empire);
scientist = new rotp.model.ai.modnar.AIScientist(empire);
diplomat = new rotp.model.ai.modnar.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.modnar.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.modnar.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.modnar.AISpyMaster(empire);
treasurer = new rotp.model.ai.modnar.AITreasurer(empire);
break;
case XILMI:
general = new rotp.model.ai.xilmi.AIGeneral(empire);
captain = new rotp.model.ai.xilmi.AIShipCaptain(empire);
governor = new rotp.model.ai.xilmi.AIGovernor(empire);
scientist = new rotp.model.ai.xilmi.AIScientist(empire);
diplomat = new rotp.model.ai.xilmi.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.xilmi.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.xilmi.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.xilmi.AISpyMaster(empire);
treasurer = new rotp.model.ai.xilmi.AITreasurer(empire);
break;
case BASE:
default:
general = new rotp.model.ai.base.AIGeneral(empire);
captain = new rotp.model.ai.base.AIShipCaptain(empire);
governor = new rotp.model.ai.base.AIGovernor(empire);
scientist = new rotp.model.ai.base.AIScientist(empire);
diplomat = new rotp.model.ai.base.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.base.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.base.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.base.AISpyMaster(empire);
treasurer = new rotp.model.ai.base.AITreasurer(empire);
break;
}
}
// MISC INTERFACE
public boolean isAI() { return empire.isAI(); }
public boolean isPlayer() { return empire.isPlayer(); }
// direct
public ShipCaptain shipCaptain() { return captain; }
public General general() { return general; }
public Diplomat diplomat() { return diplomat; }
public FleetCommander fleetCommander() { return fleetCommander; }
public Governor governor() { return governor; }
public Treasurer treasurer() { return treasurer; }
public Scientist scientist() { return scientist; }
public ShipDesigner shipDesigner() { return shipDesigner; }
public SpyMaster spyMaster() { return spyMaster; }
// uncategorized
public List<StarSystem> bestSystemsForInvasion(EmpireView v) {
// invoked when going to war
List<StarSystem> systems = empire.systemsInShipRange(v.empire());
Collections.sort(systems,StarSystem.INVASION_PRIORITY);
return systems;
}
private int popNeeded(int sysId, float pct) {
if (empire.sv.missing(sysId))
return 0;
StarSystem sys = empire.sv.view(sysId).system();
Colony col = sys.colony();
if (col == null)
return 0;
return col.calcPopNeeded(pct);
}
private ColonyTransporter createColony(StarSystem sys, int minTransports) {
int sysId = id(sys);
float targetPct = empire.governorAI().targetPopPct(sysId);
int popNeeded = popNeeded(sysId, targetPct);
int maxPopToGive = (int) empire.sv.maxPopToGive(sysId, targetPct);
if ((popNeeded < minTransports) && (maxPopToGive < minTransports))
return null;
return new ColonyTransporter(sys.colony(), popNeeded, maxPopToGive, minTransports);
}
public void sendTransports() {
long tm0 = System.currentTimeMillis();
int minTransportSize = empire.generalAI().minTransportSize();
List<ColonyTransporter> needy = new ArrayList<>();
List<ColonyTransporter> givey = new ArrayList<>();
for (StarSystem sys: empire.allColonizedSystems()) {
ColonyTransporter col = createColony(sys, minTransportSize);
if (col != null) {
if ((col.popNeeded >= minTransportSize) && (col.popNeeded >= col.maxPopToGive))
needy.add(col);
else if ((col.maxPopToGive >= minTransportSize) && (col.maxPopToGive > col.popNeeded))
givey.add(col);
}
}
if (needy.isEmpty() || givey.isEmpty()) {
log("sendTransports (NONE): "+empire.raceName()+" "+(System.currentTimeMillis()-tm0)+"ms");
return;
}
Collections.sort(needy,TRANSPORT_PRIORITY);
for(ColonyTransporter needer : needy)
{
TARGET_COLONY = needer;
Collections.sort(givey,DISTANCE_TO_TARGET);
boolean allGiversBusy = true;
for(ColonyTransporter giver : givey)
{
if(giver.colony.transport().size() > 0)
continue;
allGiversBusy = false;
float allowableTurns = (float) (1 + Math.min(7, Math.floor(22 / empire.tech().topSpeed())));
float travelTime = giver.colony.transport().travelTime(needer.colony.starSystem());
if ((giver.maxPopToGive >= minTransportSize) && (giver.transportPriority < needer.transportPriority)
&& travelTime <= allowableTurns) {
float needed = needer.popNeeded - ((int) (Math.ceil(giver.transportTimeTo(needer))) * needer.growth);
int trPop = (int) min(needed, giver.maxPopToGive);
if (trPop >= minTransportSize) {
giver.sendTransportsTo(needer, trPop);
}
}
}
if(allGiversBusy)
break;
}
long tm1 = System.currentTimeMillis();
log("sendTransports: "+empire.raceName()+" "+(tm1-tm0)+"ms");
}
public void checkColonize(StarSystem sys, ShipFleet fl) {
if (fl.retreating())
return;
if (sys.orbitingShipsInConflict())
return;
if (sys.colony() != null)
return;
if (!empire.canColonize(sys.planet().type()))
return;
ShipDesign bestDesign = shipDesigner().bestDesignToColonize(fl, sys);
// if no useable colony design, exit
if (bestDesign == null)
return;
// AT THIS POINT, the fleet can definitely colonize the planet
// confirm if player controlled & if colonize prompt is disabled
if (empire.isAIControlled() || UserPreferences.autoColonize())
fl.colonizeSystem(sys, bestDesign);
else
ColonizeSystemNotification.create(sys.id, fl, bestDesign);
}
public boolean promptForBombardment(StarSystem sys, ShipFleet fl) {
// if player, prompt for decision to bomb instead of deciding here
if (empire.isPlayerControlled()) {
if (UserPreferences.autoBombardNever())
return false;
boolean autoBomb = false;
// user preference auto-bombard set to always?
if (UserPreferences.autoBombardYes())
autoBomb = true;
// auto-bombard set to whenever at war?
boolean atWar = empire.atWarWith(sys.empId());
if (UserPreferences.autoBombardWar() && atWar)
autoBomb = true;
// auto-bombard set to whenever at war and not invading?
int transports = empire.transportsInTransit(sys);
if (UserPreferences.autoBombardInvading() && atWar && (transports == 0))
autoBomb = true;
BombardSystemNotification.create(id(sys), fl, autoBomb);
return false;
}
// ail: asking our general for permission
if(!empire.generalAI().allowedToBomb(sys))
return false;
// estimate bombardment damage and resulting population loss
float damage = fl.expectedBombardDamage();
float popLoss = damage / 200;
float sysPop = empire.sv.population(id(sys));
// if colony will NOT be destroyed, then bombs away!
if (popLoss < (sysPop * .9))
return true;
// determine number of troops in transit
int transports = empire.transportsInTransit(sys);
// if none in transit, then bombs away!
if (transports < 1)
return true;
// determine population troop loss in combat
float killRatio = empire.troopKillRatio(sys);
// if troops in transit CANNOT capture planet and will die anyway, then bombs away!
if ((transports * killRatio) < sysPop)
return true;
// else don't bomb
return false;
}
private float targetPopPct(SystemView sv) {
if (sv.borderSystem()) return .75f;
Planet pl = sv.system().planet();
if (pl.isResourceRich()) return .75f;
if (pl.isResourceUltraRich()) return .75f;
if (pl.isArtifact()) return .75f;
if (pl.isOrionArtifact()) return .75f;
if (pl.currentSize() <= 20) return .75f;
if (sv.supportSystem()) return .5f;
if (pl.currentSize() <= 40) return .5f;
return .25f;
}
class ColonyTransporter implements IMappedObject {
Colony colony;
float x, y;
float transportPriority;
float growth;
int popNeeded;
int maxPopToGive;
public ColonyTransporter(Colony c, int needs, int gives, int min) {
colony = c;
StarSystem sys = c.starSystem();
x = sys.x();
y = sys.y();
popNeeded = needs;
maxPopToGive = gives;
// calc these values only for needy colonies
if ((popNeeded >= min) && (popNeeded >= maxPopToGive)) {
transportPriority = c.empire().fleetCommanderAI().transportPriority(sys);
growth = c.normalPopGrowth();
}
}
@Override
public float x() { return x; }
@Override
public float y() { return y; }
public float transportTimeTo(ColonyTransporter dest) {
return colony.starSystem().transportTimeTo(dest.colony.starSystem());
}
public void sendTransportsTo(ColonyTransporter dest, int trPop) {
colony.scheduleTransportsToSystem(dest.colony.starSystem(), trPop);
maxPopToGive = 0;
dest.popNeeded -= trPop;
}
}
public static Comparator<ColonyTransporter> TRANSPORT_PRIORITY = (ColonyTransporter col1, ColonyTransporter col2) -> Base.compare(col1.transportPriority,col2.transportPriority);
public static ColonyTransporter TARGET_COLONY;
public static Comparator<ColonyTransporter> DISTANCE_TO_TARGET = new Comparator<ColonyTransporter>() {
@Override
public int compare(ColonyTransporter sys1, ColonyTransporter sys2) {
float pr1 = sys1.distanceTo(TARGET_COLONY);
float pr2 = sys2.distanceTo(TARGET_COLONY);
return Base.compare(pr1, pr2);
}
};
}
| rayfowler/rotp-public | src/rotp/model/ai/AI.java | 4,212 | // else don't bomb | line_comment | nl | /*
* Copyright 2015-2020 Ray Fowler
*
* Licensed under the GNU General Public License, Version 3 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/gpl-3.0.html
*
* 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 rotp.model.ai;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import rotp.model.ai.interfaces.Diplomat;
import rotp.model.ai.interfaces.FleetCommander;
import rotp.model.ai.interfaces.General;
import rotp.model.ai.interfaces.Governor;
import rotp.model.ai.interfaces.Scientist;
import rotp.model.ai.interfaces.ShipCaptain;
import rotp.model.ai.interfaces.ShipDesigner;
import rotp.model.ai.interfaces.SpyMaster;
import rotp.model.ai.interfaces.Treasurer;
import rotp.model.colony.Colony;
import rotp.model.empires.Empire;
import rotp.model.empires.EmpireView;
import rotp.model.empires.SystemView;
import rotp.model.galaxy.IMappedObject;
import rotp.model.galaxy.ShipFleet;
import rotp.model.galaxy.StarSystem;
import rotp.model.planet.Planet;
import rotp.model.ships.ShipDesign;
import rotp.ui.UserPreferences;
import rotp.ui.notifications.BombardSystemNotification;
import rotp.ui.notifications.ColonizeSystemNotification;
import rotp.util.Base;
public class AI implements Base {
public static final int BASE = 0;
public static final int MODNAR = 1;
public static final int XILMI = 2;
private final Empire empire;
private final Diplomat diplomat;
private final General general;
private final FleetCommander fleetCommander;
private final Governor governor;
private final Scientist scientist;
private final ShipCaptain captain;
private final ShipDesigner shipDesigner;
private final SpyMaster spyMaster;
private final Treasurer treasurer;
public AI (Empire e, int aiType) {
empire = e;
switch(aiType) {
case MODNAR:
general = new rotp.model.ai.modnar.AIGeneral(empire);
captain = new rotp.model.ai.modnar.AIShipCaptain(empire);
governor = new rotp.model.ai.modnar.AIGovernor(empire);
scientist = new rotp.model.ai.modnar.AIScientist(empire);
diplomat = new rotp.model.ai.modnar.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.modnar.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.modnar.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.modnar.AISpyMaster(empire);
treasurer = new rotp.model.ai.modnar.AITreasurer(empire);
break;
case XILMI:
general = new rotp.model.ai.xilmi.AIGeneral(empire);
captain = new rotp.model.ai.xilmi.AIShipCaptain(empire);
governor = new rotp.model.ai.xilmi.AIGovernor(empire);
scientist = new rotp.model.ai.xilmi.AIScientist(empire);
diplomat = new rotp.model.ai.xilmi.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.xilmi.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.xilmi.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.xilmi.AISpyMaster(empire);
treasurer = new rotp.model.ai.xilmi.AITreasurer(empire);
break;
case BASE:
default:
general = new rotp.model.ai.base.AIGeneral(empire);
captain = new rotp.model.ai.base.AIShipCaptain(empire);
governor = new rotp.model.ai.base.AIGovernor(empire);
scientist = new rotp.model.ai.base.AIScientist(empire);
diplomat = new rotp.model.ai.base.AIDiplomat(empire);
shipDesigner = new rotp.model.ai.base.AIShipDesigner(empire);
fleetCommander = new rotp.model.ai.base.AIFleetCommander(empire);
spyMaster = new rotp.model.ai.base.AISpyMaster(empire);
treasurer = new rotp.model.ai.base.AITreasurer(empire);
break;
}
}
// MISC INTERFACE
public boolean isAI() { return empire.isAI(); }
public boolean isPlayer() { return empire.isPlayer(); }
// direct
public ShipCaptain shipCaptain() { return captain; }
public General general() { return general; }
public Diplomat diplomat() { return diplomat; }
public FleetCommander fleetCommander() { return fleetCommander; }
public Governor governor() { return governor; }
public Treasurer treasurer() { return treasurer; }
public Scientist scientist() { return scientist; }
public ShipDesigner shipDesigner() { return shipDesigner; }
public SpyMaster spyMaster() { return spyMaster; }
// uncategorized
public List<StarSystem> bestSystemsForInvasion(EmpireView v) {
// invoked when going to war
List<StarSystem> systems = empire.systemsInShipRange(v.empire());
Collections.sort(systems,StarSystem.INVASION_PRIORITY);
return systems;
}
private int popNeeded(int sysId, float pct) {
if (empire.sv.missing(sysId))
return 0;
StarSystem sys = empire.sv.view(sysId).system();
Colony col = sys.colony();
if (col == null)
return 0;
return col.calcPopNeeded(pct);
}
private ColonyTransporter createColony(StarSystem sys, int minTransports) {
int sysId = id(sys);
float targetPct = empire.governorAI().targetPopPct(sysId);
int popNeeded = popNeeded(sysId, targetPct);
int maxPopToGive = (int) empire.sv.maxPopToGive(sysId, targetPct);
if ((popNeeded < minTransports) && (maxPopToGive < minTransports))
return null;
return new ColonyTransporter(sys.colony(), popNeeded, maxPopToGive, minTransports);
}
public void sendTransports() {
long tm0 = System.currentTimeMillis();
int minTransportSize = empire.generalAI().minTransportSize();
List<ColonyTransporter> needy = new ArrayList<>();
List<ColonyTransporter> givey = new ArrayList<>();
for (StarSystem sys: empire.allColonizedSystems()) {
ColonyTransporter col = createColony(sys, minTransportSize);
if (col != null) {
if ((col.popNeeded >= minTransportSize) && (col.popNeeded >= col.maxPopToGive))
needy.add(col);
else if ((col.maxPopToGive >= minTransportSize) && (col.maxPopToGive > col.popNeeded))
givey.add(col);
}
}
if (needy.isEmpty() || givey.isEmpty()) {
log("sendTransports (NONE): "+empire.raceName()+" "+(System.currentTimeMillis()-tm0)+"ms");
return;
}
Collections.sort(needy,TRANSPORT_PRIORITY);
for(ColonyTransporter needer : needy)
{
TARGET_COLONY = needer;
Collections.sort(givey,DISTANCE_TO_TARGET);
boolean allGiversBusy = true;
for(ColonyTransporter giver : givey)
{
if(giver.colony.transport().size() > 0)
continue;
allGiversBusy = false;
float allowableTurns = (float) (1 + Math.min(7, Math.floor(22 / empire.tech().topSpeed())));
float travelTime = giver.colony.transport().travelTime(needer.colony.starSystem());
if ((giver.maxPopToGive >= minTransportSize) && (giver.transportPriority < needer.transportPriority)
&& travelTime <= allowableTurns) {
float needed = needer.popNeeded - ((int) (Math.ceil(giver.transportTimeTo(needer))) * needer.growth);
int trPop = (int) min(needed, giver.maxPopToGive);
if (trPop >= minTransportSize) {
giver.sendTransportsTo(needer, trPop);
}
}
}
if(allGiversBusy)
break;
}
long tm1 = System.currentTimeMillis();
log("sendTransports: "+empire.raceName()+" "+(tm1-tm0)+"ms");
}
public void checkColonize(StarSystem sys, ShipFleet fl) {
if (fl.retreating())
return;
if (sys.orbitingShipsInConflict())
return;
if (sys.colony() != null)
return;
if (!empire.canColonize(sys.planet().type()))
return;
ShipDesign bestDesign = shipDesigner().bestDesignToColonize(fl, sys);
// if no useable colony design, exit
if (bestDesign == null)
return;
// AT THIS POINT, the fleet can definitely colonize the planet
// confirm if player controlled & if colonize prompt is disabled
if (empire.isAIControlled() || UserPreferences.autoColonize())
fl.colonizeSystem(sys, bestDesign);
else
ColonizeSystemNotification.create(sys.id, fl, bestDesign);
}
public boolean promptForBombardment(StarSystem sys, ShipFleet fl) {
// if player, prompt for decision to bomb instead of deciding here
if (empire.isPlayerControlled()) {
if (UserPreferences.autoBombardNever())
return false;
boolean autoBomb = false;
// user preference auto-bombard set to always?
if (UserPreferences.autoBombardYes())
autoBomb = true;
// auto-bombard set to whenever at war?
boolean atWar = empire.atWarWith(sys.empId());
if (UserPreferences.autoBombardWar() && atWar)
autoBomb = true;
// auto-bombard set to whenever at war and not invading?
int transports = empire.transportsInTransit(sys);
if (UserPreferences.autoBombardInvading() && atWar && (transports == 0))
autoBomb = true;
BombardSystemNotification.create(id(sys), fl, autoBomb);
return false;
}
// ail: asking our general for permission
if(!empire.generalAI().allowedToBomb(sys))
return false;
// estimate bombardment damage and resulting population loss
float damage = fl.expectedBombardDamage();
float popLoss = damage / 200;
float sysPop = empire.sv.population(id(sys));
// if colony will NOT be destroyed, then bombs away!
if (popLoss < (sysPop * .9))
return true;
// determine number of troops in transit
int transports = empire.transportsInTransit(sys);
// if none in transit, then bombs away!
if (transports < 1)
return true;
// determine population troop loss in combat
float killRatio = empire.troopKillRatio(sys);
// if troops in transit CANNOT capture planet and will die anyway, then bombs away!
if ((transports * killRatio) < sysPop)
return true;
// else don't<SUF>
return false;
}
private float targetPopPct(SystemView sv) {
if (sv.borderSystem()) return .75f;
Planet pl = sv.system().planet();
if (pl.isResourceRich()) return .75f;
if (pl.isResourceUltraRich()) return .75f;
if (pl.isArtifact()) return .75f;
if (pl.isOrionArtifact()) return .75f;
if (pl.currentSize() <= 20) return .75f;
if (sv.supportSystem()) return .5f;
if (pl.currentSize() <= 40) return .5f;
return .25f;
}
class ColonyTransporter implements IMappedObject {
Colony colony;
float x, y;
float transportPriority;
float growth;
int popNeeded;
int maxPopToGive;
public ColonyTransporter(Colony c, int needs, int gives, int min) {
colony = c;
StarSystem sys = c.starSystem();
x = sys.x();
y = sys.y();
popNeeded = needs;
maxPopToGive = gives;
// calc these values only for needy colonies
if ((popNeeded >= min) && (popNeeded >= maxPopToGive)) {
transportPriority = c.empire().fleetCommanderAI().transportPriority(sys);
growth = c.normalPopGrowth();
}
}
@Override
public float x() { return x; }
@Override
public float y() { return y; }
public float transportTimeTo(ColonyTransporter dest) {
return colony.starSystem().transportTimeTo(dest.colony.starSystem());
}
public void sendTransportsTo(ColonyTransporter dest, int trPop) {
colony.scheduleTransportsToSystem(dest.colony.starSystem(), trPop);
maxPopToGive = 0;
dest.popNeeded -= trPop;
}
}
public static Comparator<ColonyTransporter> TRANSPORT_PRIORITY = (ColonyTransporter col1, ColonyTransporter col2) -> Base.compare(col1.transportPriority,col2.transportPriority);
public static ColonyTransporter TARGET_COLONY;
public static Comparator<ColonyTransporter> DISTANCE_TO_TARGET = new Comparator<ColonyTransporter>() {
@Override
public int compare(ColonyTransporter sys1, ColonyTransporter sys2) {
float pr1 = sys1.distanceTo(TARGET_COLONY);
float pr2 = sys2.distanceTo(TARGET_COLONY);
return Base.compare(pr1, pr2);
}
};
}
|
207218_0 | package nl.youngcapital.movies.model;
/* zonder public of iets anders is package private oftewel indezelfde folder */
public class Movie {
public static String customerName = "Netflix";
// Encapsulation
private String name;
private int length;
private int stars;
public static int movieCounter = 0;
/*
Java heeft 8 primitives: the element of the periodic system
gehele getallen
- byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8)
- short => 16 bits < -32768 - 32767)
- int => 32 bits geheel getal (-2miljard tot +2 miljard)
- long => 64 bits geheel getal <
- letters:
- char 'a', 'b', 'z', 'q'
- waar of niet waar ... boolean
- true false
- floating points
-- float: 32 bits floating point number.... 1.2f, 2.3f
-- double: 64 bits floating point number 1.2, 2.3 1000.3343434;
// let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen.
*/
// new and constructor is a marriage
public Movie(String name) {
this.name = name;
movieCounter++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLength() {
return length;
}
// this is a 'method' and more specific: a 'setter'
public void setLength(int length) {
this.length = length;
}
// this is a 'method' and more specific: a 'getter'
public int getStars() {
return stars;
}
public void setStars(int stars) {
if (stars > 0 && stars <= 5) {
this.stars = stars;
}
}
}
| raymieloman/movies-oo | src/main/java/nl/youngcapital/movies/model/Movie.java | 524 | /* zonder public of iets anders is package private oftewel indezelfde folder */ | block_comment | nl | package nl.youngcapital.movies.model;
/* zonder public of<SUF>*/
public class Movie {
public static String customerName = "Netflix";
// Encapsulation
private String name;
private int length;
private int stars;
public static int movieCounter = 0;
/*
Java heeft 8 primitives: the element of the periodic system
gehele getallen
- byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8)
- short => 16 bits < -32768 - 32767)
- int => 32 bits geheel getal (-2miljard tot +2 miljard)
- long => 64 bits geheel getal <
- letters:
- char 'a', 'b', 'z', 'q'
- waar of niet waar ... boolean
- true false
- floating points
-- float: 32 bits floating point number.... 1.2f, 2.3f
-- double: 64 bits floating point number 1.2, 2.3 1000.3343434;
// let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen.
*/
// new and constructor is a marriage
public Movie(String name) {
this.name = name;
movieCounter++;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getLength() {
return length;
}
// this is a 'method' and more specific: a 'setter'
public void setLength(int length) {
this.length = length;
}
// this is a 'method' and more specific: a 'getter'
public int getStars() {
return stars;
}
public void setStars(int stars) {
if (stars > 0 && stars <= 5) {
this.stars = stars;
}
}
}
|
24577_6 |
package nl.consumergram.consumergramv2.services;
import jakarta.persistence.EntityNotFoundException;
import nl.consumergram.consumergramv2.dtos.UserDto;
import nl.consumergram.consumergramv2.models.User;
import nl.consumergram.consumergramv2.repositories.UserRepository;
import nl.consumergram.consumergramv2.utils.RandomStringGenerator;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
public PasswordEncoder passwordEncoder;
// De constructor injecteert een instantie van UserRepository
private final UserRepository userRepository;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
// // Opslaan van het versleutelde wachtwoord in de database of ergens anders
// userRepository.save(new User(UserDto.getUsername(), encodedPassword));
// }
public List<UserDto> getUsers() {
List<UserDto> collection = new ArrayList<>();
List<User> list = userRepository.findAll();
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
// Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto
public UserDto getUser(String username) {
UserDto dto = new UserDto();
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUser(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
// Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat.
public boolean userExists(String username) {
return userRepository.existsById(username);
}
// Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug.
public String createUser(UserDto userDto) {
String randomString = RandomStringGenerator.generateAlphaNumeric(20);
userDto.setApikey(randomString);
User newUser = userRepository.save(toUser(userDto));
return newUser.getUsername();
}
// Verwijdert een gebruiker op basis van de gebruikersnaam.
public void deleteUser(String username) {
userRepository.deleteById(username);
}
public UserDto updateUser(String username, UserDto dto) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new EntityNotFoundException("User not found with username " + username));
user.setEmail(dto.getEmail());
user.setUsername(dto.getUsername());
// Check if the password field in the incoming UserDto is null or empty
if (dto.getPassword() != null && !dto.getPassword().isEmpty()) {
user.setPassword(passwordEncoder.encode(dto.getPassword()));
}
User updatedUser = userRepository.save(user);
UserDto updatedUserDto = convertToDto(updatedUser);
return updatedUserDto;
}
public UserDto convertToDto(User user) {
UserDto userDto = new UserDto();
userDto.setUsername(user.getUsername());
userDto.setPassword(user.getPassword());
userDto.setEnabled(user.isEnabled());
userDto.setApikey(user.getApikey());
userDto.setEmail(user.getEmail());
userDto.setAuthorities(user.getAuthorities());
return userDto;
}
// Zet een User-object om naar een UserDto
public static UserDto fromUser(User user) {
var dto = new UserDto();
// In de code lijkt getUsername() de
// gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke
// identificator voor een gebruiker.
dto.username = user.getUsername();
dto.password = user.getPassword();
dto.enabled = user.isEnabled();
dto.apikey = user.getApikey();
dto.email = user.getEmail();
dto.authorities = user.getAuthorities();
return dto;
}
// Zet een UserDto-object om naar een User.
public User toUser(UserDto userDto) {
var user = new User();
user.setUsername(userDto.getUsername());
user.setPassword(passwordEncoder.encode(userDto.password));
// user.setPassword(userDto.getPassword());
user.setEnabled(userDto.getEnabled());
user.setApikey(userDto.getApikey());
user.setEmail(userDto.getEmail());
return user;
}
} | rayzathegrave/ConsumerGramBackendv2 | src/main/java/nl/consumergram/consumergramv2/services/UserService.java | 1,406 | // Verwijdert een gebruiker op basis van de gebruikersnaam. | line_comment | nl |
package nl.consumergram.consumergramv2.services;
import jakarta.persistence.EntityNotFoundException;
import nl.consumergram.consumergramv2.dtos.UserDto;
import nl.consumergram.consumergramv2.models.User;
import nl.consumergram.consumergramv2.repositories.UserRepository;
import nl.consumergram.consumergramv2.utils.RandomStringGenerator;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
public PasswordEncoder passwordEncoder;
// De constructor injecteert een instantie van UserRepository
private final UserRepository userRepository;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
}
// // Opslaan van het versleutelde wachtwoord in de database of ergens anders
// userRepository.save(new User(UserDto.getUsername(), encodedPassword));
// }
public List<UserDto> getUsers() {
List<UserDto> collection = new ArrayList<>();
List<User> list = userRepository.findAll();
for (User user : list) {
collection.add(fromUser(user));
}
return collection;
}
// Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto
public UserDto getUser(String username) {
UserDto dto = new UserDto();
Optional<User> user = userRepository.findById(username);
if (user.isPresent()) {
dto = fromUser(user.get());
} else {
throw new UsernameNotFoundException(username);
}
return dto;
}
// Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat.
public boolean userExists(String username) {
return userRepository.existsById(username);
}
// Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug.
public String createUser(UserDto userDto) {
String randomString = RandomStringGenerator.generateAlphaNumeric(20);
userDto.setApikey(randomString);
User newUser = userRepository.save(toUser(userDto));
return newUser.getUsername();
}
// Verwijdert een<SUF>
public void deleteUser(String username) {
userRepository.deleteById(username);
}
public UserDto updateUser(String username, UserDto dto) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new EntityNotFoundException("User not found with username " + username));
user.setEmail(dto.getEmail());
user.setUsername(dto.getUsername());
// Check if the password field in the incoming UserDto is null or empty
if (dto.getPassword() != null && !dto.getPassword().isEmpty()) {
user.setPassword(passwordEncoder.encode(dto.getPassword()));
}
User updatedUser = userRepository.save(user);
UserDto updatedUserDto = convertToDto(updatedUser);
return updatedUserDto;
}
public UserDto convertToDto(User user) {
UserDto userDto = new UserDto();
userDto.setUsername(user.getUsername());
userDto.setPassword(user.getPassword());
userDto.setEnabled(user.isEnabled());
userDto.setApikey(user.getApikey());
userDto.setEmail(user.getEmail());
userDto.setAuthorities(user.getAuthorities());
return userDto;
}
// Zet een User-object om naar een UserDto
public static UserDto fromUser(User user) {
var dto = new UserDto();
// In de code lijkt getUsername() de
// gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke
// identificator voor een gebruiker.
dto.username = user.getUsername();
dto.password = user.getPassword();
dto.enabled = user.isEnabled();
dto.apikey = user.getApikey();
dto.email = user.getEmail();
dto.authorities = user.getAuthorities();
return dto;
}
// Zet een UserDto-object om naar een User.
public User toUser(UserDto userDto) {
var user = new User();
user.setUsername(userDto.getUsername());
user.setPassword(passwordEncoder.encode(userDto.password));
// user.setPassword(userDto.getPassword());
user.setEnabled(userDto.getEnabled());
user.setApikey(userDto.getApikey());
user.setEmail(userDto.getEmail());
return user;
}
} |
37735_6 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import domein.DomeinController;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/**
*
* @author bjorn
*/
public class Startscherm extends BorderPane {
private final DomeinController dc;
public Startscherm(DomeinController dc) {
this.dc = dc;
buildGui();
}
private void buildGui(){
//Panes/Boxes/CSS *********************************************************************
getStylesheets().add("/css/startscherm.css");
GridPane gpane = new GridPane();
//setCancelDefault fzoiets vr via escape terug naar vorig scherm
//Start button ************************************************************************
Button btnStart = new Button();
btnStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnStartOnAction(ae);
}
});
btnStart.setId("btnStart");
btnStart.setPrefSize(200, 50);
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Resume button ************************************************************************
// Enkel resume game als er al een game in het spel is!
Button btnResume = new Button();
btnResume.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnResumeOnAction(ae);
}
});
btnResume.setDisable(true);
btnResume.setId("btnResume");
btnResume.setPrefSize(200, 50);
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Highscores button ************************************************************************
Button btnHighScores = new Button();
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnHighscoresOnAction(ae);
}
});
btnHighScores.setId("btnHighScores");
btnHighScores.setPrefSize(200, 50);
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Rules button ************************************************************************
Button btnGameRules = new Button();
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnGameRulesOnAction(ae);
}
});
btnGameRules.setId("btnGameRules");
btnGameRules.setPrefSize(200, 50);
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Centering van de Gridpane ***************************************************************
gpane.add(btnStart, 0, 0);
gpane.add(btnResume, 0, 1);
gpane.add(btnHighScores, 0, 2);
gpane.add(btnGameRules, 0, 3);
gpane.setAlignment(Pos.CENTER);
gpane.setPadding(new Insets(50,5,5,5));
gpane.setHgap(1);
gpane.setVgap(1);
setCenter(gpane);
}
private void btnStartOnAction(ActionEvent event)
{
//dc.deleteData() = mogelijke methode om nieuw spel te starten
SpelersSettings ss = new SpelersSettings(this, dc);
Scene scene = new Scene(ss, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
private void btnHighscoresOnAction(ActionEvent event)
{
HighscoreScherm hs = new HighscoreScherm(this, dc);
Scene scene = new Scene(hs, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
private void btnResumeOnAction(ActionEvent event)
{/*
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken
dc.vulDomein();
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);
Scene scene = new Scene(overzichtscherm,1250,700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
*/
}
private void btnGameRulesOnAction(ActionEvent event)
{
GameRulesScherm grs = new GameRulesScherm(this, dc);
Scene scene = new Scene(grs, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
}
| rayzorg/regenworm | src/gui/Startscherm.java | 1,569 | // Enkel resume game als er al een game in het spel is!
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package gui;
import domein.DomeinController;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
/**
*
* @author bjorn
*/
public class Startscherm extends BorderPane {
private final DomeinController dc;
public Startscherm(DomeinController dc) {
this.dc = dc;
buildGui();
}
private void buildGui(){
//Panes/Boxes/CSS *********************************************************************
getStylesheets().add("/css/startscherm.css");
GridPane gpane = new GridPane();
//setCancelDefault fzoiets vr via escape terug naar vorig scherm
//Start button ************************************************************************
Button btnStart = new Button();
btnStart.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnStartOnAction(ae);
}
});
btnStart.setId("btnStart");
btnStart.setPrefSize(200, 50);
//btnStart.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Resume button ************************************************************************
// Enkel resume<SUF>
Button btnResume = new Button();
btnResume.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnResumeOnAction(ae);
}
});
btnResume.setDisable(true);
btnResume.setId("btnResume");
btnResume.setPrefSize(200, 50);
//btnResume.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Highscores button ************************************************************************
Button btnHighScores = new Button();
btnHighScores.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnHighscoresOnAction(ae);
}
});
btnHighScores.setId("btnHighScores");
btnHighScores.setPrefSize(200, 50);
//btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Rules button ************************************************************************
Button btnGameRules = new Button();
btnGameRules.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent ae) {
btnGameRulesOnAction(ae);
}
});
btnGameRules.setId("btnGameRules");
btnGameRules.setPrefSize(200, 50);
// btnHighscores.prefHeightProperty().bind(this.heightProperty().multiply(1));
//Centering van de Gridpane ***************************************************************
gpane.add(btnStart, 0, 0);
gpane.add(btnResume, 0, 1);
gpane.add(btnHighScores, 0, 2);
gpane.add(btnGameRules, 0, 3);
gpane.setAlignment(Pos.CENTER);
gpane.setPadding(new Insets(50,5,5,5));
gpane.setHgap(1);
gpane.setVgap(1);
setCenter(gpane);
}
private void btnStartOnAction(ActionEvent event)
{
//dc.deleteData() = mogelijke methode om nieuw spel te starten
SpelersSettings ss = new SpelersSettings(this, dc);
Scene scene = new Scene(ss, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
private void btnHighscoresOnAction(ActionEvent event)
{
HighscoreScherm hs = new HighscoreScherm(this, dc);
Scene scene = new Scene(hs, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
private void btnResumeOnAction(ActionEvent event)
{/*
// dc aanspreken + vullen met sepl dat laatste werd opgeslagen en onderbroken
dc.vulDomein();
OverzichtScherm overzichtscherm = new OverzichtScherm(dc,dc.geefSpelInfo()[1],1);
Scene scene = new Scene(overzichtscherm,1250,700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
*/
}
private void btnGameRulesOnAction(ActionEvent event)
{
GameRulesScherm grs = new GameRulesScherm(this, dc);
Scene scene = new Scene(grs, 1250, 700);
Stage stage = (Stage) this.getScene().getWindow();
stage.setScene(scene);
stage.show();
}
}
|
200361_20 | package edu.byuh.cis.cs203.bw_i18n_2019.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.View;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import edu.byuh.cis.cs203.bw_i18n_2019.R;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.DepthCharge;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.ImageCache;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Missile;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Sprite;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Submarine;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Airplane;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Battleship;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Direction;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Size;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.TickListener;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Timer;
public class GameView extends View implements TickListener {
private Bitmap water;
private Battleship battleship;
private List<Airplane> planes;
private List<Submarine> subs;
private boolean init;
private List<DepthCharge> bombs;
private List<Missile> missiles;
private Timer horloge;
private boolean leftPop, rightPop;
private int score;
private Paint scorePaint, timePaint;
private int countdown;
private long timeNow, timeBefore;
private long bombTick;
private MediaPlayer dcSound, leftSound, rightSound, airExplosion, waterExplosion;
/**
* Constructor for our View subclass. Loads all the images.
* @param context a reference to our main Activity class
*/
public GameView(Context context) {
super(context);
bombs = new ArrayList<>();
missiles = new ArrayList<>();
planes = new ArrayList<>();
subs = new ArrayList<>();
scorePaint = new Paint();
scorePaint.setColor(Color.BLACK);
scorePaint.setStyle(Paint.Style.FILL);
scorePaint.setTextAlign(Paint.Align.LEFT);
timePaint = new Paint(scorePaint);
timePaint.setTextAlign(Paint.Align.RIGHT);
leftPop = false;
rightPop = false;
dcSound = MediaPlayer.create(getContext(), R.raw.depth_charge);
leftSound = MediaPlayer.create(getContext(), R.raw.left_gun);
rightSound = MediaPlayer.create(getContext(), R.raw.right_gun);
airExplosion = MediaPlayer.create(getContext(), R.raw.plane_explode);
waterExplosion = MediaPlayer.create(getContext(), R.raw.sub_explode);
init = false;
restart();
}
/**
* this method restarst the game
*/
private void restart() {
score = 0;
countdown = 180;
bombTick = 0;
timeBefore = System.currentTimeMillis();
}
/**
* Scales, positions, and renders the scene
* @param c the Canvas object, provided by system
*/
@Override
public void onDraw(Canvas c) {
c.drawColor(Color.WHITE);
int w = getWidth();
int h = getHeight();
if (init == false) {
init = true;
ImageCache.init(getResources(), w, h);
scorePaint.setTextSize(h/20);
timePaint.setTextSize(scorePaint.getTextSize());
water = ImageCache.getWaterImage();
battleship = Battleship.getInstance();
float battleshipX = w/2-battleship.getWidth()/2; //center the ship
float battleshipY = h/2-battleship.getHeight()+water.getHeight(); //put the ship above the water line
battleship.setLocation(battleshipX, battleshipY);
//inform Airplane class of acceptable upper/lower limits of flight
Airplane.setSkyLimits(0, battleship.getTop()-ImageCache.getAirplaneImage(Size.LARGE, Direction.RIGHT_TO_LEFT).getHeight()*2);
//inform Submarine class of acceptable upper/lower limits of depth
Submarine.setWaterDepth(h/2 + water.getHeight()*2, h-water.getHeight()*2);
//instantiate enemy vessels
float enemySpeed = Prefs.getPlaneSpeed(getContext());
for (int i=0; i<Prefs.getNumPlanes(getContext()); i++) {
planes.add(new Airplane(enemySpeed));
}
enemySpeed = Prefs.getSubSpeed(getContext());
for (int i=0; i<Prefs.getNumSubs(getContext()); i++) {
subs.add(new Submarine(enemySpeed));
}
//Once everything is in place, start the animation loop!
horloge = new Timer();
for (Airplane p : planes) {
horloge.subscribe(p);
}
for (Submarine s : subs) {
horloge.subscribe(s);
}
horloge.subscribe(this);
}
//now draw everything
float waterX = 0;
while (waterX < w) {
c.drawBitmap(water, waterX, h/2, null);
waterX += water.getWidth();
}
for (Airplane a : planes) {
a.draw(c);
}
for (Submarine s : subs) {
s.draw(c);
}
for (DepthCharge d : bombs) {
d.draw(c);
}
for (Missile d : missiles) {
d.draw(c);
}
battleship.draw(c);
//extra credit: draw the "pop" at the mouth of the cannon
Bitmap pop = ImageCache.getCannonFire();
if (leftPop) {
final PointF popLocation = battleship.getLeftCannonPosition();
c.drawBitmap(pop, popLocation.x-pop.getWidth(), popLocation.y-pop.getHeight(), null);
leftPop = false;
}
if (rightPop) {
final PointF popLocation = battleship.getRightCannonPosition();
c.drawBitmap(pop, popLocation.x, popLocation.y-pop.getHeight(), null);
rightPop = false;
}
final String scoreLabel = getResources().getString(R.string.score);
c.drawText(scoreLabel + ": " + score, 5, h*0.6f, scorePaint);
final String timeLabel = getResources().getString(R.string.time);
String temps = String.format(timeLabel + ": %d:%02d", countdown /60, countdown %60);
c.drawText(temps, w-5, h*0.6f, timePaint);
}
/**
* Deal with touch events. Launch missiles and depth charges
* @param m the MotionEvent object, provided by the OS
* @return always true. It just works better that way.
*/
@Override
public boolean onTouchEvent(MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN) {
float x = m.getX();
float y = m.getY();
//did the user tap the bottom half of the screen? Depth Charge!
if (y > getHeight()/2) {
if (Prefs.getRapidDC(getContext()) || visibleBombs()==false) {
launchNewDepthCharge();
}
} else {
//did the user tap the top half of the screen? missile!
if (Prefs.getRapidGuns(getContext()) || visibleMissiles()==false) {
if (x < getWidth() / 2) {
launchNewMissile(Direction.RIGHT_TO_LEFT);
} else {
launchNewMissile(Direction.LEFT_TO_RIGHT);
}
}
}
cleanupOffscreenObjects();
}
return true;
}
/**
* creates new depth charges
*/
private void launchNewDepthCharge() {
DepthCharge dc = new DepthCharge();
dc.setCentroid(getWidth()/2, getHeight()/2);
bombs.add(dc);
horloge.subscribe(dc);
}
/**
* creates ne missiles
* @param d
*/
private void launchNewMissile(Direction d) {
Missile miss = new Missile(d);
if (d == Direction.RIGHT_TO_LEFT) {
miss.setBottomRight(battleship.getLeftCannonPosition());
if (Prefs.getSoundFX(getContext())) {
leftSound.start();
}
leftPop = true;
} else {
miss.setBottomLeft(battleship.getRightCannonPosition());
if (Prefs.getSoundFX(getContext())) {
rightSound.start();
}
rightPop = true;
}
missiles.add(miss);
horloge.subscribe(miss);
}
/**
* cleans off object that go off screen and remove the form list and timer
*/
private void cleanupOffscreenObjects() {
//clean up depth charges that go off-screen
// List<Sprite> doomed = new ArrayList<>();
// for (DepthCharge dc : bombs) {
// if (dc.getTop() > getHeight()) {
// doomed.add(dc);
// }
// }
// for (Sprite d : doomed) {
// bombs.remove(d);
// horloge.unsubscribe(d);
// }
// doomed.clear();
List<DepthCharge> doome = bombs.stream().filter(bombs -> getTop() > getHeight()).collect(Collectors.toList());
doome.forEach(bombs -> horloge.unsubscribe(bombs));
bombs.removeIf(bombs -> bombs.getTop() > getHeight());
List<Missile> doom = missiles.stream().filter(missiles -> getBottom() < 0).collect(Collectors.toList());
doom.forEach(missiles -> horloge.unsubscribe(missiles));
missiles.removeIf(missiles -> missiles.getBottom() < 0);
//clean up missiles that go off-screen
// for (Missile dc : missiles) {
// if (dc.getBottom() < 0) {
// doomed.add(dc);
// }
// }
// for (Sprite d : doomed) {
// missiles.remove(d);
// horloge.unsubscribe(d);
// }
}
/**
* detect if objects overlap each other
*/
private void detectCollisions() {
for (Submarine s : subs) {
for (DepthCharge d : bombs) {
if (d.overlaps(s)) {
s.explode();
score += s.getPointValue();
if (Prefs.getSoundFX(getContext())) {
waterExplosion.start();
}
//hide the depth charge off-screen; it will get cleaned
//up at the next touch event.
d.setLocation(0,ImageCache.screenHeight());
}
}
}
for (Airplane p : planes) {
for (Missile m : missiles) {
if (p.overlaps(m)) {
p.explode();
score += p.getPointValue();
if (Prefs.getSoundFX(getContext())) {
airExplosion.start();
}
//hide the missile charge off-screen; it will get cleaned
//up at the next touch event.
m.setLocation(0,-ImageCache.screenHeight());
}
}
}
}
/**
* every tick of the gae, this happens
*/
@Override
public void tick() {
timeNow = System.currentTimeMillis();
if (timeNow-timeBefore > 1000) {
countdown--;
timeBefore = System.currentTimeMillis();
if (countdown <= 0) {
endgame();
}
}
invalidate();
detectCollisions();
//cleanupOffscreenObjects();
if (bombTick % 10 == 0 && visibleBombs()) {
if (Prefs.getSoundFX(getContext())) {
dcSound.start();
}
}
bombTick++;
}
/**
* check if th ebombs are on screen
* @return
*/
private boolean visibleBombs() {
boolean result = false;
for (DepthCharge d : bombs) {
if (d.getTop() < ImageCache.screenHeight()) {
result = true;
break;
}
}
return result;
}
/**
* check if missiles are on screen
* @return
*/
private boolean visibleMissiles() {
boolean result = false;
for (Missile d : missiles) {
if (d.getBottom() > 0) {
result = true;
break;
}
}
return result;
}
/**
* when the game ends,this method wil run
*/
private void endgame() {
horloge.pause();
String message = "";
int oldScore = 0;
//attempt to load the old score
final String scoreFile = "scores.txt";
try (InputStream is = getContext().openFileInput(scoreFile);
Scanner s = new Scanner(is)){
// InputStream is = getContext().openFileInput(scoreFile);
// Scanner s = new Scanner(is);
oldScore = s.nextInt();
} catch (FileNotFoundException e) {
//do nothing, just use 0 as old score
} catch (IOException e){
}
if (oldScore < score) {
message = getResources().getString(R.string.congrats);
//now, save the new score
try (OutputStream os = getContext().openFileOutput(scoreFile, Context.MODE_PRIVATE)){
os.write(("" + score).getBytes());
} catch (IOException e) {
//do nothing
}
} else {
message = getResources().getString(R.string.consolation, oldScore);
}
message += " " + getResources().getString(R.string.play_again);
//Now, prep the dialog box
AlertDialog.Builder ab = new AlertDialog.Builder(getContext());
ab.setTitle(R.string.game_over)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
horloge.resume();
restart();
}
})
.setNegativeButton(R.string.no, (dialog, which) -> çaSuffit());
AlertDialog box = ab.create();
box.show();
}
private void çaSuffit() {
((Activity)getContext()).finish();
}
/**
* pause timer
*/
public void gotoBackground() {
if (horloge != null) {
horloge.pause();
}
}
/**
* resume timer
*/
public void gotoForeground() {
if (horloge != null) {
horloge.resume();
}
}
}
| razznblue/Battleship-War | app/src/main/java/edu/byuh/cis/cs203/bw_i18n_2019/ui/GameView.java | 4,466 | // if (dc.getTop() > getHeight()) { | line_comment | nl | package edu.byuh.cis.cs203.bw_i18n_2019.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.View;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import edu.byuh.cis.cs203.bw_i18n_2019.R;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.DepthCharge;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.ImageCache;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Missile;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Sprite;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Submarine;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Airplane;
import edu.byuh.cis.cs203.bw_i18n_2019.graphics.Battleship;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Direction;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Size;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.TickListener;
import edu.byuh.cis.cs203.bw_i18n_2019.misc.Timer;
public class GameView extends View implements TickListener {
private Bitmap water;
private Battleship battleship;
private List<Airplane> planes;
private List<Submarine> subs;
private boolean init;
private List<DepthCharge> bombs;
private List<Missile> missiles;
private Timer horloge;
private boolean leftPop, rightPop;
private int score;
private Paint scorePaint, timePaint;
private int countdown;
private long timeNow, timeBefore;
private long bombTick;
private MediaPlayer dcSound, leftSound, rightSound, airExplosion, waterExplosion;
/**
* Constructor for our View subclass. Loads all the images.
* @param context a reference to our main Activity class
*/
public GameView(Context context) {
super(context);
bombs = new ArrayList<>();
missiles = new ArrayList<>();
planes = new ArrayList<>();
subs = new ArrayList<>();
scorePaint = new Paint();
scorePaint.setColor(Color.BLACK);
scorePaint.setStyle(Paint.Style.FILL);
scorePaint.setTextAlign(Paint.Align.LEFT);
timePaint = new Paint(scorePaint);
timePaint.setTextAlign(Paint.Align.RIGHT);
leftPop = false;
rightPop = false;
dcSound = MediaPlayer.create(getContext(), R.raw.depth_charge);
leftSound = MediaPlayer.create(getContext(), R.raw.left_gun);
rightSound = MediaPlayer.create(getContext(), R.raw.right_gun);
airExplosion = MediaPlayer.create(getContext(), R.raw.plane_explode);
waterExplosion = MediaPlayer.create(getContext(), R.raw.sub_explode);
init = false;
restart();
}
/**
* this method restarst the game
*/
private void restart() {
score = 0;
countdown = 180;
bombTick = 0;
timeBefore = System.currentTimeMillis();
}
/**
* Scales, positions, and renders the scene
* @param c the Canvas object, provided by system
*/
@Override
public void onDraw(Canvas c) {
c.drawColor(Color.WHITE);
int w = getWidth();
int h = getHeight();
if (init == false) {
init = true;
ImageCache.init(getResources(), w, h);
scorePaint.setTextSize(h/20);
timePaint.setTextSize(scorePaint.getTextSize());
water = ImageCache.getWaterImage();
battleship = Battleship.getInstance();
float battleshipX = w/2-battleship.getWidth()/2; //center the ship
float battleshipY = h/2-battleship.getHeight()+water.getHeight(); //put the ship above the water line
battleship.setLocation(battleshipX, battleshipY);
//inform Airplane class of acceptable upper/lower limits of flight
Airplane.setSkyLimits(0, battleship.getTop()-ImageCache.getAirplaneImage(Size.LARGE, Direction.RIGHT_TO_LEFT).getHeight()*2);
//inform Submarine class of acceptable upper/lower limits of depth
Submarine.setWaterDepth(h/2 + water.getHeight()*2, h-water.getHeight()*2);
//instantiate enemy vessels
float enemySpeed = Prefs.getPlaneSpeed(getContext());
for (int i=0; i<Prefs.getNumPlanes(getContext()); i++) {
planes.add(new Airplane(enemySpeed));
}
enemySpeed = Prefs.getSubSpeed(getContext());
for (int i=0; i<Prefs.getNumSubs(getContext()); i++) {
subs.add(new Submarine(enemySpeed));
}
//Once everything is in place, start the animation loop!
horloge = new Timer();
for (Airplane p : planes) {
horloge.subscribe(p);
}
for (Submarine s : subs) {
horloge.subscribe(s);
}
horloge.subscribe(this);
}
//now draw everything
float waterX = 0;
while (waterX < w) {
c.drawBitmap(water, waterX, h/2, null);
waterX += water.getWidth();
}
for (Airplane a : planes) {
a.draw(c);
}
for (Submarine s : subs) {
s.draw(c);
}
for (DepthCharge d : bombs) {
d.draw(c);
}
for (Missile d : missiles) {
d.draw(c);
}
battleship.draw(c);
//extra credit: draw the "pop" at the mouth of the cannon
Bitmap pop = ImageCache.getCannonFire();
if (leftPop) {
final PointF popLocation = battleship.getLeftCannonPosition();
c.drawBitmap(pop, popLocation.x-pop.getWidth(), popLocation.y-pop.getHeight(), null);
leftPop = false;
}
if (rightPop) {
final PointF popLocation = battleship.getRightCannonPosition();
c.drawBitmap(pop, popLocation.x, popLocation.y-pop.getHeight(), null);
rightPop = false;
}
final String scoreLabel = getResources().getString(R.string.score);
c.drawText(scoreLabel + ": " + score, 5, h*0.6f, scorePaint);
final String timeLabel = getResources().getString(R.string.time);
String temps = String.format(timeLabel + ": %d:%02d", countdown /60, countdown %60);
c.drawText(temps, w-5, h*0.6f, timePaint);
}
/**
* Deal with touch events. Launch missiles and depth charges
* @param m the MotionEvent object, provided by the OS
* @return always true. It just works better that way.
*/
@Override
public boolean onTouchEvent(MotionEvent m) {
if (m.getAction() == MotionEvent.ACTION_DOWN) {
float x = m.getX();
float y = m.getY();
//did the user tap the bottom half of the screen? Depth Charge!
if (y > getHeight()/2) {
if (Prefs.getRapidDC(getContext()) || visibleBombs()==false) {
launchNewDepthCharge();
}
} else {
//did the user tap the top half of the screen? missile!
if (Prefs.getRapidGuns(getContext()) || visibleMissiles()==false) {
if (x < getWidth() / 2) {
launchNewMissile(Direction.RIGHT_TO_LEFT);
} else {
launchNewMissile(Direction.LEFT_TO_RIGHT);
}
}
}
cleanupOffscreenObjects();
}
return true;
}
/**
* creates new depth charges
*/
private void launchNewDepthCharge() {
DepthCharge dc = new DepthCharge();
dc.setCentroid(getWidth()/2, getHeight()/2);
bombs.add(dc);
horloge.subscribe(dc);
}
/**
* creates ne missiles
* @param d
*/
private void launchNewMissile(Direction d) {
Missile miss = new Missile(d);
if (d == Direction.RIGHT_TO_LEFT) {
miss.setBottomRight(battleship.getLeftCannonPosition());
if (Prefs.getSoundFX(getContext())) {
leftSound.start();
}
leftPop = true;
} else {
miss.setBottomLeft(battleship.getRightCannonPosition());
if (Prefs.getSoundFX(getContext())) {
rightSound.start();
}
rightPop = true;
}
missiles.add(miss);
horloge.subscribe(miss);
}
/**
* cleans off object that go off screen and remove the form list and timer
*/
private void cleanupOffscreenObjects() {
//clean up depth charges that go off-screen
// List<Sprite> doomed = new ArrayList<>();
// for (DepthCharge dc : bombs) {
// if (dc.getTop()<SUF>
// doomed.add(dc);
// }
// }
// for (Sprite d : doomed) {
// bombs.remove(d);
// horloge.unsubscribe(d);
// }
// doomed.clear();
List<DepthCharge> doome = bombs.stream().filter(bombs -> getTop() > getHeight()).collect(Collectors.toList());
doome.forEach(bombs -> horloge.unsubscribe(bombs));
bombs.removeIf(bombs -> bombs.getTop() > getHeight());
List<Missile> doom = missiles.stream().filter(missiles -> getBottom() < 0).collect(Collectors.toList());
doom.forEach(missiles -> horloge.unsubscribe(missiles));
missiles.removeIf(missiles -> missiles.getBottom() < 0);
//clean up missiles that go off-screen
// for (Missile dc : missiles) {
// if (dc.getBottom() < 0) {
// doomed.add(dc);
// }
// }
// for (Sprite d : doomed) {
// missiles.remove(d);
// horloge.unsubscribe(d);
// }
}
/**
* detect if objects overlap each other
*/
private void detectCollisions() {
for (Submarine s : subs) {
for (DepthCharge d : bombs) {
if (d.overlaps(s)) {
s.explode();
score += s.getPointValue();
if (Prefs.getSoundFX(getContext())) {
waterExplosion.start();
}
//hide the depth charge off-screen; it will get cleaned
//up at the next touch event.
d.setLocation(0,ImageCache.screenHeight());
}
}
}
for (Airplane p : planes) {
for (Missile m : missiles) {
if (p.overlaps(m)) {
p.explode();
score += p.getPointValue();
if (Prefs.getSoundFX(getContext())) {
airExplosion.start();
}
//hide the missile charge off-screen; it will get cleaned
//up at the next touch event.
m.setLocation(0,-ImageCache.screenHeight());
}
}
}
}
/**
* every tick of the gae, this happens
*/
@Override
public void tick() {
timeNow = System.currentTimeMillis();
if (timeNow-timeBefore > 1000) {
countdown--;
timeBefore = System.currentTimeMillis();
if (countdown <= 0) {
endgame();
}
}
invalidate();
detectCollisions();
//cleanupOffscreenObjects();
if (bombTick % 10 == 0 && visibleBombs()) {
if (Prefs.getSoundFX(getContext())) {
dcSound.start();
}
}
bombTick++;
}
/**
* check if th ebombs are on screen
* @return
*/
private boolean visibleBombs() {
boolean result = false;
for (DepthCharge d : bombs) {
if (d.getTop() < ImageCache.screenHeight()) {
result = true;
break;
}
}
return result;
}
/**
* check if missiles are on screen
* @return
*/
private boolean visibleMissiles() {
boolean result = false;
for (Missile d : missiles) {
if (d.getBottom() > 0) {
result = true;
break;
}
}
return result;
}
/**
* when the game ends,this method wil run
*/
private void endgame() {
horloge.pause();
String message = "";
int oldScore = 0;
//attempt to load the old score
final String scoreFile = "scores.txt";
try (InputStream is = getContext().openFileInput(scoreFile);
Scanner s = new Scanner(is)){
// InputStream is = getContext().openFileInput(scoreFile);
// Scanner s = new Scanner(is);
oldScore = s.nextInt();
} catch (FileNotFoundException e) {
//do nothing, just use 0 as old score
} catch (IOException e){
}
if (oldScore < score) {
message = getResources().getString(R.string.congrats);
//now, save the new score
try (OutputStream os = getContext().openFileOutput(scoreFile, Context.MODE_PRIVATE)){
os.write(("" + score).getBytes());
} catch (IOException e) {
//do nothing
}
} else {
message = getResources().getString(R.string.consolation, oldScore);
}
message += " " + getResources().getString(R.string.play_again);
//Now, prep the dialog box
AlertDialog.Builder ab = new AlertDialog.Builder(getContext());
ab.setTitle(R.string.game_over)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
horloge.resume();
restart();
}
})
.setNegativeButton(R.string.no, (dialog, which) -> çaSuffit());
AlertDialog box = ab.create();
box.show();
}
private void çaSuffit() {
((Activity)getContext()).finish();
}
/**
* pause timer
*/
public void gotoBackground() {
if (horloge != null) {
horloge.pause();
}
}
/**
* resume timer
*/
public void gotoForeground() {
if (horloge != null) {
horloge.resume();
}
}
}
|
117915_0 | package nl.topicus.patientcase;
import nl.topicus.patientcase.models.Patient;
import nl.topicus.patientcase.models.Recipe;
import nl.topicus.patientcase.services.PatientService;
import nl.topicus.patientcase.services.RecipeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class PatientCaseApplication {
public static void main(String[] args) {
SpringApplication.run(PatientCaseApplication.class, args);
}
@Bean
public CommandLineRunner demo(PatientService patients, RecipeService recipes){
return (args) -> {
// Vul database met voorbeeldrecepten en patiënten
List<Recipe> l = new ArrayList<>();
Recipe r = new Recipe("Asperine", 500, "mg");
recipes.save(r);
l.add(r);
r = new Recipe("Medicijn X", 2, "tabletten");
r.setDescription("Een placebo.");
recipes.save(r);
l.add(r);
r = new Recipe("Lembas bread", 1, "hapje");
r.setDescription("Een hapje is genoeg voor een hele dag.");
recipes.save(r);
l.add(r);
r = new Recipe("Xanax", 1, "pil");
r.setDescription("Generieke naam: Alprazolam.");
recipes.save(r);
l.add(r);
r = new Recipe("Codeïne", 1, "pil");
r.setDescription("Pijnstiller, werkt tegen kriebelhoest.");
recipes.save(r);
l.add(r);
r = new Recipe("Nasacort", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Tamoxifen", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Morfine", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Prednisolol acetaat+benzalkoniumchloride", 1, "druppel per oog");
r.setDescription("Oogdruppels.");
recipes.save(r);
l.add(r);
Patient p = new Patient("Iemand", "Anders", LocalDate.of(1965, 3, 9), "23456235789", "v", "Straatstraat 153", "1234AB", "1234567", "Werkstraat 3", "1234AB");
p.addRecipe(l.get(5));
patients.save(p);
p = new Patient("Niemand", "Anders", LocalDate.of(1966, 7, 21), "5343896710", "v", "Straatstraat 153", "1234AB", "1234567", "Arbeidstraat 33", "1234AB");
p.addRecipe(l.get(7));
patients.save(p);
p = new Patient("Bilbo", "Baggins", LocalDate.of(1690, 6, 12), "12345678910", "m", "The Shire", "1111TS", "000000", "", "");
p.addRecipe(l.get(1));
p.addRecipe(l.get(0));
patients.save(p);
p = new Patient("Frodo", "Baggins", LocalDate.of(1750, 6, 12));
p.setGender("m");
p.setHomeAddress("The Shire");
p.setWorkAddress("Mount Doom");
p.addRecipe(l.get(2));
patients.save(p);
p = new Patient("Naam", "Achternaam", LocalDate.of(2000, 1, 1));
p.setGender("m");
p.addRecipe(l.get(8));
patients.save(p);
};
}
}
| rbaas1/PatientCase | patientcase-backend/src/main/java/nl/topicus/patientcase/PatientCaseApplication.java | 1,134 | // Vul database met voorbeeldrecepten en patiënten | line_comment | nl | package nl.topicus.patientcase;
import nl.topicus.patientcase.models.Patient;
import nl.topicus.patientcase.models.Recipe;
import nl.topicus.patientcase.services.PatientService;
import nl.topicus.patientcase.services.RecipeService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class PatientCaseApplication {
public static void main(String[] args) {
SpringApplication.run(PatientCaseApplication.class, args);
}
@Bean
public CommandLineRunner demo(PatientService patients, RecipeService recipes){
return (args) -> {
// Vul database<SUF>
List<Recipe> l = new ArrayList<>();
Recipe r = new Recipe("Asperine", 500, "mg");
recipes.save(r);
l.add(r);
r = new Recipe("Medicijn X", 2, "tabletten");
r.setDescription("Een placebo.");
recipes.save(r);
l.add(r);
r = new Recipe("Lembas bread", 1, "hapje");
r.setDescription("Een hapje is genoeg voor een hele dag.");
recipes.save(r);
l.add(r);
r = new Recipe("Xanax", 1, "pil");
r.setDescription("Generieke naam: Alprazolam.");
recipes.save(r);
l.add(r);
r = new Recipe("Codeïne", 1, "pil");
r.setDescription("Pijnstiller, werkt tegen kriebelhoest.");
recipes.save(r);
l.add(r);
r = new Recipe("Nasacort", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Tamoxifen", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Morfine", 1, "eenheid");
recipes.save(r);
l.add(r);
r = new Recipe("Prednisolol acetaat+benzalkoniumchloride", 1, "druppel per oog");
r.setDescription("Oogdruppels.");
recipes.save(r);
l.add(r);
Patient p = new Patient("Iemand", "Anders", LocalDate.of(1965, 3, 9), "23456235789", "v", "Straatstraat 153", "1234AB", "1234567", "Werkstraat 3", "1234AB");
p.addRecipe(l.get(5));
patients.save(p);
p = new Patient("Niemand", "Anders", LocalDate.of(1966, 7, 21), "5343896710", "v", "Straatstraat 153", "1234AB", "1234567", "Arbeidstraat 33", "1234AB");
p.addRecipe(l.get(7));
patients.save(p);
p = new Patient("Bilbo", "Baggins", LocalDate.of(1690, 6, 12), "12345678910", "m", "The Shire", "1111TS", "000000", "", "");
p.addRecipe(l.get(1));
p.addRecipe(l.get(0));
patients.save(p);
p = new Patient("Frodo", "Baggins", LocalDate.of(1750, 6, 12));
p.setGender("m");
p.setHomeAddress("The Shire");
p.setWorkAddress("Mount Doom");
p.addRecipe(l.get(2));
patients.save(p);
p = new Patient("Naam", "Achternaam", LocalDate.of(2000, 1, 1));
p.setGender("m");
p.addRecipe(l.get(8));
patients.save(p);
};
}
}
|
112701_4 | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS 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.
*
* B3P Commons GIS 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 B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.roybraam.vanenapp.service;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Chris
*/
public class Crypter {
private static final Log log = LogFactory.getLog(Crypter.class);
/**
* Key waarmee de url wordt encrypt/decrypt.
*/
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "DES";
protected final static String encryptionMode = "ECB";
protected final static String encryptionPadding = "PKCS5Padding";
protected static SecretKey secretKey;
protected static String cipherParameters;
static {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec desKeySpec = new DESKeySpec("proxy00000070707707".getBytes(CHARSET));
secretKey = keyFactory.generateSecret(desKeySpec);
} catch (Exception e) {
log.error("error: ", e);
}
cipherParameters = encryptionAlgorithm + "/" + encryptionMode + "/" + encryptionPadding;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
public static String encryptText(String clearText) throws Exception {
if (clearText == null) {
log.error("text to encrypt may not be null!");
throw new Exception("text to encrypt may not be null!");
}
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), CHARSET);
/* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/
encryptedEncodedText = encryptedEncodedText.replaceAll("[\r\n]", "");
return URLEncoder.encode(encryptedEncodedText, "utf-8");
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
public static String decryptText(String encryptedText) throws Exception {
if (encryptedText == null) {
return null;
}
String et = URLDecoder.decode(encryptedText, "utf-8");
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(et.getBytes(CHARSET));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
}
| rbraam/vanenapp | vanenapp/src/main/java/com/roybraam/vanenapp/service/Crypter.java | 1,170 | /* Verwijder eventuele \r\n karakters die door Commons-Codec 1.4
* zijn toegevoegd. Deze zijn niet toegestaan in een cookie.
*/ | block_comment | nl | /*
* B3P Commons GIS is a library with commonly used classes for OGC
* reading and writing. Included are wms, wfs, gml, csv and other
* general helper classes and extensions.
*
* Copyright 2005 - 2008 B3Partners BV
*
* This file is part of B3P Commons GIS.
*
* B3P Commons GIS 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.
*
* B3P Commons GIS 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 B3P Commons GIS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.roybraam.vanenapp.service;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Chris
*/
public class Crypter {
private static final Log log = LogFactory.getLog(Crypter.class);
/**
* Key waarmee de url wordt encrypt/decrypt.
*/
protected final static String CHARSET = "US-ASCII";
protected final static String encryptionAlgorithm = "DES";
protected final static String encryptionMode = "ECB";
protected final static String encryptionPadding = "PKCS5Padding";
protected static SecretKey secretKey;
protected static String cipherParameters;
static {
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptionAlgorithm);
DESKeySpec desKeySpec = new DESKeySpec("proxy00000070707707".getBytes(CHARSET));
secretKey = keyFactory.generateSecret(desKeySpec);
} catch (Exception e) {
log.error("error: ", e);
}
cipherParameters = encryptionAlgorithm + "/" + encryptionMode + "/" + encryptionPadding;
}
/**
* Encrypt a string.
*
* @param clearText
* @return clearText, encrypted
*/
public static String encryptText(String clearText) throws Exception {
if (clearText == null) {
log.error("text to encrypt may not be null!");
throw new Exception("text to encrypt may not be null!");
}
Base64 encoder = new Base64();
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.ENCRYPT_MODE, secretKey);
byte clearTextBytes[];
clearTextBytes = clearText.getBytes();
byte encryptedText[] = c1.doFinal(clearTextBytes);
String encryptedEncodedText = new String(encoder.encode(encryptedText), CHARSET);
/* Verwijder eventuele \r\n<SUF>*/
encryptedEncodedText = encryptedEncodedText.replaceAll("[\r\n]", "");
return URLEncoder.encode(encryptedEncodedText, "utf-8");
}
/**
* Decrypt a string.
*
* @param encryptedText
* @return encryptedText, decrypted
*/
public static String decryptText(String encryptedText) throws Exception {
if (encryptedText == null) {
return null;
}
String et = URLDecoder.decode(encryptedText, "utf-8");
Base64 decoder = new Base64();
byte decodedEncryptedText[] = decoder.decode(et.getBytes(CHARSET));
Cipher c1 = Cipher.getInstance(cipherParameters);
c1.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedText = c1.doFinal(decodedEncryptedText);
String decryptedTextString = new String(decryptedText);
return decryptedTextString;
}
}
|
23961_23 | package br.gov.mec.aghu.configuracao.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import br.gov.mec.aghu.dominio.DominioSituacao;
import br.gov.mec.aghu.dominio.DominioTipoUnidade;
import br.gov.mec.aghu.internacao.vo.PesquisaReferencialClinicaEspecialidadeVO;
import br.gov.mec.aghu.model.AghClinicas;
import br.gov.mec.aghu.model.FatMotivoDesdobrClinica;
import br.gov.mec.aghu.core.commons.CoreUtil;
import br.gov.mec.aghu.core.exception.ApplicationBusinessException;
/**
* DAO para <code>AghClinicas</code>
*
* @author riccosta
*
*/
public class AghClinicasDAO extends br.gov.mec.aghu.core.persistence.dao.BaseDao<AghClinicas> {
private static final long serialVersionUID = -4527925880644111055L;
/**
* Obter Clinicas.
*
* @return
*/
public List<AghClinicas> obterTodasClinicas() {
DetachedCriteria cri = DetachedCriteria.forClass(AghClinicas.class);
cri.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
return executeCriteria(cri);
}
public Long pesquisarClinicasCount(String filtro) {
DetachedCriteria criteria = createPesquisaClinicasCriteria(filtro);
return executeCriteriaCount(criteria);
}
private DetachedCriteria createPesquisaClinicasCriteria(String filtro) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(filtro)) {
Criterion descricaoCriterion = Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), filtro,
MatchMode.ANYWHERE);
if (CoreUtil.isNumeroInteger(filtro)) {
criteria.add(Restrictions.or(Restrictions.eq(
AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(filtro)), descricaoCriterion));
} else {
criteria.add(descricaoCriterion);
}
}
return criteria;
}
/**
*
* @dbtables AghClinicas select
*
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicasSolInternacao(String strPesquisa) {
// Utilizado HQL, pois não é possível fazer pesquisar com LIKE para tipos
// numéricos (Integer, Byte, Short)
// através de Criteria (ocorre ClassCastException). Se usado Criteria e
// Restrictions.like para a descricao
// e for recebido um numero por parametro, também ocorre ClassCastException.
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
hql.append("order by c.codigo");
List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(
hql.toString()).list();
return li;
}
// public List<AghClinicas> pesquisarClinicas(String filtro) {
// DetachedCriteria criteria = createPesquisaClinicasCriteria(filtro);
// return executeCriteria(criteria, 0, 25, null, false);
// }
/**
* Pesquisa <b>AghClinicas</b> com codigo igual a <i>strPesquisa</i><br>
* ou descricao contendo <i>strPesquisa</i>.
*
* @dbtables AghClinicas select
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicas(String strPesquisa) {
final String hql = montarHQLPesquisarClinicas(strPesquisa) + "order by c.descricao";
final List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(hql).list();
return li;
}
/*
* Optou-se por não alterar o método acima criando um count especifico para o mesmo
*/
@SuppressWarnings("unchecked")
public Integer pesquisarClinicasHQLCount(String strPesquisa) {
final String hql = montarHQLPesquisarClinicas(strPesquisa);
final List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(hql).list();
return li.size();
}
private String montarHQLPesquisarClinicas(String strPesquisa) {
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = CoreUtil.retirarCaracteresInvalidos(strPesquisa);
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
return hql.toString();
}
/**
*
* @dbtables AghClinicas select
*
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicasOrdernadoPorCodigo(
String strPesquisa) {
// Utilizado HQL, pois não é possível fazer pesquisar com LIKE para tipos
// numéricos (Integer, Byte, Short)
// através de Criteria (ocorre ClassCastException). Se usado Criteria e
// Restrictions.like para a descricao
// e for recebido um numero por parametro, também ocorre ClassCastException.
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = CoreUtil.retirarCaracteresInvalidos(strPesquisa);
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
hql.append("order by c.codigo");
List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(
hql.toString()).list();
return li;
}
/**
* @dbtables AghClinicas select
*
* @param codigo
* @return
*/
public AghClinicas obterClinica(Integer codigo) {
DetachedCriteria cri = DetachedCriteria.forClass(AghClinicas.class);
cri.add(Restrictions.idEq(codigo));
return (AghClinicas) executeCriteriaUniqueResult(cri);
}
private DetachedCriteria createPesquisaCriteria(Integer codigo,
String descricao, Integer codigoSUS) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (codigo != null) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
codigo));
}
if (StringUtils.isNotBlank(descricao)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), descricao,
MatchMode.ANYWHERE));
}
if (codigoSUS != null) {
criteria.add(Restrictions.eq(
AghClinicas.Fields.CODIGO_SUS.toString(), codigoSUS));
}
return criteria;
}
/**
*
* @dbtables AghClinicas select
*
* @param firstResult
* @param maxResults
* @param orderProperty
* @param asc
* @param codigo
* @param descricao
* @param codigoSUS
* @return
*/
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> pesquisa(Integer firstResult, Integer maxResults,
String orderProperty, boolean asc, Integer codigo,
String descricao, Integer codigoSUS) {
DetachedCriteria criteria = createPesquisaCriteria(codigo, descricao,
codigoSUS);
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria, firstResult, maxResults,
orderProperty, asc);
}
/**
*
* @dbtables AghClinicas select
*
* @param codigo
* @param descricao
* @param codigoSUS
* @return
*/
public Long pesquisaCount(Integer codigo, String descricao,
Integer codigoSUS) {
DetachedCriteria criteria = createPesquisaCriteria(codigo, descricao,
codigoSUS);
return executeCriteriaCount(criteria);
}
public AghClinicas obterClinicaPelaDescricaoExata(String descricao) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (descricao != null && !descricao.equalsIgnoreCase("")) {
criteria.add(Restrictions.eq(
AghClinicas.Fields.DESCRICAO.toString(), descricao).ignoreCase());
}
return (AghClinicas) executeCriteriaUniqueResult(criteria);
}
/**
*
* @dbtables AghClinicas select
*
* @param objPesquisa
* @return
*/
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> pesquisarClinicasPorCodigoEDescricao(
Object objPesquisa) {
String strPesquisa = (String) objPesquisa;
if (StringUtils.isNotBlank(strPesquisa)
&& CoreUtil.isNumeroInteger(strPesquisa)) {
DetachedCriteria _criteria = DetachedCriteria
.forClass(AghClinicas.class);
_criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(strPesquisa)));
_criteria.add(Restrictions.eq(
AghClinicas.Fields.SITUACAO.toString(), DominioSituacao.A));
List<AghClinicas> list = executeCriteria(_criteria);
if (list.size() > 0) {
return list;
}
}
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(strPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), strPesquisa,
MatchMode.ANYWHERE));
}
criteria.add(Restrictions.eq(AghClinicas.Fields.SITUACAO.toString(),
DominioSituacao.A));
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria);
}
public List<AghClinicas> obterClinicaCapacidadeReferencial(
String strPesquisa) {
if (StringUtils.isNotBlank(strPesquisa)
&& CoreUtil.isNumeroInteger(strPesquisa)) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(strPesquisa)));
criteria.add(Restrictions.gt(
AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
List<AghClinicas> result = executeCriteria(criteria);
if (result != null && result.size() == 1) {
return result;
}
}
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(strPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), strPesquisa,
MatchMode.ANYWHERE));
}
criteria.add(Restrictions.gt(
AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria);
}
public List<AghClinicas> pesquisarClinicasPorCodigoOuDescricao(
Object objPesquisa, Boolean ordCodigo, Boolean ordDesc) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
if (ordCodigo) {
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
}
if (ordDesc) {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return executeCriteria(criteria);
}
public Long pesquisarClinicasPorCodigoOuDescricaoCount(Object objPesquisa) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
return executeCriteriaCount(criteria);
}
public List<AghClinicas> pesquisarClinicasPorCodigoOuDescricaoSuggestionBox(
Object objPesquisa, Boolean ordCodigo, Boolean ordDesc) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
if (ordCodigo) {
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
}
if (ordDesc) {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return executeCriteria(criteria, 0, 100, null);
}
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> listarPorNomeOuCodigo(Object paramPesquisa) {
return pesquisarClinicasOrdernadoPorCodigo((String) paramPesquisa);
}
private DetachedCriteria createPesquisaSituacaoLeitosCriteria(AghClinicas clinica) {
return createPesquisaSituacaoLeitosCriteria(clinica, null, null);
}
private DetachedCriteria createPesquisaSituacaoLeitosCriteria(AghClinicas clinica, String orderProperty, Boolean asc) {
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class);
if (clinica != null) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(), clinica.getCodigo()));
}
criteria.add(Restrictions.gt(AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
if (StringUtils.isNotBlank(orderProperty)) {
criteria.addOrder(asc ? Order.asc(orderProperty) : Order.desc(orderProperty));
} else {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return criteria;
}
public List<AghClinicas> pesquisaSituacaoLeitos(AghClinicas clinica, String orderProperty, Boolean asc) {
DetachedCriteria criteria = createPesquisaSituacaoLeitosCriteria(clinica, orderProperty, asc);
return executeCriteria(criteria);
}
public List<AghClinicas> pesquisaSituacaoLeitos(AghClinicas clinica) {
DetachedCriteria criteria = createPesquisaSituacaoLeitosCriteria(clinica);
return executeCriteria(criteria);
}
private Query clinicaReferencial(AghClinicas clinica, boolean count) throws ApplicationBusinessException {
StringBuffer sql4 = new StringBuffer(400);
if (count) {
sql4.append(" select count (*) ");
} else {
sql4.append(" select new br.gov.mec.aghu.internacao.vo.PesquisaReferencialClinicaEspecialidadeVO (");
sql4.append(" cli.codigo, 0, 'TOT', cli.capacReferencial, ih.mediaPermanencia, ih.percentualOcupacao ");
sql4.append(" ) ");
}
sql4.append(" from AghClinicas cli ");
sql4.append(" join cli.indicadoresHospitalares as ih ");
sql4.append(" where cli = :clinica ");
sql4.append(" and ih.tipoUnidade = :tipoUnidade ");
sql4.append(" and ih.serVinCodigo is null ");
sql4.append(" and ih.serMatricula is null ");
sql4.append(" and ih.unidadeFuncional.seq is null ");
sql4.append(" and ih.especialidade is null ");
sql4.append(" and ih.competenciaInternacao = (");
sql4.append(" select max(ih2.competenciaInternacao) ");
sql4.append(" from AinIndicadoresHospitalares ih2 ");
sql4.append(" where ih2.clinica = cli ");
sql4.append(" ) ");
Query query = createHibernateQuery(sql4.toString());
query.setParameter("clinica", clinica);
query.setParameter("tipoUnidade", DominioTipoUnidade.U);
return query;
}
public Long countClinicaReferencial(AghClinicas clinica) throws ApplicationBusinessException {
// Count do SQL #4 da view
Query query = this.clinicaReferencial(clinica, true);
return (Long) query.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<PesquisaReferencialClinicaEspecialidadeVO> listaClinicaferencial(AghClinicas clinica) throws ApplicationBusinessException {
// SQL #4 da view
Query query = this.clinicaReferencial(clinica, false);
return query.list();
}
public List<AghClinicas> pesquisarClinicasPorMotivoDesdobramento(Short codigoMotivoDesdobramento) {
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class, "CLI");
criteria.createAlias("CLI." + AghClinicas.Fields.MOTIVO_DESDOBRAMENTO_CLINICA.toString(), "MDC", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("MDC." + FatMotivoDesdobrClinica.Fields.MDS_SEQ.toString(), codigoMotivoDesdobramento));
return executeCriteria(criteria);
}
/**
* Padrão correto da suggestion: Primeiro por código, se nao achar, por descricao.
* @param param
* @return
*/
public List<AghClinicas> buscarClinicasSb(Object param) {
List<AghClinicas> retorno = new ArrayList<AghClinicas>();
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class);
//Busca por codigo
if (param != null && CoreUtil.isNumeroInteger(param)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(), Integer.valueOf(param.toString())));
retorno = executeCriteria(criteria);
}
//Se não encontrar, busca por descrição.
if (retorno == null || retorno.isEmpty()) {
criteria = DetachedCriteria.forClass(AghClinicas.class);
if (param != null) {
criteria.add(Restrictions.ilike(AghClinicas.Fields.DESCRICAO.toString(), param.toString(), MatchMode.ANYWHERE));
}
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
retorno = executeCriteria(criteria);
}
return executeCriteria(criteria);
}
/**
* Padrão correto da suggestion COUNT: Primeiro por código, se nao achar, por descricao.
* @param param
* @return
*/
public Long buscarClinicasSbCount(Object param) {
List<AghClinicas> retorno = buscarClinicasSb(param);
Long count = Long.valueOf(0);
if (retorno != null) {
count = Long.valueOf(retorno.size());
}
return count;
}
}
| rdexm/aghu-sistema | 6x/aplicacao/aghu_jee/aghu/aghu-dao/src/main/java/br/gov/mec/aghu/configuracao/dao/AghClinicasDAO.java | 7,095 | // Count do SQL #4 da view
| line_comment | nl | package br.gov.mec.aghu.configuracao.dao;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.sql.JoinType;
import br.gov.mec.aghu.dominio.DominioSituacao;
import br.gov.mec.aghu.dominio.DominioTipoUnidade;
import br.gov.mec.aghu.internacao.vo.PesquisaReferencialClinicaEspecialidadeVO;
import br.gov.mec.aghu.model.AghClinicas;
import br.gov.mec.aghu.model.FatMotivoDesdobrClinica;
import br.gov.mec.aghu.core.commons.CoreUtil;
import br.gov.mec.aghu.core.exception.ApplicationBusinessException;
/**
* DAO para <code>AghClinicas</code>
*
* @author riccosta
*
*/
public class AghClinicasDAO extends br.gov.mec.aghu.core.persistence.dao.BaseDao<AghClinicas> {
private static final long serialVersionUID = -4527925880644111055L;
/**
* Obter Clinicas.
*
* @return
*/
public List<AghClinicas> obterTodasClinicas() {
DetachedCriteria cri = DetachedCriteria.forClass(AghClinicas.class);
cri.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
return executeCriteria(cri);
}
public Long pesquisarClinicasCount(String filtro) {
DetachedCriteria criteria = createPesquisaClinicasCriteria(filtro);
return executeCriteriaCount(criteria);
}
private DetachedCriteria createPesquisaClinicasCriteria(String filtro) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(filtro)) {
Criterion descricaoCriterion = Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), filtro,
MatchMode.ANYWHERE);
if (CoreUtil.isNumeroInteger(filtro)) {
criteria.add(Restrictions.or(Restrictions.eq(
AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(filtro)), descricaoCriterion));
} else {
criteria.add(descricaoCriterion);
}
}
return criteria;
}
/**
*
* @dbtables AghClinicas select
*
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicasSolInternacao(String strPesquisa) {
// Utilizado HQL, pois não é possível fazer pesquisar com LIKE para tipos
// numéricos (Integer, Byte, Short)
// através de Criteria (ocorre ClassCastException). Se usado Criteria e
// Restrictions.like para a descricao
// e for recebido um numero por parametro, também ocorre ClassCastException.
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
hql.append("order by c.codigo");
List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(
hql.toString()).list();
return li;
}
// public List<AghClinicas> pesquisarClinicas(String filtro) {
// DetachedCriteria criteria = createPesquisaClinicasCriteria(filtro);
// return executeCriteria(criteria, 0, 25, null, false);
// }
/**
* Pesquisa <b>AghClinicas</b> com codigo igual a <i>strPesquisa</i><br>
* ou descricao contendo <i>strPesquisa</i>.
*
* @dbtables AghClinicas select
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicas(String strPesquisa) {
final String hql = montarHQLPesquisarClinicas(strPesquisa) + "order by c.descricao";
final List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(hql).list();
return li;
}
/*
* Optou-se por não alterar o método acima criando um count especifico para o mesmo
*/
@SuppressWarnings("unchecked")
public Integer pesquisarClinicasHQLCount(String strPesquisa) {
final String hql = montarHQLPesquisarClinicas(strPesquisa);
final List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(hql).list();
return li.size();
}
private String montarHQLPesquisarClinicas(String strPesquisa) {
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = CoreUtil.retirarCaracteresInvalidos(strPesquisa);
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
return hql.toString();
}
/**
*
* @dbtables AghClinicas select
*
* @param strPesquisa
* @return
*/
@SuppressWarnings("unchecked")
public List<AghClinicas> pesquisarClinicasOrdernadoPorCodigo(
String strPesquisa) {
// Utilizado HQL, pois não é possível fazer pesquisar com LIKE para tipos
// numéricos (Integer, Byte, Short)
// através de Criteria (ocorre ClassCastException). Se usado Criteria e
// Restrictions.like para a descricao
// e for recebido um numero por parametro, também ocorre ClassCastException.
StringBuilder hql = new StringBuilder(50);
hql.append("from AghClinicas c ");
if (strPesquisa != null && !"".equals(strPesquisa)) {
strPesquisa = CoreUtil.retirarCaracteresInvalidos(strPesquisa);
strPesquisa = strPesquisa.toUpperCase();
hql.append("where str(c.codigo) = '").append(strPesquisa)
.append("' ");
hql.append("or upper(c.descricao) like '%").append(strPesquisa)
.append("%' ");
}
hql.append("order by c.codigo");
List<AghClinicas> li = (List<AghClinicas>) createHibernateQuery(
hql.toString()).list();
return li;
}
/**
* @dbtables AghClinicas select
*
* @param codigo
* @return
*/
public AghClinicas obterClinica(Integer codigo) {
DetachedCriteria cri = DetachedCriteria.forClass(AghClinicas.class);
cri.add(Restrictions.idEq(codigo));
return (AghClinicas) executeCriteriaUniqueResult(cri);
}
private DetachedCriteria createPesquisaCriteria(Integer codigo,
String descricao, Integer codigoSUS) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (codigo != null) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
codigo));
}
if (StringUtils.isNotBlank(descricao)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), descricao,
MatchMode.ANYWHERE));
}
if (codigoSUS != null) {
criteria.add(Restrictions.eq(
AghClinicas.Fields.CODIGO_SUS.toString(), codigoSUS));
}
return criteria;
}
/**
*
* @dbtables AghClinicas select
*
* @param firstResult
* @param maxResults
* @param orderProperty
* @param asc
* @param codigo
* @param descricao
* @param codigoSUS
* @return
*/
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> pesquisa(Integer firstResult, Integer maxResults,
String orderProperty, boolean asc, Integer codigo,
String descricao, Integer codigoSUS) {
DetachedCriteria criteria = createPesquisaCriteria(codigo, descricao,
codigoSUS);
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria, firstResult, maxResults,
orderProperty, asc);
}
/**
*
* @dbtables AghClinicas select
*
* @param codigo
* @param descricao
* @param codigoSUS
* @return
*/
public Long pesquisaCount(Integer codigo, String descricao,
Integer codigoSUS) {
DetachedCriteria criteria = createPesquisaCriteria(codigo, descricao,
codigoSUS);
return executeCriteriaCount(criteria);
}
public AghClinicas obterClinicaPelaDescricaoExata(String descricao) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (descricao != null && !descricao.equalsIgnoreCase("")) {
criteria.add(Restrictions.eq(
AghClinicas.Fields.DESCRICAO.toString(), descricao).ignoreCase());
}
return (AghClinicas) executeCriteriaUniqueResult(criteria);
}
/**
*
* @dbtables AghClinicas select
*
* @param objPesquisa
* @return
*/
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> pesquisarClinicasPorCodigoEDescricao(
Object objPesquisa) {
String strPesquisa = (String) objPesquisa;
if (StringUtils.isNotBlank(strPesquisa)
&& CoreUtil.isNumeroInteger(strPesquisa)) {
DetachedCriteria _criteria = DetachedCriteria
.forClass(AghClinicas.class);
_criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(strPesquisa)));
_criteria.add(Restrictions.eq(
AghClinicas.Fields.SITUACAO.toString(), DominioSituacao.A));
List<AghClinicas> list = executeCriteria(_criteria);
if (list.size() > 0) {
return list;
}
}
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(strPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), strPesquisa,
MatchMode.ANYWHERE));
}
criteria.add(Restrictions.eq(AghClinicas.Fields.SITUACAO.toString(),
DominioSituacao.A));
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria);
}
public List<AghClinicas> obterClinicaCapacidadeReferencial(
String strPesquisa) {
if (StringUtils.isNotBlank(strPesquisa)
&& CoreUtil.isNumeroInteger(strPesquisa)) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf(strPesquisa)));
criteria.add(Restrictions.gt(
AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
List<AghClinicas> result = executeCriteria(criteria);
if (result != null && result.size() == 1) {
return result;
}
}
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (StringUtils.isNotBlank(strPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(), strPesquisa,
MatchMode.ANYWHERE));
}
criteria.add(Restrictions.gt(
AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
return executeCriteria(criteria);
}
public List<AghClinicas> pesquisarClinicasPorCodigoOuDescricao(
Object objPesquisa, Boolean ordCodigo, Boolean ordDesc) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
if (ordCodigo) {
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
}
if (ordDesc) {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return executeCriteria(criteria);
}
public Long pesquisarClinicasPorCodigoOuDescricaoCount(Object objPesquisa) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
return executeCriteriaCount(criteria);
}
public List<AghClinicas> pesquisarClinicasPorCodigoOuDescricaoSuggestionBox(
Object objPesquisa, Boolean ordCodigo, Boolean ordDesc) {
DetachedCriteria criteria = DetachedCriteria
.forClass(AghClinicas.class);
if (CoreUtil.isNumeroShort(objPesquisa)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(),
Integer.valueOf((String) objPesquisa)));
} else {
if (!StringUtils.isEmpty((String) objPesquisa)) {
criteria.add(Restrictions.ilike(
AghClinicas.Fields.DESCRICAO.toString(),
(String) objPesquisa, MatchMode.ANYWHERE));
}
}
if (ordCodigo) {
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
}
if (ordDesc) {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return executeCriteria(criteria, 0, 100, null);
}
//@Restrict("#{s:hasPermission('clinica','pesquisar')}")
public List<AghClinicas> listarPorNomeOuCodigo(Object paramPesquisa) {
return pesquisarClinicasOrdernadoPorCodigo((String) paramPesquisa);
}
private DetachedCriteria createPesquisaSituacaoLeitosCriteria(AghClinicas clinica) {
return createPesquisaSituacaoLeitosCriteria(clinica, null, null);
}
private DetachedCriteria createPesquisaSituacaoLeitosCriteria(AghClinicas clinica, String orderProperty, Boolean asc) {
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class);
if (clinica != null) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(), clinica.getCodigo()));
}
criteria.add(Restrictions.gt(AghClinicas.Fields.CAPACIDADE_REFERENCIAL.toString(), 1));
if (StringUtils.isNotBlank(orderProperty)) {
criteria.addOrder(asc ? Order.asc(orderProperty) : Order.desc(orderProperty));
} else {
criteria.addOrder(Order.asc(AghClinicas.Fields.DESCRICAO.toString()));
}
return criteria;
}
public List<AghClinicas> pesquisaSituacaoLeitos(AghClinicas clinica, String orderProperty, Boolean asc) {
DetachedCriteria criteria = createPesquisaSituacaoLeitosCriteria(clinica, orderProperty, asc);
return executeCriteria(criteria);
}
public List<AghClinicas> pesquisaSituacaoLeitos(AghClinicas clinica) {
DetachedCriteria criteria = createPesquisaSituacaoLeitosCriteria(clinica);
return executeCriteria(criteria);
}
private Query clinicaReferencial(AghClinicas clinica, boolean count) throws ApplicationBusinessException {
StringBuffer sql4 = new StringBuffer(400);
if (count) {
sql4.append(" select count (*) ");
} else {
sql4.append(" select new br.gov.mec.aghu.internacao.vo.PesquisaReferencialClinicaEspecialidadeVO (");
sql4.append(" cli.codigo, 0, 'TOT', cli.capacReferencial, ih.mediaPermanencia, ih.percentualOcupacao ");
sql4.append(" ) ");
}
sql4.append(" from AghClinicas cli ");
sql4.append(" join cli.indicadoresHospitalares as ih ");
sql4.append(" where cli = :clinica ");
sql4.append(" and ih.tipoUnidade = :tipoUnidade ");
sql4.append(" and ih.serVinCodigo is null ");
sql4.append(" and ih.serMatricula is null ");
sql4.append(" and ih.unidadeFuncional.seq is null ");
sql4.append(" and ih.especialidade is null ");
sql4.append(" and ih.competenciaInternacao = (");
sql4.append(" select max(ih2.competenciaInternacao) ");
sql4.append(" from AinIndicadoresHospitalares ih2 ");
sql4.append(" where ih2.clinica = cli ");
sql4.append(" ) ");
Query query = createHibernateQuery(sql4.toString());
query.setParameter("clinica", clinica);
query.setParameter("tipoUnidade", DominioTipoUnidade.U);
return query;
}
public Long countClinicaReferencial(AghClinicas clinica) throws ApplicationBusinessException {
// Count do<SUF>
Query query = this.clinicaReferencial(clinica, true);
return (Long) query.uniqueResult();
}
@SuppressWarnings("unchecked")
public List<PesquisaReferencialClinicaEspecialidadeVO> listaClinicaferencial(AghClinicas clinica) throws ApplicationBusinessException {
// SQL #4 da view
Query query = this.clinicaReferencial(clinica, false);
return query.list();
}
public List<AghClinicas> pesquisarClinicasPorMotivoDesdobramento(Short codigoMotivoDesdobramento) {
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class, "CLI");
criteria.createAlias("CLI." + AghClinicas.Fields.MOTIVO_DESDOBRAMENTO_CLINICA.toString(), "MDC", JoinType.INNER_JOIN);
criteria.add(Restrictions.eq("MDC." + FatMotivoDesdobrClinica.Fields.MDS_SEQ.toString(), codigoMotivoDesdobramento));
return executeCriteria(criteria);
}
/**
* Padrão correto da suggestion: Primeiro por código, se nao achar, por descricao.
* @param param
* @return
*/
public List<AghClinicas> buscarClinicasSb(Object param) {
List<AghClinicas> retorno = new ArrayList<AghClinicas>();
DetachedCriteria criteria = DetachedCriteria.forClass(AghClinicas.class);
//Busca por codigo
if (param != null && CoreUtil.isNumeroInteger(param)) {
criteria.add(Restrictions.eq(AghClinicas.Fields.CODIGO.toString(), Integer.valueOf(param.toString())));
retorno = executeCriteria(criteria);
}
//Se não encontrar, busca por descrição.
if (retorno == null || retorno.isEmpty()) {
criteria = DetachedCriteria.forClass(AghClinicas.class);
if (param != null) {
criteria.add(Restrictions.ilike(AghClinicas.Fields.DESCRICAO.toString(), param.toString(), MatchMode.ANYWHERE));
}
criteria.addOrder(Order.asc(AghClinicas.Fields.CODIGO.toString()));
retorno = executeCriteria(criteria);
}
return executeCriteria(criteria);
}
/**
* Padrão correto da suggestion COUNT: Primeiro por código, se nao achar, por descricao.
* @param param
* @return
*/
public Long buscarClinicasSbCount(Object param) {
List<AghClinicas> retorno = buscarClinicasSb(param);
Long count = Long.valueOf(0);
if (retorno != null) {
count = Long.valueOf(retorno.size());
}
return count;
}
}
|
102941_1 | package collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class QueueLesson {
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue<Integer> q = new LinkedList<>();
q.add(5);
q.offer(4);
q.offer(19);
//FIFO
System.out.println(q.peek()); //prints 5, peek, doesn't remove
System.out.println(q); // prints [5, 4, 19]
System.out.println(q.poll()); // prints 5, poll, get&remove
System.out.println(q); // prints [4, 19]
Deque<Integer> dq = new LinkedList<>();
dq.addFirst(12);
dq.addFirst(13);
dq.addFirst(14);
dq.addLast(16);
// 14 ilk eleman olarak ekleniyor
// 16 zaten son eleman olarak en sona ekleniyor
System.out.println(dq); // prints [14, 13, 12, 16]
}
}
| rdilruba/DataStructuresAndAlgorithms | src/main/java/collections/QueueLesson.java | 315 | //prints 5, peek, doesn't remove | line_comment | nl | package collections;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Queue;
public class QueueLesson {
public static void main(String[] args) {
// TODO Auto-generated method stub
Queue<Integer> q = new LinkedList<>();
q.add(5);
q.offer(4);
q.offer(19);
//FIFO
System.out.println(q.peek()); //prints 5,<SUF>
System.out.println(q); // prints [5, 4, 19]
System.out.println(q.poll()); // prints 5, poll, get&remove
System.out.println(q); // prints [4, 19]
Deque<Integer> dq = new LinkedList<>();
dq.addFirst(12);
dq.addFirst(13);
dq.addFirst(14);
dq.addLast(16);
// 14 ilk eleman olarak ekleniyor
// 16 zaten son eleman olarak en sona ekleniyor
System.out.println(dq); // prints [14, 13, 12, 16]
}
}
|
84427_4 | /*
* Copyright (c) 2022-2024 VMware, 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.netty.channel;
import io.micrometer.common.docs.KeyName;
import io.micrometer.observation.docs.ObservationDocumentation;
/**
* Connect observations.
*
* @author Marcin Grzejszczak
* @author Violeta Georgieva
* @since 1.1.0
*/
enum ConnectObservations implements ObservationDocumentation {
/**
* Connect metric.
*/
CONNECT_TIME {
@Override
public KeyName[] getHighCardinalityKeyNames() {
return ConnectTimeHighCardinalityTags.values();
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return ConnectTimeLowCardinalityTags.values();
}
@Override
public String getName() {
return "%s";
}
};
/**
* Connect High Cardinality Tags.
*/
enum ConnectTimeHighCardinalityTags implements KeyName {
/**
* Net peer name.
*/
NET_PEER_NAME {
@Override
public String asString() {
return "net.peer.name";
}
},
/**
* Net peer port.
*/
NET_PEER_PORT {
@Override
public String asString() {
return "net.peer.port";
}
},
/**
* Reactor Netty protocol (tcp/http etc.).
*/
REACTOR_NETTY_PROTOCOL {
@Override
public String asString() {
return "reactor.netty.protocol";
}
},
/**
* Reactor Netty status.
*/
REACTOR_NETTY_STATUS {
@Override
public String asString() {
return "reactor.netty.status";
}
},
/**
* Reactor Netty type (always client).
*/
REACTOR_NETTY_TYPE {
@Override
public String asString() {
return "reactor.netty.type";
}
}
}
/**
* Connect Low Cardinality Tags.
*/
enum ConnectTimeLowCardinalityTags implements KeyName {
/**
* Proxy address, when there is a proxy configured.
*/
PROXY_ADDRESS {
@Override
public String asString() {
return "proxy.address";
}
},
/**
* Remote address.
*/
REMOTE_ADDRESS {
@Override
public String asString() {
return "remote.address";
}
},
/**
* STATUS.
*/
STATUS {
@Override
public String asString() {
return "status";
}
}
}
}
| reactor/reactor-netty | reactor-netty-core/src/main/java/reactor/netty/channel/ConnectObservations.java | 871 | /**
* Net peer name.
*/ | block_comment | nl | /*
* Copyright (c) 2022-2024 VMware, 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.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.netty.channel;
import io.micrometer.common.docs.KeyName;
import io.micrometer.observation.docs.ObservationDocumentation;
/**
* Connect observations.
*
* @author Marcin Grzejszczak
* @author Violeta Georgieva
* @since 1.1.0
*/
enum ConnectObservations implements ObservationDocumentation {
/**
* Connect metric.
*/
CONNECT_TIME {
@Override
public KeyName[] getHighCardinalityKeyNames() {
return ConnectTimeHighCardinalityTags.values();
}
@Override
public KeyName[] getLowCardinalityKeyNames() {
return ConnectTimeLowCardinalityTags.values();
}
@Override
public String getName() {
return "%s";
}
};
/**
* Connect High Cardinality Tags.
*/
enum ConnectTimeHighCardinalityTags implements KeyName {
/**
* Net peer name.<SUF>*/
NET_PEER_NAME {
@Override
public String asString() {
return "net.peer.name";
}
},
/**
* Net peer port.
*/
NET_PEER_PORT {
@Override
public String asString() {
return "net.peer.port";
}
},
/**
* Reactor Netty protocol (tcp/http etc.).
*/
REACTOR_NETTY_PROTOCOL {
@Override
public String asString() {
return "reactor.netty.protocol";
}
},
/**
* Reactor Netty status.
*/
REACTOR_NETTY_STATUS {
@Override
public String asString() {
return "reactor.netty.status";
}
},
/**
* Reactor Netty type (always client).
*/
REACTOR_NETTY_TYPE {
@Override
public String asString() {
return "reactor.netty.type";
}
}
}
/**
* Connect Low Cardinality Tags.
*/
enum ConnectTimeLowCardinalityTags implements KeyName {
/**
* Proxy address, when there is a proxy configured.
*/
PROXY_ADDRESS {
@Override
public String asString() {
return "proxy.address";
}
},
/**
* Remote address.
*/
REMOTE_ADDRESS {
@Override
public String asString() {
return "remote.address";
}
},
/**
* STATUS.
*/
STATUS {
@Override
public String asString() {
return "status";
}
}
}
}
|
45270_2 | package activities;
import java.util.List;
import services.UploadXML;
import classes.Article;
import classes.AsyncTaskLoadXML_;
import classes.Channel;
import classes.Utils;
import com.example.pocrss.R;
import dao.ActivityDao;
import dao.ChannelDao;
import dao.FontDao;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
public class ListTitlesArticleForSingleThemeActivity extends Activity {
ListView listView;
ProgressBar progress;
int[] activeFont;
//DatabaseHandler db;
Intent in;
List<Article> articlesForThemeAtCreate;
List<Article> articlesForThemeAtUpdate;
Channel channel;
@Override
protected void onCreate(Bundle savedInstanceState) {
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_titles_article_for_single_theme);
// register as active
ActivityDao.addActivity(this);
// set the listview
listView = (ListView) findViewById(R.id.listArticlesForTheme);
// get intent data
in = getIntent();
// set the db
//db = new DatabaseHandler(ListTitlesArticleForSingleThemeActivity.this);
// get the channel from db
channel = ChannelDao.getChannelById(Integer.parseInt(in
.getStringExtra("channelId")));
// get the articles for this channel
articlesForThemeAtCreate = ChannelDao.getArticlesForChannel(channel);
// set a new title for the screen/activity
ListTitlesArticleForSingleThemeActivity.this.setTitle(channel
.getDescription());
progress = (ProgressBar) findViewById(R.id.progressBarPhone2);
progress.setVisibility(View.GONE);
// start background service
new AsyncTaskLoadXML_(getBaseContext(), progress,
ListTitlesArticleForSingleThemeActivity.this).execute();
this.fillInFields(articlesForThemeAtCreate);
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
// if user goes back to overview screen.
// articles have to be updated
super.onRestart();
Log.w("test",
"in onRestart met reeds bezig "
+ UploadXML.isRefreshScreenPause());
if (UploadXML.isRefreshScreenPause() == false) {
Log.w("test", "in onRestart");
refreshScreen();
Log.w("test",
"in onRestart met reeds bezig " + UploadXML.isAlreadyBusy());
if (UploadXML.isAlreadyBusy() != true) {
// start background service
new AsyncTaskLoadXML_(getBaseContext(), progress,
ListTitlesArticleForSingleThemeActivity.this)
.execute();
}
}
}
public void refreshScreen() {
//articlesForTheme.clear();
Log.w("test", "in refreshScreen");
articlesForThemeAtUpdate = ChannelDao.getArticlesForChannel(channel);
runOnUiThread(new Runnable() {
public void run() {
Log.w("test", "in runnable van refreshScreen");
// remove all textviews
//listView.removeAllViews();
// set the listview
listView = (ListView) findViewById(R.id.listArticlesForTheme);
// set a new title for the screen/activity
ListTitlesArticleForSingleThemeActivity.this.setTitle(channel
.getDescription());
fillInFields(articlesForThemeAtUpdate);
}
});
}
private void fillInFields(List<Article> articlesIn) {
//get active font
activeFont=FontDao.getLayoutXML();
Article[] articles = new Article[articlesIn.size()];
for (int i = 0; i < articlesIn.size(); i++) {
articles[i] = articlesIn.get(i);
}
ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(
ListTitlesArticleForSingleThemeActivity.this,
activeFont[1], articles);
/*ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(
ListTitlesArticleForSingleThemeActivity.this,
android.R.layout.simple_list_item_1, articles);*/
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
PhoneSingleArticleActivity.class);
Article listItem = (Article) listView
.getItemAtPosition(position);
in.putExtra("article_id", Integer.toString(listItem.get_id()));
in.putExtra("title", listItem.getTitle());
in.putExtra("enclosure", listItem.getEnclosure());
in.putExtra("description", listItem.getDescription());
in.putExtra("pubDate", listItem.getPubDate().toString());
in.putExtra("channel_id",
Integer.toString(listItem.getChannel().get_id()));
startActivity(in);
}
});
listView.setAdapter(adapter);
}
}
| readerAppRafKurt/AndroidApp | POCRSS/src/activities/ListTitlesArticleForSingleThemeActivity.java | 1,524 | // get intent data | line_comment | nl | package activities;
import java.util.List;
import services.UploadXML;
import classes.Article;
import classes.AsyncTaskLoadXML_;
import classes.Channel;
import classes.Utils;
import com.example.pocrss.R;
import dao.ActivityDao;
import dao.ChannelDao;
import dao.FontDao;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
public class ListTitlesArticleForSingleThemeActivity extends Activity {
ListView listView;
ProgressBar progress;
int[] activeFont;
//DatabaseHandler db;
Intent in;
List<Article> articlesForThemeAtCreate;
List<Article> articlesForThemeAtUpdate;
Channel channel;
@Override
protected void onCreate(Bundle savedInstanceState) {
Utils.setThemeToActivity(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_titles_article_for_single_theme);
// register as active
ActivityDao.addActivity(this);
// set the listview
listView = (ListView) findViewById(R.id.listArticlesForTheme);
// get intent<SUF>
in = getIntent();
// set the db
//db = new DatabaseHandler(ListTitlesArticleForSingleThemeActivity.this);
// get the channel from db
channel = ChannelDao.getChannelById(Integer.parseInt(in
.getStringExtra("channelId")));
// get the articles for this channel
articlesForThemeAtCreate = ChannelDao.getArticlesForChannel(channel);
// set a new title for the screen/activity
ListTitlesArticleForSingleThemeActivity.this.setTitle(channel
.getDescription());
progress = (ProgressBar) findViewById(R.id.progressBarPhone2);
progress.setVisibility(View.GONE);
// start background service
new AsyncTaskLoadXML_(getBaseContext(), progress,
ListTitlesArticleForSingleThemeActivity.this).execute();
this.fillInFields(articlesForThemeAtCreate);
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
// if user goes back to overview screen.
// articles have to be updated
super.onRestart();
Log.w("test",
"in onRestart met reeds bezig "
+ UploadXML.isRefreshScreenPause());
if (UploadXML.isRefreshScreenPause() == false) {
Log.w("test", "in onRestart");
refreshScreen();
Log.w("test",
"in onRestart met reeds bezig " + UploadXML.isAlreadyBusy());
if (UploadXML.isAlreadyBusy() != true) {
// start background service
new AsyncTaskLoadXML_(getBaseContext(), progress,
ListTitlesArticleForSingleThemeActivity.this)
.execute();
}
}
}
public void refreshScreen() {
//articlesForTheme.clear();
Log.w("test", "in refreshScreen");
articlesForThemeAtUpdate = ChannelDao.getArticlesForChannel(channel);
runOnUiThread(new Runnable() {
public void run() {
Log.w("test", "in runnable van refreshScreen");
// remove all textviews
//listView.removeAllViews();
// set the listview
listView = (ListView) findViewById(R.id.listArticlesForTheme);
// set a new title for the screen/activity
ListTitlesArticleForSingleThemeActivity.this.setTitle(channel
.getDescription());
fillInFields(articlesForThemeAtUpdate);
}
});
}
private void fillInFields(List<Article> articlesIn) {
//get active font
activeFont=FontDao.getLayoutXML();
Article[] articles = new Article[articlesIn.size()];
for (int i = 0; i < articlesIn.size(); i++) {
articles[i] = articlesIn.get(i);
}
ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(
ListTitlesArticleForSingleThemeActivity.this,
activeFont[1], articles);
/*ArrayAdapter<Article> adapter = new ArrayAdapter<Article>(
ListTitlesArticleForSingleThemeActivity.this,
android.R.layout.simple_list_item_1, articles);*/
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
PhoneSingleArticleActivity.class);
Article listItem = (Article) listView
.getItemAtPosition(position);
in.putExtra("article_id", Integer.toString(listItem.get_id()));
in.putExtra("title", listItem.getTitle());
in.putExtra("enclosure", listItem.getEnclosure());
in.putExtra("description", listItem.getDescription());
in.putExtra("pubDate", listItem.getPubDate().toString());
in.putExtra("channel_id",
Integer.toString(listItem.getChannel().get_id()));
startActivity(in);
}
});
listView.setAdapter(adapter);
}
}
|
184926_18 | /*******************************************************************************
* 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.ofbiz.entity.serialize;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilObject;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* XmlSerializer class. This class is deprecated - new code should use the
* Java object marshalling/unmarshalling methods in <code>UtilXml.java</code>.
*
*/
public class XmlSerializer {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private volatile static WeakReference<DateFormat> simpleDateFormatter;
// SCIPIO: 2019-03-08: Renamed to *Core, added errorMessageList (if non-null, accumulates errors instead of throwing exception)
private static String serializeCore(Object object, List<? super String> errorMessageList) throws SerializeException, FileNotFoundException, IOException {
Document document = UtilXml.makeEmptyXmlDocument("ofbiz-ser");
Element rootElement = document.getDocumentElement();
rootElement.appendChild(serializeSingle(object, document, errorMessageList));
if (errorMessageList != null) {
try {
return UtilXml.writeXmlDocument(document);
} catch (IOException e) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
return null;
}
} else {
return UtilXml.writeXmlDocument(document);
}
}
// SCIPIO: 2019-03-08: New overload
public static String serialize(Object object, List<? super String> errorMessageList) throws SerializeException, FileNotFoundException, IOException {
if (errorMessageList != null) {
try {
return serializeCore(object, errorMessageList);
} catch(IOException e) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
return null;
}
} else {
return serializeCore(object, errorMessageList);
}
}
public static String serialize(Object object) throws SerializeException, FileNotFoundException, IOException {
return serializeCore(object, null); // SCIPIO: 2019-03-08: Refactored, delegated
}
// SCIPIO: 2019-03-08: New method
public static String serializeOrNull(Object object, List<? super String> errorMessageList) {
try {
return serializeCore(object, errorMessageList);
} catch (IOException | SerializeException e) {
if (errorMessageList != null) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
}
return null;
}
}
/** Deserialize a Java object from an XML string. <p>This method should be used with caution.
* If the XML string contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param content the content
* @param delegator the delegator
* @return return a deserialized object from XML string
* @throws SerializeException
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static Object deserialize(String content, Delegator delegator)
throws SerializeException, SAXException, ParserConfigurationException, IOException {
// readXmlDocument with false second parameter to disable validation
Document document = UtilXml.readXmlDocument(content, false);
if (document != null) {
if (!"ofbiz-ser".equals(document.getDocumentElement().getTagName())) {
return UtilXml.fromXml(content);
}
return deserialize(document, delegator);
}
Debug.logWarning("Serialized document came back null", module);
return null;
}
/** Deserialize a Java object from a DOM <code>Document</code>.
* <p>This method should be used with caution. If the DOM <code>Document</code>
* contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param document the document
* @param delegator the delegator
* @return returns a deserialized object from a DOM document
* @throws SerializeException
*/
public static Object deserialize(Document document, Delegator delegator) throws SerializeException {
Element rootElement = document.getDocumentElement();
// find the first element below the root element, that should be the object
Node curChild = rootElement.getFirstChild();
while (curChild != null && curChild.getNodeType() != Node.ELEMENT_NODE) {
curChild = curChild.getNextSibling();
}
if (curChild == null) {
return null;
}
return deserializeSingle((Element) curChild, delegator);
}
// SCIPIO: 2019-03-08: Added safe flag
public static Element serializeSingle(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (errorMessageList != null) {
try {
return serializeSingleCore(object, document, errorMessageList);
} catch(SerializeException e) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName() + ": " + e.toString());
return null;
}
} else {
return serializeSingleCore(object, document, errorMessageList); // SCIPIO: 2019-03-08: Refactored, delegated
}
}
public static Element serializeSingle(Object object, Document document) throws SerializeException {
return serializeSingleCore(object, document, null); // SCIPIO: 2019-03-08: Refactored, delegated
}
// SCIPIO: 2019-03-08: New method
public static Element serializeSingleOrNull(Object object, Document document, List<? super String> errorMessageList) {
try {
return serializeSingle(object, document, errorMessageList);
} catch (SerializeException e) {
return null; // already logged
}
}
// SCIPIO: Renamed to *Core, added safe flag
private static Element serializeSingleCore(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (document == null) {
return null;
}
if (object == null) {
return makeElement("null", null, document);
}
// - Standard Objects -
if (object instanceof String) {
return makeElement("std-String", object, document);
} else if (object instanceof Integer) {
return makeElement("std-Integer", object, document);
} else if (object instanceof Long) {
return makeElement("std-Long", object, document);
} else if (object instanceof Float) {
return makeElement("std-Float", object, document);
} else if (object instanceof Double) {
return makeElement("std-Double", object, document);
} else if (object instanceof Boolean) {
return makeElement("std-Boolean", object, document);
} else if (object instanceof Locale) {
return makeElement("std-Locale", object, document);
} else if (object instanceof BigDecimal) {
String stringValue = ((BigDecimal) object).setScale(10, RoundingMode.HALF_UP).toString();
return makeElement("std-BigDecimal", stringValue, document);
// - SQL Objects -
} else if (object instanceof java.sql.Timestamp) {
String stringValue = object.toString().replace(' ', 'T');
return makeElement("sql-Timestamp", stringValue, document);
} else if (object instanceof java.sql.Date) {
return makeElement("sql-Date", object, document);
} else if (object instanceof java.sql.Time) {
return makeElement("sql-Time", object, document);
} else if (object instanceof java.util.Date) {
// NOTE: make sure this is AFTER the java.sql date/time objects since they inherit from java.util.Date
DateFormat formatter = getDateFormat();
String stringValue = null;
synchronized (formatter) {
stringValue = formatter.format((java.util.Date) object);
}
return makeElement("std-Date", stringValue, document);
// return makeElement("std-Date", object, document);
} else if (object instanceof Collection<?>) {
// - Collections -
String elementName = null;
// these ARE order sensitive; for instance Stack extends Vector, so if Vector were first we would lose the stack part
if (object instanceof ArrayList<?>) {
elementName = "col-ArrayList";
} else if (object instanceof LinkedList<?>) {
elementName = "col-LinkedList";
} else if (object instanceof Stack<?>) {
elementName = "col-Stack";
} else if (object instanceof Vector<?>) {
elementName = "col-Vector";
} else if (object instanceof TreeSet<?>) {
elementName = "col-TreeSet";
} else if (object instanceof HashSet<?>) {
elementName = "col-HashSet";
} else {
// no specific type found, do general Collection, will deserialize as LinkedList
elementName = "col-Collection";
}
Collection<?> value = UtilGenerics.cast(object);
Element element = document.createElement(elementName);
Iterator<?> iter = value.iterator();
while (iter.hasNext()) {
element.appendChild(serializeSingleOrNullEntry(iter.next(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
}
return element;
} else if (object instanceof GenericPK) {
// Do GenericEntity objects as a special case, use std XML import/export routines
GenericPK value = (GenericPK) object;
return value.makeXmlElement(document, "eepk-");
} else if (object instanceof GenericValue) {
GenericValue value = (GenericValue) object;
return value.makeXmlElement(document, "eeval-");
} else if (object instanceof Map<?, ?>) {
// - Maps -
String elementName = null;
// these ARE order sensitive; for instance Properties extends Hashtable, so if Hashtable were first we would lose the Properties part
if (object instanceof HashMap<?, ?>) {
elementName = "map-HashMap";
} else if (object instanceof Properties) {
elementName = "map-Properties";
} else if (object instanceof Hashtable<?, ?>) {
elementName = "map-Hashtable";
} else if (object instanceof WeakHashMap<?, ?>) {
elementName = "map-WeakHashMap";
} else if (object instanceof TreeMap<?, ?>) {
elementName = "map-TreeMap";
} else {
// serialize as a simple Map implementation if nothing else applies, these will deserialize as a HashMap
elementName = "map-Map";
}
Element element = document.createElement(elementName);
Map<?,?> value = UtilGenerics.cast(object);
Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
while (iter.hasNext()) {
Map.Entry<?,?> entry = iter.next();
Element entryElement = document.createElement("map-Entry");
element.appendChild(entryElement);
Element key = document.createElement("map-Key");
entryElement.appendChild(key);
key.appendChild(serializeSingleOrNullEntry(entry.getKey(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
Element mapValue = document.createElement("map-Value");
entryElement.appendChild(mapValue);
mapValue.appendChild(serializeSingleOrNullEntry(entry.getValue(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
}
return element;
}
return serializeCustom(object, document, errorMessageList); // SCIPIO: 2019-03-08: Safe flag
}
// SCIPIO
private static Element serializeSingleOrNullEntry(Object value, Document document, List<? super String> errorMessageList) throws SerializeException {
Element serializedValue = serializeSingle(value, document, errorMessageList);
return (serializedValue != null) ? serializedValue : makeElement("null", null, document);
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)}; assumes the object is Serializable.
* Added 2019-03-08.
*/
private static Element serializeCustomCore(Object object, Document document) throws SerializeException {
// SCIPIO: Avoid this overload to avoid double-logging and to give a better error
//byte[] objBytes = UtilObject.getBytes(object);
byte[] objBytes;
try {
objBytes = UtilObject.getBytesOrEx(object);
} catch (Exception e) {
throw new SerializeException("Unable to serialize object: " + e.getMessage(), e);
}
if (objBytes == null) {
throw new SerializeException("Unable to serialize object; null byte array returned");
}
String byteHex = StringUtil.toHexString(objBytes);
Element element = document.createElement("cus-obj");
// this is hex encoded so does not need to be in a CDATA block
element.appendChild(document.createTextNode(byteHex));
return element;
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise, if safe true, logs
* a warning or error, while if safe false, throws a SerializeException.
*/
public static Element serializeCustom(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (object instanceof Serializable) {
if (errorMessageList != null) {
try {
return serializeCustomCore(object, document); // SCIPIO: 2019-03-08: Refactored
} catch(SerializeException e) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName() + ": " + e.toString());
}
} else {
return serializeCustomCore(object, document); // SCIPIO: 2019-03-08: Refactored
}
}
if (errorMessageList != null) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName());
} else {
throw new SerializeException("Cannot serialize object of class " + object.getClass().getName());
}
return null;
}
/**
* Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise throws a SerializeException.
* SCIPIO: NOTE: This is the original stock method.
*/
public static Element serializeCustom(Object object, Document document) throws SerializeException {
return serializeCustom(object, document, null);
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise returns null.
*/
public static Element serializeCustomOrNull(Object object, Document document, List<? super String> errorMessageList) {
try {
return serializeCustom(object, document, errorMessageList);
} catch (SerializeException e) {
return null; // already printed
}
}
public static Element makeElement(String elementName, Object value, Document document) {
if (value == null) {
Element element = document.createElement("null");
element.setAttribute("xsi:nil", "true");
// I tried to put the schema in the envelope header (in createAndSendSOAPResponse)
// resEnv.declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null);
// But it gets prefixed and that does not work. So adding in each instance
element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
return element;
}
Element element = document.createElement(elementName);
element.setAttribute("value", value.toString());
return element;
}
public static Object deserializeSingle(Element element, Delegator delegator) throws SerializeException {
String tagName = element.getLocalName();
if ("null".equals(tagName)) {
return null;
}
if (tagName.startsWith("std-")) {
// - Standard Objects -
if ("std-String".equals(tagName)) {
return element.getAttribute("value");
} else if ("std-Integer".equals(tagName)) {
String valStr = element.getAttribute("value");
return Integer.valueOf(valStr);
} else if ("std-Long".equals(tagName)) {
String valStr = element.getAttribute("value");
return Long.valueOf(valStr);
} else if ("std-Float".equals(tagName)) {
String valStr = element.getAttribute("value");
return Float.valueOf(valStr);
} else if ("std-Double".equals(tagName)) {
String valStr = element.getAttribute("value");
return Double.valueOf(valStr);
} else if ("std-BigDecimal".equals(tagName)) {
String valStr = element.getAttribute("value");
return new BigDecimal(valStr);
} else if ("std-Boolean".equals(tagName)) {
String valStr = element.getAttribute("value");
return Boolean.valueOf(valStr);
} else if ("std-Locale".equals(tagName)) {
String valStr = element.getAttribute("value");
return UtilMisc.parseLocale(valStr);
} else if ("std-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
DateFormat formatter = getDateFormat();
java.util.Date value = null;
try {
synchronized (formatter) {
value = formatter.parse(valStr);
}
} catch (ParseException e) {
throw new SerializeException("Could not parse date String: " + valStr, e);
}
return value;
}
} else if (tagName.startsWith("sql-")) {
// - SQL Objects -
if ("sql-Timestamp".equals(tagName)) {
String valStr = element.getAttribute("value");
/*
* sql-Timestamp is defined as xsd:dateTime in ModelService.getTypes(),
* so try to parse the value as xsd:dateTime first.
* Fallback is java.sql.Timestamp because it has been this way all the time.
*/
try {
Calendar cal = DatatypeConverter.parseDate(valStr);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
catch (Exception e) {
Debug.logWarning("sql-Timestamp does not conform to XML Schema definition, try java.sql.Timestamp format", module);
return java.sql.Timestamp.valueOf(valStr);
}
} else if ("sql-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Date.valueOf(valStr);
} else if ("sql-Time".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Time.valueOf(valStr);
}
} else if (tagName.startsWith("col-")) {
// - Collections -
Collection<Object> value = null;
if ("col-ArrayList".equals(tagName)) {
value = new ArrayList<>();
} else if ("col-LinkedList".equals(tagName)) {
value = new LinkedList<>();
} else if ("col-Stack".equals(tagName)) {
value = new Stack<>();
} else if ("col-Vector".equals(tagName)) {
value = new Vector<>();
} else if ("col-TreeSet".equals(tagName)) {
value = new TreeSet<>();
} else if ("col-HashSet".equals(tagName)) {
value = new HashSet<>();
} else if ("col-Collection".equals(tagName)) {
value = new LinkedList<>();
}
if (value == null) {
return deserializeCustom(element);
}
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
value.add(deserializeSingle((Element) curChild, delegator));
}
curChild = curChild.getNextSibling();
}
return value;
} else if (tagName.startsWith("map-")) {
// - Maps -
Map<Object, Object> value = null;
if ("map-HashMap".equals(tagName)) {
value = new HashMap<>();
} else if ("map-Properties".equals(tagName)) {
value = new Properties();
} else if ("map-Hashtable".equals(tagName)) {
value = new Hashtable<>();
} else if ("map-WeakHashMap".equals(tagName)) {
value = new WeakHashMap<>();
} else if ("map-TreeMap".equals(tagName)) {
value = new TreeMap<>();
} else if ("map-Map".equals(tagName)) {
value = new HashMap<>();
}
if (value == null) {
return deserializeCustom(element);
}
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) curChild;
if ("map-Entry".equals(curElement.getLocalName())) {
Element mapKeyElement = UtilXml.firstChildElement(curElement, "map-Key");
Element keyElement = null;
Node tempNode = mapKeyElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
keyElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (keyElement == null) {
throw new SerializeException("Could not find an element under the map-Key");
}
Element mapValueElement = UtilXml.firstChildElement(curElement, "map-Value");
Element valueElement = null;
tempNode = mapValueElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
valueElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (valueElement == null) {
throw new SerializeException("Could not find an element under the map-Value");
}
value.put(deserializeSingle(keyElement, delegator), deserializeSingle(valueElement, delegator));
}
}
curChild = curChild.getNextSibling();
}
return value;
} else if (tagName.startsWith("eepk-")) {
return delegator.makePK(element);
} else if (tagName.startsWith("eeval-")) {
return delegator.makeValue(element);
}
return deserializeCustom(element);
}
public static Object deserializeCustom(Element element) throws SerializeException {
String tagName = element.getLocalName();
if ("cus-obj".equals(tagName)) {
String value = UtilXml.elementValue(element);
if (value != null) {
byte[] valueBytes = StringUtil.fromHexString(value);
if (valueBytes != null) {
Object obj = UtilObject.getObject(valueBytes);
if (obj != null) {
return obj;
}
}
}
throw new SerializeException("Problem deserializing object from byte array + " + element.getLocalName());
}
throw new SerializeException("Cannot deserialize element named " + element.getLocalName());
}
/**
* Returns the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
* This format is NOT used to format any of the java.sql subtypes of java.util.Date.
* A <code>WeakReference</code> is used to maintain a reference to the DateFormat object
* so that it can be created and garbage collected as needed.
*
* @return the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
*/
private static DateFormat getDateFormat() {
DateFormat formatter = null;
if (simpleDateFormatter != null) {
formatter = simpleDateFormatter.get();
}
if (formatter == null) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
simpleDateFormatter = new WeakReference<>(formatter);
}
return formatter;
}
}
| readloud/scipio-erp | framework/entity/src/org/ofbiz/entity/serialize/XmlSerializer.java | 7,239 | // return makeElement("std-Date", object, document); | line_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.ofbiz.entity.serialize;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.Vector;
import java.util.WeakHashMap;
import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.ParserConfigurationException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilObject;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
/**
* XmlSerializer class. This class is deprecated - new code should use the
* Java object marshalling/unmarshalling methods in <code>UtilXml.java</code>.
*
*/
public class XmlSerializer {
private static final Debug.OfbizLogger module = Debug.getOfbizLogger(java.lang.invoke.MethodHandles.lookup().lookupClass());
private volatile static WeakReference<DateFormat> simpleDateFormatter;
// SCIPIO: 2019-03-08: Renamed to *Core, added errorMessageList (if non-null, accumulates errors instead of throwing exception)
private static String serializeCore(Object object, List<? super String> errorMessageList) throws SerializeException, FileNotFoundException, IOException {
Document document = UtilXml.makeEmptyXmlDocument("ofbiz-ser");
Element rootElement = document.getDocumentElement();
rootElement.appendChild(serializeSingle(object, document, errorMessageList));
if (errorMessageList != null) {
try {
return UtilXml.writeXmlDocument(document);
} catch (IOException e) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
return null;
}
} else {
return UtilXml.writeXmlDocument(document);
}
}
// SCIPIO: 2019-03-08: New overload
public static String serialize(Object object, List<? super String> errorMessageList) throws SerializeException, FileNotFoundException, IOException {
if (errorMessageList != null) {
try {
return serializeCore(object, errorMessageList);
} catch(IOException e) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
return null;
}
} else {
return serializeCore(object, errorMessageList);
}
}
public static String serialize(Object object) throws SerializeException, FileNotFoundException, IOException {
return serializeCore(object, null); // SCIPIO: 2019-03-08: Refactored, delegated
}
// SCIPIO: 2019-03-08: New method
public static String serializeOrNull(Object object, List<? super String> errorMessageList) {
try {
return serializeCore(object, errorMessageList);
} catch (IOException | SerializeException e) {
if (errorMessageList != null) {
errorMessageList.add("Unable to write serialized XML for value: " + e.toString());
}
return null;
}
}
/** Deserialize a Java object from an XML string. <p>This method should be used with caution.
* If the XML string contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param content the content
* @param delegator the delegator
* @return return a deserialized object from XML string
* @throws SerializeException
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static Object deserialize(String content, Delegator delegator)
throws SerializeException, SAXException, ParserConfigurationException, IOException {
// readXmlDocument with false second parameter to disable validation
Document document = UtilXml.readXmlDocument(content, false);
if (document != null) {
if (!"ofbiz-ser".equals(document.getDocumentElement().getTagName())) {
return UtilXml.fromXml(content);
}
return deserialize(document, delegator);
}
Debug.logWarning("Serialized document came back null", module);
return null;
}
/** Deserialize a Java object from a DOM <code>Document</code>.
* <p>This method should be used with caution. If the DOM <code>Document</code>
* contains a serialized <code>GenericValue</code> or <code>GenericPK</code>
* then it is possible to unintentionally corrupt the database.</p>
*
* @param document the document
* @param delegator the delegator
* @return returns a deserialized object from a DOM document
* @throws SerializeException
*/
public static Object deserialize(Document document, Delegator delegator) throws SerializeException {
Element rootElement = document.getDocumentElement();
// find the first element below the root element, that should be the object
Node curChild = rootElement.getFirstChild();
while (curChild != null && curChild.getNodeType() != Node.ELEMENT_NODE) {
curChild = curChild.getNextSibling();
}
if (curChild == null) {
return null;
}
return deserializeSingle((Element) curChild, delegator);
}
// SCIPIO: 2019-03-08: Added safe flag
public static Element serializeSingle(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (errorMessageList != null) {
try {
return serializeSingleCore(object, document, errorMessageList);
} catch(SerializeException e) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName() + ": " + e.toString());
return null;
}
} else {
return serializeSingleCore(object, document, errorMessageList); // SCIPIO: 2019-03-08: Refactored, delegated
}
}
public static Element serializeSingle(Object object, Document document) throws SerializeException {
return serializeSingleCore(object, document, null); // SCIPIO: 2019-03-08: Refactored, delegated
}
// SCIPIO: 2019-03-08: New method
public static Element serializeSingleOrNull(Object object, Document document, List<? super String> errorMessageList) {
try {
return serializeSingle(object, document, errorMessageList);
} catch (SerializeException e) {
return null; // already logged
}
}
// SCIPIO: Renamed to *Core, added safe flag
private static Element serializeSingleCore(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (document == null) {
return null;
}
if (object == null) {
return makeElement("null", null, document);
}
// - Standard Objects -
if (object instanceof String) {
return makeElement("std-String", object, document);
} else if (object instanceof Integer) {
return makeElement("std-Integer", object, document);
} else if (object instanceof Long) {
return makeElement("std-Long", object, document);
} else if (object instanceof Float) {
return makeElement("std-Float", object, document);
} else if (object instanceof Double) {
return makeElement("std-Double", object, document);
} else if (object instanceof Boolean) {
return makeElement("std-Boolean", object, document);
} else if (object instanceof Locale) {
return makeElement("std-Locale", object, document);
} else if (object instanceof BigDecimal) {
String stringValue = ((BigDecimal) object).setScale(10, RoundingMode.HALF_UP).toString();
return makeElement("std-BigDecimal", stringValue, document);
// - SQL Objects -
} else if (object instanceof java.sql.Timestamp) {
String stringValue = object.toString().replace(' ', 'T');
return makeElement("sql-Timestamp", stringValue, document);
} else if (object instanceof java.sql.Date) {
return makeElement("sql-Date", object, document);
} else if (object instanceof java.sql.Time) {
return makeElement("sql-Time", object, document);
} else if (object instanceof java.util.Date) {
// NOTE: make sure this is AFTER the java.sql date/time objects since they inherit from java.util.Date
DateFormat formatter = getDateFormat();
String stringValue = null;
synchronized (formatter) {
stringValue = formatter.format((java.util.Date) object);
}
return makeElement("std-Date", stringValue, document);
// return makeElement("std-Date",<SUF>
} else if (object instanceof Collection<?>) {
// - Collections -
String elementName = null;
// these ARE order sensitive; for instance Stack extends Vector, so if Vector were first we would lose the stack part
if (object instanceof ArrayList<?>) {
elementName = "col-ArrayList";
} else if (object instanceof LinkedList<?>) {
elementName = "col-LinkedList";
} else if (object instanceof Stack<?>) {
elementName = "col-Stack";
} else if (object instanceof Vector<?>) {
elementName = "col-Vector";
} else if (object instanceof TreeSet<?>) {
elementName = "col-TreeSet";
} else if (object instanceof HashSet<?>) {
elementName = "col-HashSet";
} else {
// no specific type found, do general Collection, will deserialize as LinkedList
elementName = "col-Collection";
}
Collection<?> value = UtilGenerics.cast(object);
Element element = document.createElement(elementName);
Iterator<?> iter = value.iterator();
while (iter.hasNext()) {
element.appendChild(serializeSingleOrNullEntry(iter.next(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
}
return element;
} else if (object instanceof GenericPK) {
// Do GenericEntity objects as a special case, use std XML import/export routines
GenericPK value = (GenericPK) object;
return value.makeXmlElement(document, "eepk-");
} else if (object instanceof GenericValue) {
GenericValue value = (GenericValue) object;
return value.makeXmlElement(document, "eeval-");
} else if (object instanceof Map<?, ?>) {
// - Maps -
String elementName = null;
// these ARE order sensitive; for instance Properties extends Hashtable, so if Hashtable were first we would lose the Properties part
if (object instanceof HashMap<?, ?>) {
elementName = "map-HashMap";
} else if (object instanceof Properties) {
elementName = "map-Properties";
} else if (object instanceof Hashtable<?, ?>) {
elementName = "map-Hashtable";
} else if (object instanceof WeakHashMap<?, ?>) {
elementName = "map-WeakHashMap";
} else if (object instanceof TreeMap<?, ?>) {
elementName = "map-TreeMap";
} else {
// serialize as a simple Map implementation if nothing else applies, these will deserialize as a HashMap
elementName = "map-Map";
}
Element element = document.createElement(elementName);
Map<?,?> value = UtilGenerics.cast(object);
Iterator<Map.Entry<?, ?>> iter = UtilGenerics.cast(value.entrySet().iterator());
while (iter.hasNext()) {
Map.Entry<?,?> entry = iter.next();
Element entryElement = document.createElement("map-Entry");
element.appendChild(entryElement);
Element key = document.createElement("map-Key");
entryElement.appendChild(key);
key.appendChild(serializeSingleOrNullEntry(entry.getKey(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
Element mapValue = document.createElement("map-Value");
entryElement.appendChild(mapValue);
mapValue.appendChild(serializeSingleOrNullEntry(entry.getValue(), document, errorMessageList)); // SCIPIO: 2019-03-08: Added safe flag
}
return element;
}
return serializeCustom(object, document, errorMessageList); // SCIPIO: 2019-03-08: Safe flag
}
// SCIPIO
private static Element serializeSingleOrNullEntry(Object value, Document document, List<? super String> errorMessageList) throws SerializeException {
Element serializedValue = serializeSingle(value, document, errorMessageList);
return (serializedValue != null) ? serializedValue : makeElement("null", null, document);
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)}; assumes the object is Serializable.
* Added 2019-03-08.
*/
private static Element serializeCustomCore(Object object, Document document) throws SerializeException {
// SCIPIO: Avoid this overload to avoid double-logging and to give a better error
//byte[] objBytes = UtilObject.getBytes(object);
byte[] objBytes;
try {
objBytes = UtilObject.getBytesOrEx(object);
} catch (Exception e) {
throw new SerializeException("Unable to serialize object: " + e.getMessage(), e);
}
if (objBytes == null) {
throw new SerializeException("Unable to serialize object; null byte array returned");
}
String byteHex = StringUtil.toHexString(objBytes);
Element element = document.createElement("cus-obj");
// this is hex encoded so does not need to be in a CDATA block
element.appendChild(document.createTextNode(byteHex));
return element;
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise, if safe true, logs
* a warning or error, while if safe false, throws a SerializeException.
*/
public static Element serializeCustom(Object object, Document document, List<? super String> errorMessageList) throws SerializeException {
if (object instanceof Serializable) {
if (errorMessageList != null) {
try {
return serializeCustomCore(object, document); // SCIPIO: 2019-03-08: Refactored
} catch(SerializeException e) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName() + ": " + e.toString());
}
} else {
return serializeCustomCore(object, document); // SCIPIO: 2019-03-08: Refactored
}
}
if (errorMessageList != null) {
errorMessageList.add("Cannot serialize object of class " + object.getClass().getName());
} else {
throw new SerializeException("Cannot serialize object of class " + object.getClass().getName());
}
return null;
}
/**
* Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise throws a SerializeException.
* SCIPIO: NOTE: This is the original stock method.
*/
public static Element serializeCustom(Object object, Document document) throws SerializeException {
return serializeCustom(object, document, null);
}
/**
* SCIPIO: Performs serialization using {@link org.ofbiz.base.util.UtilObject#getBytes(Object)} if the object is serializable; otherwise returns null.
*/
public static Element serializeCustomOrNull(Object object, Document document, List<? super String> errorMessageList) {
try {
return serializeCustom(object, document, errorMessageList);
} catch (SerializeException e) {
return null; // already printed
}
}
public static Element makeElement(String elementName, Object value, Document document) {
if (value == null) {
Element element = document.createElement("null");
element.setAttribute("xsi:nil", "true");
// I tried to put the schema in the envelope header (in createAndSendSOAPResponse)
// resEnv.declareNamespace("http://www.w3.org/2001/XMLSchema-instance", null);
// But it gets prefixed and that does not work. So adding in each instance
element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
return element;
}
Element element = document.createElement(elementName);
element.setAttribute("value", value.toString());
return element;
}
public static Object deserializeSingle(Element element, Delegator delegator) throws SerializeException {
String tagName = element.getLocalName();
if ("null".equals(tagName)) {
return null;
}
if (tagName.startsWith("std-")) {
// - Standard Objects -
if ("std-String".equals(tagName)) {
return element.getAttribute("value");
} else if ("std-Integer".equals(tagName)) {
String valStr = element.getAttribute("value");
return Integer.valueOf(valStr);
} else if ("std-Long".equals(tagName)) {
String valStr = element.getAttribute("value");
return Long.valueOf(valStr);
} else if ("std-Float".equals(tagName)) {
String valStr = element.getAttribute("value");
return Float.valueOf(valStr);
} else if ("std-Double".equals(tagName)) {
String valStr = element.getAttribute("value");
return Double.valueOf(valStr);
} else if ("std-BigDecimal".equals(tagName)) {
String valStr = element.getAttribute("value");
return new BigDecimal(valStr);
} else if ("std-Boolean".equals(tagName)) {
String valStr = element.getAttribute("value");
return Boolean.valueOf(valStr);
} else if ("std-Locale".equals(tagName)) {
String valStr = element.getAttribute("value");
return UtilMisc.parseLocale(valStr);
} else if ("std-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
DateFormat formatter = getDateFormat();
java.util.Date value = null;
try {
synchronized (formatter) {
value = formatter.parse(valStr);
}
} catch (ParseException e) {
throw new SerializeException("Could not parse date String: " + valStr, e);
}
return value;
}
} else if (tagName.startsWith("sql-")) {
// - SQL Objects -
if ("sql-Timestamp".equals(tagName)) {
String valStr = element.getAttribute("value");
/*
* sql-Timestamp is defined as xsd:dateTime in ModelService.getTypes(),
* so try to parse the value as xsd:dateTime first.
* Fallback is java.sql.Timestamp because it has been this way all the time.
*/
try {
Calendar cal = DatatypeConverter.parseDate(valStr);
return new java.sql.Timestamp(cal.getTimeInMillis());
}
catch (Exception e) {
Debug.logWarning("sql-Timestamp does not conform to XML Schema definition, try java.sql.Timestamp format", module);
return java.sql.Timestamp.valueOf(valStr);
}
} else if ("sql-Date".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Date.valueOf(valStr);
} else if ("sql-Time".equals(tagName)) {
String valStr = element.getAttribute("value");
return java.sql.Time.valueOf(valStr);
}
} else if (tagName.startsWith("col-")) {
// - Collections -
Collection<Object> value = null;
if ("col-ArrayList".equals(tagName)) {
value = new ArrayList<>();
} else if ("col-LinkedList".equals(tagName)) {
value = new LinkedList<>();
} else if ("col-Stack".equals(tagName)) {
value = new Stack<>();
} else if ("col-Vector".equals(tagName)) {
value = new Vector<>();
} else if ("col-TreeSet".equals(tagName)) {
value = new TreeSet<>();
} else if ("col-HashSet".equals(tagName)) {
value = new HashSet<>();
} else if ("col-Collection".equals(tagName)) {
value = new LinkedList<>();
}
if (value == null) {
return deserializeCustom(element);
}
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
value.add(deserializeSingle((Element) curChild, delegator));
}
curChild = curChild.getNextSibling();
}
return value;
} else if (tagName.startsWith("map-")) {
// - Maps -
Map<Object, Object> value = null;
if ("map-HashMap".equals(tagName)) {
value = new HashMap<>();
} else if ("map-Properties".equals(tagName)) {
value = new Properties();
} else if ("map-Hashtable".equals(tagName)) {
value = new Hashtable<>();
} else if ("map-WeakHashMap".equals(tagName)) {
value = new WeakHashMap<>();
} else if ("map-TreeMap".equals(tagName)) {
value = new TreeMap<>();
} else if ("map-Map".equals(tagName)) {
value = new HashMap<>();
}
if (value == null) {
return deserializeCustom(element);
}
Node curChild = element.getFirstChild();
while (curChild != null) {
if (curChild.getNodeType() == Node.ELEMENT_NODE) {
Element curElement = (Element) curChild;
if ("map-Entry".equals(curElement.getLocalName())) {
Element mapKeyElement = UtilXml.firstChildElement(curElement, "map-Key");
Element keyElement = null;
Node tempNode = mapKeyElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
keyElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (keyElement == null) {
throw new SerializeException("Could not find an element under the map-Key");
}
Element mapValueElement = UtilXml.firstChildElement(curElement, "map-Value");
Element valueElement = null;
tempNode = mapValueElement.getFirstChild();
while (tempNode != null) {
if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
valueElement = (Element) tempNode;
break;
}
tempNode = tempNode.getNextSibling();
}
if (valueElement == null) {
throw new SerializeException("Could not find an element under the map-Value");
}
value.put(deserializeSingle(keyElement, delegator), deserializeSingle(valueElement, delegator));
}
}
curChild = curChild.getNextSibling();
}
return value;
} else if (tagName.startsWith("eepk-")) {
return delegator.makePK(element);
} else if (tagName.startsWith("eeval-")) {
return delegator.makeValue(element);
}
return deserializeCustom(element);
}
public static Object deserializeCustom(Element element) throws SerializeException {
String tagName = element.getLocalName();
if ("cus-obj".equals(tagName)) {
String value = UtilXml.elementValue(element);
if (value != null) {
byte[] valueBytes = StringUtil.fromHexString(value);
if (valueBytes != null) {
Object obj = UtilObject.getObject(valueBytes);
if (obj != null) {
return obj;
}
}
}
throw new SerializeException("Problem deserializing object from byte array + " + element.getLocalName());
}
throw new SerializeException("Cannot deserialize element named " + element.getLocalName());
}
/**
* Returns the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
* This format is NOT used to format any of the java.sql subtypes of java.util.Date.
* A <code>WeakReference</code> is used to maintain a reference to the DateFormat object
* so that it can be created and garbage collected as needed.
*
* @return the DateFormat used to serialize and deserialize <code>java.util.Date</code> objects.
*/
private static DateFormat getDateFormat() {
DateFormat formatter = null;
if (simpleDateFormatter != null) {
formatter = simpleDateFormatter.get();
}
if (formatter == null) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
simpleDateFormatter = new WeakReference<>(formatter);
}
return formatter;
}
}
|
61877_6 | package Firebase;
import Objects.RaceFiche;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.database.annotations.NotNull;
import com.google.firebase.database.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ExecutionException;
public class FirebaseServiceOwn {
private Firestore firestore;
private CollectionReference colRef;
private DocumentReference gameRef;
public FirebaseServiceOwn() {
Database db = new Database();
this.firestore = db.getFirestoreDatabase();
this.colRef = this.firestore.collection("Games");
}
public void setGame(String lobbyName){
gameRef = colRef.document(lobbyName);
}
public Firestore getFireStore(){
return firestore;
}
/**
* Geeft een update naar de meegeleverde controller
* op het moment dat er een wijziging in het firebase document plaatsvindt.
*
* @param documentId
* @param controller
*/
public void listen(String documentId, final FirebaseControllerObserver controller) {
DocumentReference docRef = this.colRef.document(documentId);
docRef.addSnapshotListener((snapshot, e) -> {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
if (snapshot != null && snapshot.exists()) {
controller.update(snapshot);
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
});
}
public void playerListen(String player, final FirebaseControllerObserver controller) {
DocumentReference docRef = gameRef.collection("Spelers").document(player);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) controller.update(snapshot);
else System.out.print("Current data: null");
}
});
}
//AreaRegister
public void AreaListener(String areaId, final FirebaseControllerObserver controller){
DocumentReference docRef = gameRef.collection("Areas").document(areaId);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) controller.update(snapshot);
else System.out.print("Current data: null");
}
});
}
//player Updates
public void playerUpdateFiches(String player, int fichesCount){
DocumentReference docRef = gameRef.collection("Spelers").document(player);
docRef.update("fiche", fichesCount);
}
//areaUpdates
public void areaUpdateFiches(String areaId, int count){
DocumentReference docRef = gameRef.collection("Areas").document(areaId);
docRef.update("fiches", count);
}
//Areas setten in firebase
public void setAreas(String areaId, Map<String, Object> area){
gameRef.collection("Areas").document(areaId).set(area);
}
/**
* Overschrijft een document als het als bestaat of maakt een nieuwe aan.
* Wees hier dus voorzichtig mee.
*
* @param documentId
* @param docData
*/
public void set(String documentId, Map<String, Object> docData) {
this.colRef.document(documentId).set(docData);
}
/**
* Verkrijgen van 1 document op basis van een documentId.
*
* @param documentId
* @return
*/
public DocumentSnapshot getColRef(String documentId) {
DocumentReference docRef = this.colRef.document(documentId);
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return document;
else System.out.println("No such document!");
return null;
}
/**
* Verwijdert een document op basis van het documentId.
*
* @param documentId
*/
public void delete(String documentId) {
this.colRef.document(documentId).delete();
}
/**
* Controlleert of opgegeven gevens kloppen.
*
* @param username
* @param password
* @return
*/
public boolean login(@NotNull String username, @NotNull String password) {
DocumentReference docRef = firestore.collection("Accounts").document(username);
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return document.get("password").equals(password);
return false;
}
/**
* Registeerd gebruiker, returned false als gebruikers naam bezet is.
*
* @param username
* @param password
* @return
*/
public boolean register(String username, String password) {
DocumentReference docRef = firestore.collection("Accounts").document(username);
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return false;
Map<String, String> pass = new HashMap<>();
pass.put("password", password);
firestore.collection("Accounts").document(username).set(pass);
return true;
}
/**
* Gebruikt voor cleanup, de try/catch van future.get() gecentraliseerd.
*
* @param docRef
* @return
*/
private DocumentSnapshot getDocSnapshot(DocumentReference docRef) {
ApiFuture<DocumentSnapshot> future = docRef.get();
try {
return future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
| realDragonium/SmallWorld | src/main/java/Firebase/FirebaseServiceOwn.java | 1,663 | /**
* Registeerd gebruiker, returned false als gebruikers naam bezet is.
*
* @param username
* @param password
* @return
*/ | block_comment | nl | package Firebase;
import Objects.RaceFiche;
import com.google.api.core.ApiFuture;
import com.google.cloud.firestore.*;
import com.google.firebase.database.annotations.NotNull;
import com.google.firebase.database.annotations.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.ExecutionException;
public class FirebaseServiceOwn {
private Firestore firestore;
private CollectionReference colRef;
private DocumentReference gameRef;
public FirebaseServiceOwn() {
Database db = new Database();
this.firestore = db.getFirestoreDatabase();
this.colRef = this.firestore.collection("Games");
}
public void setGame(String lobbyName){
gameRef = colRef.document(lobbyName);
}
public Firestore getFireStore(){
return firestore;
}
/**
* Geeft een update naar de meegeleverde controller
* op het moment dat er een wijziging in het firebase document plaatsvindt.
*
* @param documentId
* @param controller
*/
public void listen(String documentId, final FirebaseControllerObserver controller) {
DocumentReference docRef = this.colRef.document(documentId);
docRef.addSnapshotListener((snapshot, e) -> {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
if (snapshot != null && snapshot.exists()) {
controller.update(snapshot);
System.out.println("Current data: " + snapshot.getData());
} else {
System.out.print("Current data: null");
}
});
}
public void playerListen(String player, final FirebaseControllerObserver controller) {
DocumentReference docRef = gameRef.collection("Spelers").document(player);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) controller.update(snapshot);
else System.out.print("Current data: null");
}
});
}
//AreaRegister
public void AreaListener(String areaId, final FirebaseControllerObserver controller){
DocumentReference docRef = gameRef.collection("Areas").document(areaId);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirestoreException error) {
if (error != null) {
System.err.println("Listen failed: " + error);
return;
}
if (snapshot != null && snapshot.exists()) controller.update(snapshot);
else System.out.print("Current data: null");
}
});
}
//player Updates
public void playerUpdateFiches(String player, int fichesCount){
DocumentReference docRef = gameRef.collection("Spelers").document(player);
docRef.update("fiche", fichesCount);
}
//areaUpdates
public void areaUpdateFiches(String areaId, int count){
DocumentReference docRef = gameRef.collection("Areas").document(areaId);
docRef.update("fiches", count);
}
//Areas setten in firebase
public void setAreas(String areaId, Map<String, Object> area){
gameRef.collection("Areas").document(areaId).set(area);
}
/**
* Overschrijft een document als het als bestaat of maakt een nieuwe aan.
* Wees hier dus voorzichtig mee.
*
* @param documentId
* @param docData
*/
public void set(String documentId, Map<String, Object> docData) {
this.colRef.document(documentId).set(docData);
}
/**
* Verkrijgen van 1 document op basis van een documentId.
*
* @param documentId
* @return
*/
public DocumentSnapshot getColRef(String documentId) {
DocumentReference docRef = this.colRef.document(documentId);
ApiFuture<DocumentSnapshot> future = docRef.get();
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return document;
else System.out.println("No such document!");
return null;
}
/**
* Verwijdert een document op basis van het documentId.
*
* @param documentId
*/
public void delete(String documentId) {
this.colRef.document(documentId).delete();
}
/**
* Controlleert of opgegeven gevens kloppen.
*
* @param username
* @param password
* @return
*/
public boolean login(@NotNull String username, @NotNull String password) {
DocumentReference docRef = firestore.collection("Accounts").document(username);
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return document.get("password").equals(password);
return false;
}
/**
* Registeerd gebruiker, returned<SUF>*/
public boolean register(String username, String password) {
DocumentReference docRef = firestore.collection("Accounts").document(username);
DocumentSnapshot document = getDocSnapshot(docRef);
if (document.exists()) return false;
Map<String, String> pass = new HashMap<>();
pass.put("password", password);
firestore.collection("Accounts").document(username).set(pass);
return true;
}
/**
* Gebruikt voor cleanup, de try/catch van future.get() gecentraliseerd.
*
* @param docRef
* @return
*/
private DocumentSnapshot getDocSnapshot(DocumentReference docRef) {
ApiFuture<DocumentSnapshot> future = docRef.get();
try {
return future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}
|
74020_0 | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3 is het grootste aantal
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
| realDragonium/SmallWorld3D | src/main/java/Controller/FirebaseGameController.java | 1,106 | //Met 3 is het grootste aantal | line_comment | nl | package Controller;
import Firebase.FirebaseActionObserver;
import Firebase.FirebaseGameObserver;
import Firebase.FirebaseGameService;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentSnapshot;
import com.google.cloud.firestore.QuerySnapshot;
import javafx.application.Platform;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirebaseGameController implements FirebaseActionObserver {
private GameController gameCon;
private FirebaseGameService service;
private Map<String, FirebaseGameObserver> observers = new HashMap<>();
public FirebaseGameController(String gameName, GameController gameCon) {
this.gameCon = gameCon;
service = new FirebaseGameService(gameName);
turnActionListener(this);
}
private void placeAction(Map<String, Object> map) {
service.placeAction(getEventNumber(), map);
}
//Met 3<SUF>
private String getEventNumber(){
String id = String.valueOf(service.getLastestEventNumber());
StringBuilder str = new StringBuilder(id);
while(str.length() < 3) str.insert(0, "0");
return str.toString();
}
public void nextPhaseAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "phase");
map.put("id", "nextPhase");
map.put("action", "nextPhase");
placeAction(map);
}
public void buyCombiAction(int number) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "buy");
map.put("item", number);
placeAction(map);
}
public void addCombiAction(String race, String power) {
Map<String, Object> map = new HashMap<>();
map.put("division", "shop");
map.put("id", "add");
map.put("race", race);
map.put("power", power);
placeAction(map);
}
public void attackAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "attack");
map.put("areaId", areaId);
placeAction(map);
}
public void addsFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "add");
map.put("areaId", areaId);
placeAction(map);
}
public void removeFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "remove");
map.put("areaId", areaId);
placeAction(map);
}
public void leavesFicheAction(String areaId) {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "leaves");
map.put("areaId", areaId);
placeAction(map);
}
public void declineAction() {
Map<String, Object> map = new HashMap<>();
map.put("division", "currentplayer");
map.put("id", "decline");
map.put("action", "decline");
placeAction(map);
}
private void turnActionListener(final FirebaseActionObserver controller) {
service.actionListener(controller);
}
public void register(String id, FirebaseGameObserver observer) {
observers.put(id, observer);
}
@Override
public void update(QuerySnapshot qs) {
List<DocumentChange> updateList = qs.getDocumentChanges();
for (DocumentChange documentChange : updateList) {
DocumentSnapshot doc = documentChange.getDocument();
System.out.println("Id: " + doc.getId());
System.out.println(doc.getData());
Platform.runLater(() -> observers.get(doc.getString("division")).update(doc));
}
}
}
|
81017_10 | /*
* Copyright 2017 Realm 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 io.realm.internal;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.UUID;
import javax.annotation.Nullable;
import io.realm.OrderedRealmCollectionChangeListener;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmModel;
import io.realm.Sort;
import io.realm.internal.objectstore.OsKeyPathMapping;
import io.realm.internal.objectstore.OsObjectBuilder;
/**
* Java wrapper of Object Store Results class.
* It is the backend of binding's query results and back links.
*/
public class OsResults implements NativeObject, ObservableCollection {
private static final String CLOSED_REALM_MESSAGE =
"This Realm instance has already been closed, making it unusable.";
// Custom OsResults iterator. It ensures that we only iterate on a Realm OsResults that hasn't changed.
public abstract static class Iterator<T> implements java.util.Iterator<T> {
protected OsResults iteratorOsResults;
protected int pos = -1;
public Iterator(OsResults osResults) {
if (osResults.sharedRealm.isClosed()) {
throw new IllegalStateException(CLOSED_REALM_MESSAGE);
}
this.iteratorOsResults = osResults;
if (osResults.isSnapshot) {
// No need to detach a snapshot.
return;
}
if (osResults.sharedRealm.isInTransaction()) {
detach();
} else {
iteratorOsResults.sharedRealm.addIterator(this);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
checkValid();
return pos + 1 < iteratorOsResults.size();
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public T next() {
checkValid();
pos++;
if (pos >= iteratorOsResults.size()) {
throw new NoSuchElementException("Cannot access index " + pos + " when size is " + iteratorOsResults.size() +
". Remember to check hasNext() before using next().");
}
return get(pos);
}
/**
* Not supported by Realm collection iterators.
*/
@Override
@Deprecated
public void remove() {
throw new UnsupportedOperationException("remove() is not supported by RealmResults iterators.");
}
void detach() {
iteratorOsResults = iteratorOsResults.createSnapshot();
}
// The iterator becomes invalid after receiving a remote change notification. In Java, the destruction of
// iterator totally depends on GC. If we just detach those iterators when remote change notification received
// like what realm-cocoa does, we will have a massive overhead since all the iterators created in the previous
// event loop need to be detached.
void invalidate() {
iteratorOsResults = null;
}
void checkValid() {
if (iteratorOsResults == null) {
throw new ConcurrentModificationException(
"No outside changes to a Realm is allowed while iterating a living Realm collection.");
}
}
@Nullable
T get(int pos) {
return getInternal(pos, iteratorOsResults);
}
// Returns the RealmModel by given row in this list. This has to be implemented in the upper layer since
// we don't have information about the object types in the internal package.
protected abstract T convertRowToObject(UncheckedRow row);
protected abstract T getInternal(int pos, OsResults iteratorOsResults);
}
// Custom Realm collection list iterator.
public abstract static class ListIterator<T> extends Iterator<T> implements java.util.ListIterator<T> {
public ListIterator(OsResults osResults, int start) {
super(osResults);
if (start >= 0 && start <= iteratorOsResults.size()) {
pos = start - 1;
} else {
throw new IndexOutOfBoundsException("Starting location must be a valid index: [0, "
+ (iteratorOsResults.size() - 1) + "]. Yours was " + start);
}
}
/**
* Unsupported by Realm collection iterators.
*/
@Override
@Deprecated
public void add(@Nullable T object) {
throw new UnsupportedOperationException("Adding an element is not supported. Use Realm.createObject() instead.");
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasPrevious() {
checkValid();
return pos >= 0;
}
/**
* {@inheritDoc}
*/
@Override
public int nextIndex() {
checkValid();
return pos + 1;
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public T previous() {
checkValid();
try {
T obj = get(pos);
pos--;
return obj;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException("Cannot access index less than zero. This was " + pos +
". Remember to check hasPrevious() before using previous().");
}
}
/**
* {@inheritDoc}
*/
@Override
public int previousIndex() {
checkValid();
return pos;
}
/**
* Unsupported by RealmResults iterators.
*/
@Override
@Deprecated
public void set(@Nullable T object) {
throw new UnsupportedOperationException("Replacing an element is not supported.");
}
}
private final long nativePtr;
private static final long nativeFinalizerPtr = nativeGetFinalizerPtr();
private final OsSharedRealm sharedRealm;
private final NativeContext context;
private final Table table;
protected boolean loaded;
private boolean isSnapshot = false;
protected final ObserverPairList<CollectionObserverPair> observerPairs =
new ObserverPairList<CollectionObserverPair>();
// Public for static checking in JNI
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_MINIMUM = 1;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_MAXIMUM = 2;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_AVERAGE = 3;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_SUM = 4;
public enum Aggregate {
MINIMUM(AGGREGATE_FUNCTION_MINIMUM),
MAXIMUM(AGGREGATE_FUNCTION_MAXIMUM),
AVERAGE(AGGREGATE_FUNCTION_AVERAGE),
SUM(AGGREGATE_FUNCTION_SUM);
private final byte value;
Aggregate(byte value) {
this.value = value;
}
public byte getValue() {
return value;
}
}
@SuppressWarnings("WeakerAccess")
public static final byte MODE_EMPTY = 0;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_TABLE = 1;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_LIST = 2;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_QUERY = 3;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_TABLEVIEW = 4;
public enum Mode {
EMPTY, // Backed by nothing (for missing tables)
TABLE, // Backed directly by a Table
PRIMITIVE_LIST, // List of primitives
QUERY, // Backed by a query that has not yet been turned into a TableView
TABLEVIEW; // Backed by a TableView created from a Query
static Mode getByValue(byte value) {
switch (value) {
case MODE_EMPTY:
return EMPTY;
case MODE_TABLE:
return TABLE;
case MODE_QUERY:
return QUERY;
case MODE_LIST:
return PRIMITIVE_LIST;
case MODE_TABLEVIEW:
return TABLEVIEW;
default:
throw new IllegalArgumentException("Invalid value: " + value);
}
}
}
public static OsResults createForBacklinks(OsSharedRealm realm, UncheckedRow row, Table srcTable,
String srcFieldName) {
long backlinksPtr = nativeCreateResultsFromBacklinks(
realm.getNativePtr(),
row.getNativePtr(),
srcTable.getNativePtr(),
srcTable.getColumnKey(srcFieldName));
return new OsResults(realm, srcTable, backlinksPtr);
}
public static OsResults createFromQuery(OsSharedRealm sharedRealm, TableQuery query) {
query.validateQuery();
long ptr = nativeCreateResults(sharedRealm.getNativePtr(), query.getNativePtr());
return new OsResults(sharedRealm, query.getTable(), ptr);
}
public static OsResults createFromMap(OsSharedRealm sharedRealm, long resultsPtr) {
return new OsResults(sharedRealm, resultsPtr);
}
// Use this when we don't have the table, e.g. when calling RealmDictionary.values()
OsResults(OsSharedRealm sharedRealm, long nativePtr) {
this.sharedRealm = sharedRealm;
this.context = sharedRealm.context;
this.nativePtr = nativePtr;
this.context.addReference(this);
this.loaded = getMode() != Mode.QUERY;
this.table = new Table(sharedRealm, nativeGetTable(nativePtr));
}
OsResults(OsSharedRealm sharedRealm, Table table, long nativePtr) {
this.sharedRealm = sharedRealm;
this.context = sharedRealm.context;
this.table = table;
this.nativePtr = nativePtr;
this.context.addReference(this);
this.loaded = getMode() != Mode.QUERY;
}
public OsResults createSnapshot() {
if (isSnapshot) {
return this;
}
OsResults osResults = new OsResults(sharedRealm, table, nativeCreateSnapshot(nativePtr));
osResults.isSnapshot = true;
return osResults;
}
public OsResults freeze(OsSharedRealm frozenRealm) {
OsResults results = new OsResults(frozenRealm, table.freeze(frozenRealm), nativeFreeze(nativePtr, frozenRealm.getNativePtr()));
if (isLoaded()) {
results.load();
}
return results;
}
@Override
public long getNativePtr() {
return nativePtr;
}
@Override
public long getNativeFinalizerPtr() {
return nativeFinalizerPtr;
}
public Object getValue(int index) {
return nativeGetValue(nativePtr, index);
}
public UncheckedRow getUncheckedRow(int index) {
return table.getUncheckedRowByPointer(nativeGetRow(nativePtr, index));
}
public UncheckedRow firstUncheckedRow() {
long rowPtr = nativeFirstRow(nativePtr);
if (rowPtr != 0) {
return table.getUncheckedRowByPointer(rowPtr);
}
return null;
}
public UncheckedRow lastUncheckedRow() {
long rowPtr = nativeLastRow(nativePtr);
if (rowPtr != 0) {
return table.getUncheckedRowByPointer(rowPtr);
}
return null;
}
public Table getTable() {
return table;
}
public TableQuery where() {
long nativeQueryPtr = nativeWhere(nativePtr);
return new TableQuery(this.context, this.table, nativeQueryPtr);
}
public String toJSON(int maxDepth) {
return toJSON(nativePtr, maxDepth);
}
public Number aggregateNumber(Aggregate aggregateMethod, long columnKey) {
try {
return (Number) nativeAggregate(nativePtr, columnKey, aggregateMethod.getValue());
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
public Date aggregateDate(Aggregate aggregateMethod, long columnIndex) {
try {
return (Date) nativeAggregate(nativePtr, columnIndex, aggregateMethod.getValue());
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
public long size() {
return nativeSize(nativePtr);
}
public void clear() {
nativeClear(nativePtr);
}
public OsResults sort(@Nullable OsKeyPathMapping mapping, String fieldName, Sort sortOrder) {
String query = TableQuery.buildSortDescriptor(new String[] {fieldName}, new Sort[] {sortOrder});
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public OsResults sort(@Nullable OsKeyPathMapping mapping, String[] fieldNames, Sort[] sortOrders) {
//noinspection ConstantConditions
if (sortOrders == null || sortOrders.length == 0) {
throw new IllegalArgumentException("You must provide at least one sort order.");
}
if (fieldNames.length != sortOrders.length) {
throw new IllegalArgumentException("Number of fields and sort orders do not match.");
}
String query = TableQuery.buildSortDescriptor(fieldNames, sortOrders);
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public OsResults distinct(@Nullable OsKeyPathMapping mapping, String[] fieldNames) {
String query = TableQuery.buildDistinctDescriptor(fieldNames);
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public boolean contains(UncheckedRow row) {
return nativeContains(nativePtr, row.getNativePtr());
}
public int indexOf(UncheckedRow row) {
long index = nativeIndexOf(nativePtr, row.getNativePtr());
return (index > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) index;
}
public void delete(long index) {
nativeDelete(nativePtr, index);
}
public boolean deleteFirst() {
return nativeDeleteFirst(nativePtr);
}
public boolean deleteLast() {
return nativeDeleteLast(nativePtr);
}
public void setNull(String fieldName) {
nativeSetNull(nativePtr, fieldName);
}
public void setBoolean(String fieldName, boolean value) {
nativeSetBoolean(nativePtr, fieldName, value);
}
public void setInt(String fieldName, long value) {
nativeSetInt(nativePtr, fieldName, value);
}
public void setFloat(String fieldName, float value) {
nativeSetFloat(nativePtr, fieldName, value);
}
public void setDouble(String fieldName, double value) {
nativeSetDouble(nativePtr, fieldName, value);
}
public void setString(String fieldName, @Nullable String value) {
nativeSetString(nativePtr, fieldName, value);
}
public void setBlob(String fieldName, @Nullable byte[] value) {
nativeSetBinary(nativePtr, fieldName, value);
}
public void setDate(String fieldName, @Nullable Date timestamp) {
if (timestamp == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetTimestamp(nativePtr, fieldName, timestamp.getTime());
}
}
public void setDecimal128(String fieldName, @Nullable Decimal128 value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetDecimal128(nativePtr, fieldName, value.getLow(), value.getHigh());
}
}
public void setObjectId(String fieldName, @Nullable ObjectId value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetObjectId(nativePtr, fieldName, value.toString());
}
}
public void setUUID(String fieldName, @Nullable UUID value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetUUID(nativePtr, fieldName, value.toString());
}
}
public void setObject(String fieldName, @Nullable Row row) {
if (row == null) {
setNull(fieldName);
} else {
long rowPtr;
if (row instanceof UncheckedRow) {
// Normal Realms
rowPtr = ((UncheckedRow) row).getNativePtr();
} else if (row instanceof CheckedRow) {
// Dynamic Realms
rowPtr = ((CheckedRow) row).getNativePtr();
} else {
// Should never happen, but just in case.
throw new UnsupportedOperationException("Unsupported Row type: " + row.getClass().getCanonicalName());
}
nativeSetObject(nativePtr, fieldName, rowPtr);
}
}
// Interface wrapping adding the specific list type
private interface AddListTypeDelegate<T> {
void addList(OsObjectBuilder builder, RealmList<T> list);
}
// Helper method for adding specific types of lists.
private <T> void addTypeSpecificList(String fieldName, RealmList<T> list, AddListTypeDelegate<T> delegate) {
//noinspection unchecked
OsObjectBuilder builder = new OsObjectBuilder(getTable(), Collections.EMPTY_SET);
delegate.addList(builder, list);
try {
nativeSetList(nativePtr, fieldName, builder.getNativePtr());
} finally {
builder.close();
}
}
public void setStringList(String fieldName, RealmList<String> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<String>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<String> list) {
builder.addStringList(0, list);
}
});
}
public void setByteList(String fieldName, RealmList<Byte> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Byte>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Byte> list) {
builder.addByteList(0, list);
}
});
}
public void setShortList(String fieldName, RealmList<Short> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Short>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Short> list) {
builder.addShortList(0, list);
}
});
}
public void setIntegerList(String fieldName, RealmList<Integer> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Integer>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Integer> list) {
builder.addIntegerList(0, list);
}
});
}
public void setLongList(String fieldName, RealmList<Long> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Long>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Long> list) {
builder.addLongList(0, list);
}
});
}
public void setBooleanList(String fieldName, RealmList<Boolean> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Boolean>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Boolean> list) {
builder.addBooleanList(0, list);
}
});
}
public void setByteArrayList(String fieldName, RealmList<byte[]> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<byte[]>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<byte[]> list) {
builder.addByteArrayList(0, list);
}
});
}
public void setDateList(String fieldName, RealmList<Date> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Date>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Date> list) {
builder.addDateList(0, list);
}
});
}
public void setFloatList(String fieldName, RealmList<Float> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Float>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Float> list) {
builder.addFloatList(0, list);
}
});
}
public void setDoubleList(String fieldName, RealmList<Double> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Double>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Double> list) {
builder.addDoubleList(0, list);
}
});
}
public void setModelList(String fieldName, RealmList<RealmModel> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<RealmModel>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<RealmModel> list) {
builder.addObjectList(0, list);
}
});
}
public void setDecimal128List(String fieldName, RealmList<Decimal128> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Decimal128>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Decimal128> list) {
builder.addDecimal128List(0, list);
}
});
}
public void setObjectIdList(String fieldName, RealmList<ObjectId> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<ObjectId>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<ObjectId> list) {
builder.addObjectIdList(0, list);
}
});
}
public void setUUIDList(String fieldName, RealmList<UUID> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<UUID>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<UUID> list) {
builder.addUUIDList(0, list);
}
});
}
public <T> void addListener(T observer, OrderedRealmCollectionChangeListener<T> listener) {
if (observerPairs.isEmpty()) {
nativeStartListening(nativePtr);
}
CollectionObserverPair<T> collectionObserverPair = new CollectionObserverPair<T>(observer, listener);
observerPairs.add(collectionObserverPair);
}
public <T> void addListener(T observer, RealmChangeListener<T> listener) {
addListener(observer, new RealmChangeListenerWrapper<T>(listener));
}
public <T> void removeListener(T observer, OrderedRealmCollectionChangeListener<T> listener) {
observerPairs.remove(observer, listener);
if (observerPairs.isEmpty()) {
nativeStopListening(nativePtr);
}
}
public <T> void removeListener(T observer, RealmChangeListener<T> listener) {
removeListener(observer, new RealmChangeListenerWrapper<T>(listener));
}
public void removeAllListeners() {
observerPairs.clear();
nativeStopListening(nativePtr);
}
public boolean isValid() {
return nativeIsValid(nativePtr);
}
// Called by JNI
@Override
public void notifyChangeListeners(long nativeChangeSetPtr) {
// Object Store compute the change set between the SharedGroup versions when the query created and the latest.
// So it is possible it deliver a non-empty change set for the first async query returns.
OsCollectionChangeSet changeset = (nativeChangeSetPtr == 0)
? new EmptyLoadChangeSet()
: new OsCollectionChangeSet(nativeChangeSetPtr, !isLoaded());
// Happens e.g. if a synchronous query is created, a change listener is added and then
// a transaction is started on the same thread. This will trigger all notifications
// and deliver an empty changeset.
if (changeset.isEmpty() && isLoaded()) {
return;
}
loaded = true;
observerPairs.foreach(new Callback(changeset));
}
public Mode getMode() {
return Mode.getByValue(nativeGetMode(nativePtr));
}
// The Results with mode QUERY will be evaluated asynchronously in Object Store. But we do have to support "sync"
// query by Java like RealmQuery.findAll().
// The flag is used for following cases:
// 1. When Results is created, loaded will be set to false if the mode is QUERY. For other modes, loaded will be set
// to true.
// 2. For sync query (RealmQuery.findAll()), load() should be called after the Results creation. Then query will be
// evaluated immediately and then loaded will be set to true (And the mode will be changed to TABLEVIEW in OS).
// 3. For async query, when load() gets called with loaded not set, the listener should be triggered with empty
// change set since it is considered as query first returned.
// 4. If the listener triggered with empty change set after load() called for async queries, it is treated as the
// same case as 2).
public boolean isLoaded() {
return loaded;
}
public void load() {
if (loaded) {
return;
}
try {
nativeEvaluateQueryIfNeeded(nativePtr, false);
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Cannot sort on a collection property")) {
throw new IllegalStateException("Illegal Argument: " + e.getMessage());
}
}
notifyChangeListeners(0);
}
private static long stringDescriptor(long nativePtr, String descriptor, long mapping){
try {
return nativeStringDescriptor(nativePtr, descriptor, mapping);
} catch (IllegalStateException e) {
if (e.getMessage().contains("Realm accessed from incorrect thread.")) {
throw e;
} else {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
}
private static native long nativeGetFinalizerPtr();
protected static native long nativeCreateResults(long sharedRealmNativePtr, long queryNativePtr);
private static native long nativeCreateSnapshot(long nativePtr);
private static native long nativeFreeze(long nativePtr, long frozenRealmNativePtr);
private static native long nativeGetRow(long nativePtr, int index);
private static native long nativeFirstRow(long nativePtr);
private static native long nativeLastRow(long nativePtr);
private static native boolean nativeContains(long nativePtr, long nativeRowPtr);
private static native void nativeClear(long nativePtr);
private static native long nativeSize(long nativePtr);
private static native Object nativeAggregate(long nativePtr, long columnIndex, byte aggregateFunc);
private static native long nativeStringDescriptor(long nativePtr, String descriptor, long mapping);
private static native boolean nativeDeleteFirst(long nativePtr);
private static native boolean nativeDeleteLast(long nativePtr);
private static native void nativeDelete(long nativePtr, long index);
private static native void nativeSetNull(long nativePtr, String fieldName);
private static native void nativeSetBoolean(long nativePtr, String fieldName, boolean value);
private static native void nativeSetInt(long nativePtr, String fieldName, long value);
private static native void nativeSetFloat(long nativePtr, String fieldName, float value);
private static native void nativeSetDouble(long nativePtr, String fieldName, double value);
private static native void nativeSetString(long nativePtr, String fieldName, @Nullable String value);
private static native void nativeSetBinary(long nativePtr, String fieldName, @Nullable byte[] value);
private static native void nativeSetTimestamp(long nativePtr, String fieldName, long value);
private static native void nativeSetDecimal128(long nativePtr, String fieldName, long low, long high);
private static native void nativeSetObjectId(long nativePtr, String fieldName, String data);
private static native void nativeSetUUID(long nativePtr, String fieldName, String data);
private static native void nativeSetObject(long nativePtr, String fieldName, long rowNativePtr);
private static native void nativeSetList(long nativePtr, String fieldName, long builderNativePtr);
// Non-static, we need this OsResults object in JNI.
private native void nativeStartListening(long nativePtr);
private native void nativeStopListening(long nativePtr);
private static native long nativeGetTable(long nativePtr);
private static native long nativeWhere(long nativePtr);
private static native String toJSON(long nativePtr, int maxDepth);
private static native long nativeIndexOf(long nativePtr, long rowNativePtr);
private static native boolean nativeIsValid(long nativePtr);
private static native byte nativeGetMode(long nativePtr);
private static native long nativeCreateResultsFromBacklinks(long sharedRealmNativePtr, long rowNativePtr, long srcTableNativePtr, long srColIndex);
private static native void nativeEvaluateQueryIfNeeded(long nativePtr, boolean wantsNotifications);
private static native Object nativeGetValue(long nativePtr, int index);
}
| realm/realm-java | realm/realm-library/src/main/java/io/realm/internal/OsResults.java | 7,970 | // event loop need to be detached. | line_comment | nl | /*
* Copyright 2017 Realm 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 io.realm.internal;
import org.bson.types.Decimal128;
import org.bson.types.ObjectId;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.UUID;
import javax.annotation.Nullable;
import io.realm.OrderedRealmCollectionChangeListener;
import io.realm.RealmChangeListener;
import io.realm.RealmList;
import io.realm.RealmModel;
import io.realm.Sort;
import io.realm.internal.objectstore.OsKeyPathMapping;
import io.realm.internal.objectstore.OsObjectBuilder;
/**
* Java wrapper of Object Store Results class.
* It is the backend of binding's query results and back links.
*/
public class OsResults implements NativeObject, ObservableCollection {
private static final String CLOSED_REALM_MESSAGE =
"This Realm instance has already been closed, making it unusable.";
// Custom OsResults iterator. It ensures that we only iterate on a Realm OsResults that hasn't changed.
public abstract static class Iterator<T> implements java.util.Iterator<T> {
protected OsResults iteratorOsResults;
protected int pos = -1;
public Iterator(OsResults osResults) {
if (osResults.sharedRealm.isClosed()) {
throw new IllegalStateException(CLOSED_REALM_MESSAGE);
}
this.iteratorOsResults = osResults;
if (osResults.isSnapshot) {
// No need to detach a snapshot.
return;
}
if (osResults.sharedRealm.isInTransaction()) {
detach();
} else {
iteratorOsResults.sharedRealm.addIterator(this);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasNext() {
checkValid();
return pos + 1 < iteratorOsResults.size();
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public T next() {
checkValid();
pos++;
if (pos >= iteratorOsResults.size()) {
throw new NoSuchElementException("Cannot access index " + pos + " when size is " + iteratorOsResults.size() +
". Remember to check hasNext() before using next().");
}
return get(pos);
}
/**
* Not supported by Realm collection iterators.
*/
@Override
@Deprecated
public void remove() {
throw new UnsupportedOperationException("remove() is not supported by RealmResults iterators.");
}
void detach() {
iteratorOsResults = iteratorOsResults.createSnapshot();
}
// The iterator becomes invalid after receiving a remote change notification. In Java, the destruction of
// iterator totally depends on GC. If we just detach those iterators when remote change notification received
// like what realm-cocoa does, we will have a massive overhead since all the iterators created in the previous
// event loop<SUF>
void invalidate() {
iteratorOsResults = null;
}
void checkValid() {
if (iteratorOsResults == null) {
throw new ConcurrentModificationException(
"No outside changes to a Realm is allowed while iterating a living Realm collection.");
}
}
@Nullable
T get(int pos) {
return getInternal(pos, iteratorOsResults);
}
// Returns the RealmModel by given row in this list. This has to be implemented in the upper layer since
// we don't have information about the object types in the internal package.
protected abstract T convertRowToObject(UncheckedRow row);
protected abstract T getInternal(int pos, OsResults iteratorOsResults);
}
// Custom Realm collection list iterator.
public abstract static class ListIterator<T> extends Iterator<T> implements java.util.ListIterator<T> {
public ListIterator(OsResults osResults, int start) {
super(osResults);
if (start >= 0 && start <= iteratorOsResults.size()) {
pos = start - 1;
} else {
throw new IndexOutOfBoundsException("Starting location must be a valid index: [0, "
+ (iteratorOsResults.size() - 1) + "]. Yours was " + start);
}
}
/**
* Unsupported by Realm collection iterators.
*/
@Override
@Deprecated
public void add(@Nullable T object) {
throw new UnsupportedOperationException("Adding an element is not supported. Use Realm.createObject() instead.");
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasPrevious() {
checkValid();
return pos >= 0;
}
/**
* {@inheritDoc}
*/
@Override
public int nextIndex() {
checkValid();
return pos + 1;
}
/**
* {@inheritDoc}
*/
@Override
@Nullable
public T previous() {
checkValid();
try {
T obj = get(pos);
pos--;
return obj;
} catch (IndexOutOfBoundsException e) {
throw new NoSuchElementException("Cannot access index less than zero. This was " + pos +
". Remember to check hasPrevious() before using previous().");
}
}
/**
* {@inheritDoc}
*/
@Override
public int previousIndex() {
checkValid();
return pos;
}
/**
* Unsupported by RealmResults iterators.
*/
@Override
@Deprecated
public void set(@Nullable T object) {
throw new UnsupportedOperationException("Replacing an element is not supported.");
}
}
private final long nativePtr;
private static final long nativeFinalizerPtr = nativeGetFinalizerPtr();
private final OsSharedRealm sharedRealm;
private final NativeContext context;
private final Table table;
protected boolean loaded;
private boolean isSnapshot = false;
protected final ObserverPairList<CollectionObserverPair> observerPairs =
new ObserverPairList<CollectionObserverPair>();
// Public for static checking in JNI
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_MINIMUM = 1;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_MAXIMUM = 2;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_AVERAGE = 3;
@SuppressWarnings("WeakerAccess")
public static final byte AGGREGATE_FUNCTION_SUM = 4;
public enum Aggregate {
MINIMUM(AGGREGATE_FUNCTION_MINIMUM),
MAXIMUM(AGGREGATE_FUNCTION_MAXIMUM),
AVERAGE(AGGREGATE_FUNCTION_AVERAGE),
SUM(AGGREGATE_FUNCTION_SUM);
private final byte value;
Aggregate(byte value) {
this.value = value;
}
public byte getValue() {
return value;
}
}
@SuppressWarnings("WeakerAccess")
public static final byte MODE_EMPTY = 0;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_TABLE = 1;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_LIST = 2;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_QUERY = 3;
@SuppressWarnings("WeakerAccess")
public static final byte MODE_TABLEVIEW = 4;
public enum Mode {
EMPTY, // Backed by nothing (for missing tables)
TABLE, // Backed directly by a Table
PRIMITIVE_LIST, // List of primitives
QUERY, // Backed by a query that has not yet been turned into a TableView
TABLEVIEW; // Backed by a TableView created from a Query
static Mode getByValue(byte value) {
switch (value) {
case MODE_EMPTY:
return EMPTY;
case MODE_TABLE:
return TABLE;
case MODE_QUERY:
return QUERY;
case MODE_LIST:
return PRIMITIVE_LIST;
case MODE_TABLEVIEW:
return TABLEVIEW;
default:
throw new IllegalArgumentException("Invalid value: " + value);
}
}
}
public static OsResults createForBacklinks(OsSharedRealm realm, UncheckedRow row, Table srcTable,
String srcFieldName) {
long backlinksPtr = nativeCreateResultsFromBacklinks(
realm.getNativePtr(),
row.getNativePtr(),
srcTable.getNativePtr(),
srcTable.getColumnKey(srcFieldName));
return new OsResults(realm, srcTable, backlinksPtr);
}
public static OsResults createFromQuery(OsSharedRealm sharedRealm, TableQuery query) {
query.validateQuery();
long ptr = nativeCreateResults(sharedRealm.getNativePtr(), query.getNativePtr());
return new OsResults(sharedRealm, query.getTable(), ptr);
}
public static OsResults createFromMap(OsSharedRealm sharedRealm, long resultsPtr) {
return new OsResults(sharedRealm, resultsPtr);
}
// Use this when we don't have the table, e.g. when calling RealmDictionary.values()
OsResults(OsSharedRealm sharedRealm, long nativePtr) {
this.sharedRealm = sharedRealm;
this.context = sharedRealm.context;
this.nativePtr = nativePtr;
this.context.addReference(this);
this.loaded = getMode() != Mode.QUERY;
this.table = new Table(sharedRealm, nativeGetTable(nativePtr));
}
OsResults(OsSharedRealm sharedRealm, Table table, long nativePtr) {
this.sharedRealm = sharedRealm;
this.context = sharedRealm.context;
this.table = table;
this.nativePtr = nativePtr;
this.context.addReference(this);
this.loaded = getMode() != Mode.QUERY;
}
public OsResults createSnapshot() {
if (isSnapshot) {
return this;
}
OsResults osResults = new OsResults(sharedRealm, table, nativeCreateSnapshot(nativePtr));
osResults.isSnapshot = true;
return osResults;
}
public OsResults freeze(OsSharedRealm frozenRealm) {
OsResults results = new OsResults(frozenRealm, table.freeze(frozenRealm), nativeFreeze(nativePtr, frozenRealm.getNativePtr()));
if (isLoaded()) {
results.load();
}
return results;
}
@Override
public long getNativePtr() {
return nativePtr;
}
@Override
public long getNativeFinalizerPtr() {
return nativeFinalizerPtr;
}
public Object getValue(int index) {
return nativeGetValue(nativePtr, index);
}
public UncheckedRow getUncheckedRow(int index) {
return table.getUncheckedRowByPointer(nativeGetRow(nativePtr, index));
}
public UncheckedRow firstUncheckedRow() {
long rowPtr = nativeFirstRow(nativePtr);
if (rowPtr != 0) {
return table.getUncheckedRowByPointer(rowPtr);
}
return null;
}
public UncheckedRow lastUncheckedRow() {
long rowPtr = nativeLastRow(nativePtr);
if (rowPtr != 0) {
return table.getUncheckedRowByPointer(rowPtr);
}
return null;
}
public Table getTable() {
return table;
}
public TableQuery where() {
long nativeQueryPtr = nativeWhere(nativePtr);
return new TableQuery(this.context, this.table, nativeQueryPtr);
}
public String toJSON(int maxDepth) {
return toJSON(nativePtr, maxDepth);
}
public Number aggregateNumber(Aggregate aggregateMethod, long columnKey) {
try {
return (Number) nativeAggregate(nativePtr, columnKey, aggregateMethod.getValue());
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
public Date aggregateDate(Aggregate aggregateMethod, long columnIndex) {
try {
return (Date) nativeAggregate(nativePtr, columnIndex, aggregateMethod.getValue());
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
public long size() {
return nativeSize(nativePtr);
}
public void clear() {
nativeClear(nativePtr);
}
public OsResults sort(@Nullable OsKeyPathMapping mapping, String fieldName, Sort sortOrder) {
String query = TableQuery.buildSortDescriptor(new String[] {fieldName}, new Sort[] {sortOrder});
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public OsResults sort(@Nullable OsKeyPathMapping mapping, String[] fieldNames, Sort[] sortOrders) {
//noinspection ConstantConditions
if (sortOrders == null || sortOrders.length == 0) {
throw new IllegalArgumentException("You must provide at least one sort order.");
}
if (fieldNames.length != sortOrders.length) {
throw new IllegalArgumentException("Number of fields and sort orders do not match.");
}
String query = TableQuery.buildSortDescriptor(fieldNames, sortOrders);
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public OsResults distinct(@Nullable OsKeyPathMapping mapping, String[] fieldNames) {
String query = TableQuery.buildDistinctDescriptor(fieldNames);
return new OsResults(sharedRealm, table, stringDescriptor(nativePtr, query, (mapping != null) ? mapping.getNativePtr() : 0));
}
public boolean contains(UncheckedRow row) {
return nativeContains(nativePtr, row.getNativePtr());
}
public int indexOf(UncheckedRow row) {
long index = nativeIndexOf(nativePtr, row.getNativePtr());
return (index > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) index;
}
public void delete(long index) {
nativeDelete(nativePtr, index);
}
public boolean deleteFirst() {
return nativeDeleteFirst(nativePtr);
}
public boolean deleteLast() {
return nativeDeleteLast(nativePtr);
}
public void setNull(String fieldName) {
nativeSetNull(nativePtr, fieldName);
}
public void setBoolean(String fieldName, boolean value) {
nativeSetBoolean(nativePtr, fieldName, value);
}
public void setInt(String fieldName, long value) {
nativeSetInt(nativePtr, fieldName, value);
}
public void setFloat(String fieldName, float value) {
nativeSetFloat(nativePtr, fieldName, value);
}
public void setDouble(String fieldName, double value) {
nativeSetDouble(nativePtr, fieldName, value);
}
public void setString(String fieldName, @Nullable String value) {
nativeSetString(nativePtr, fieldName, value);
}
public void setBlob(String fieldName, @Nullable byte[] value) {
nativeSetBinary(nativePtr, fieldName, value);
}
public void setDate(String fieldName, @Nullable Date timestamp) {
if (timestamp == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetTimestamp(nativePtr, fieldName, timestamp.getTime());
}
}
public void setDecimal128(String fieldName, @Nullable Decimal128 value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetDecimal128(nativePtr, fieldName, value.getLow(), value.getHigh());
}
}
public void setObjectId(String fieldName, @Nullable ObjectId value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetObjectId(nativePtr, fieldName, value.toString());
}
}
public void setUUID(String fieldName, @Nullable UUID value) {
if (value == null) {
nativeSetNull(nativePtr, fieldName);
} else {
nativeSetUUID(nativePtr, fieldName, value.toString());
}
}
public void setObject(String fieldName, @Nullable Row row) {
if (row == null) {
setNull(fieldName);
} else {
long rowPtr;
if (row instanceof UncheckedRow) {
// Normal Realms
rowPtr = ((UncheckedRow) row).getNativePtr();
} else if (row instanceof CheckedRow) {
// Dynamic Realms
rowPtr = ((CheckedRow) row).getNativePtr();
} else {
// Should never happen, but just in case.
throw new UnsupportedOperationException("Unsupported Row type: " + row.getClass().getCanonicalName());
}
nativeSetObject(nativePtr, fieldName, rowPtr);
}
}
// Interface wrapping adding the specific list type
private interface AddListTypeDelegate<T> {
void addList(OsObjectBuilder builder, RealmList<T> list);
}
// Helper method for adding specific types of lists.
private <T> void addTypeSpecificList(String fieldName, RealmList<T> list, AddListTypeDelegate<T> delegate) {
//noinspection unchecked
OsObjectBuilder builder = new OsObjectBuilder(getTable(), Collections.EMPTY_SET);
delegate.addList(builder, list);
try {
nativeSetList(nativePtr, fieldName, builder.getNativePtr());
} finally {
builder.close();
}
}
public void setStringList(String fieldName, RealmList<String> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<String>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<String> list) {
builder.addStringList(0, list);
}
});
}
public void setByteList(String fieldName, RealmList<Byte> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Byte>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Byte> list) {
builder.addByteList(0, list);
}
});
}
public void setShortList(String fieldName, RealmList<Short> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Short>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Short> list) {
builder.addShortList(0, list);
}
});
}
public void setIntegerList(String fieldName, RealmList<Integer> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Integer>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Integer> list) {
builder.addIntegerList(0, list);
}
});
}
public void setLongList(String fieldName, RealmList<Long> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Long>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Long> list) {
builder.addLongList(0, list);
}
});
}
public void setBooleanList(String fieldName, RealmList<Boolean> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Boolean>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Boolean> list) {
builder.addBooleanList(0, list);
}
});
}
public void setByteArrayList(String fieldName, RealmList<byte[]> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<byte[]>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<byte[]> list) {
builder.addByteArrayList(0, list);
}
});
}
public void setDateList(String fieldName, RealmList<Date> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Date>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Date> list) {
builder.addDateList(0, list);
}
});
}
public void setFloatList(String fieldName, RealmList<Float> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Float>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Float> list) {
builder.addFloatList(0, list);
}
});
}
public void setDoubleList(String fieldName, RealmList<Double> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Double>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Double> list) {
builder.addDoubleList(0, list);
}
});
}
public void setModelList(String fieldName, RealmList<RealmModel> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<RealmModel>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<RealmModel> list) {
builder.addObjectList(0, list);
}
});
}
public void setDecimal128List(String fieldName, RealmList<Decimal128> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<Decimal128>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<Decimal128> list) {
builder.addDecimal128List(0, list);
}
});
}
public void setObjectIdList(String fieldName, RealmList<ObjectId> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<ObjectId>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<ObjectId> list) {
builder.addObjectIdList(0, list);
}
});
}
public void setUUIDList(String fieldName, RealmList<UUID> list) {
addTypeSpecificList(fieldName, list, new AddListTypeDelegate<UUID>() {
@Override
public void addList(OsObjectBuilder builder, RealmList<UUID> list) {
builder.addUUIDList(0, list);
}
});
}
public <T> void addListener(T observer, OrderedRealmCollectionChangeListener<T> listener) {
if (observerPairs.isEmpty()) {
nativeStartListening(nativePtr);
}
CollectionObserverPair<T> collectionObserverPair = new CollectionObserverPair<T>(observer, listener);
observerPairs.add(collectionObserverPair);
}
public <T> void addListener(T observer, RealmChangeListener<T> listener) {
addListener(observer, new RealmChangeListenerWrapper<T>(listener));
}
public <T> void removeListener(T observer, OrderedRealmCollectionChangeListener<T> listener) {
observerPairs.remove(observer, listener);
if (observerPairs.isEmpty()) {
nativeStopListening(nativePtr);
}
}
public <T> void removeListener(T observer, RealmChangeListener<T> listener) {
removeListener(observer, new RealmChangeListenerWrapper<T>(listener));
}
public void removeAllListeners() {
observerPairs.clear();
nativeStopListening(nativePtr);
}
public boolean isValid() {
return nativeIsValid(nativePtr);
}
// Called by JNI
@Override
public void notifyChangeListeners(long nativeChangeSetPtr) {
// Object Store compute the change set between the SharedGroup versions when the query created and the latest.
// So it is possible it deliver a non-empty change set for the first async query returns.
OsCollectionChangeSet changeset = (nativeChangeSetPtr == 0)
? new EmptyLoadChangeSet()
: new OsCollectionChangeSet(nativeChangeSetPtr, !isLoaded());
// Happens e.g. if a synchronous query is created, a change listener is added and then
// a transaction is started on the same thread. This will trigger all notifications
// and deliver an empty changeset.
if (changeset.isEmpty() && isLoaded()) {
return;
}
loaded = true;
observerPairs.foreach(new Callback(changeset));
}
public Mode getMode() {
return Mode.getByValue(nativeGetMode(nativePtr));
}
// The Results with mode QUERY will be evaluated asynchronously in Object Store. But we do have to support "sync"
// query by Java like RealmQuery.findAll().
// The flag is used for following cases:
// 1. When Results is created, loaded will be set to false if the mode is QUERY. For other modes, loaded will be set
// to true.
// 2. For sync query (RealmQuery.findAll()), load() should be called after the Results creation. Then query will be
// evaluated immediately and then loaded will be set to true (And the mode will be changed to TABLEVIEW in OS).
// 3. For async query, when load() gets called with loaded not set, the listener should be triggered with empty
// change set since it is considered as query first returned.
// 4. If the listener triggered with empty change set after load() called for async queries, it is treated as the
// same case as 2).
public boolean isLoaded() {
return loaded;
}
public void load() {
if (loaded) {
return;
}
try {
nativeEvaluateQueryIfNeeded(nativePtr, false);
} catch (IllegalStateException e) {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
} catch (IllegalArgumentException e) {
if (e.getMessage().contains("Cannot sort on a collection property")) {
throw new IllegalStateException("Illegal Argument: " + e.getMessage());
}
}
notifyChangeListeners(0);
}
private static long stringDescriptor(long nativePtr, String descriptor, long mapping){
try {
return nativeStringDescriptor(nativePtr, descriptor, mapping);
} catch (IllegalStateException e) {
if (e.getMessage().contains("Realm accessed from incorrect thread.")) {
throw e;
} else {
throw new IllegalArgumentException("Illegal Argument: " + e.getMessage());
}
}
}
private static native long nativeGetFinalizerPtr();
protected static native long nativeCreateResults(long sharedRealmNativePtr, long queryNativePtr);
private static native long nativeCreateSnapshot(long nativePtr);
private static native long nativeFreeze(long nativePtr, long frozenRealmNativePtr);
private static native long nativeGetRow(long nativePtr, int index);
private static native long nativeFirstRow(long nativePtr);
private static native long nativeLastRow(long nativePtr);
private static native boolean nativeContains(long nativePtr, long nativeRowPtr);
private static native void nativeClear(long nativePtr);
private static native long nativeSize(long nativePtr);
private static native Object nativeAggregate(long nativePtr, long columnIndex, byte aggregateFunc);
private static native long nativeStringDescriptor(long nativePtr, String descriptor, long mapping);
private static native boolean nativeDeleteFirst(long nativePtr);
private static native boolean nativeDeleteLast(long nativePtr);
private static native void nativeDelete(long nativePtr, long index);
private static native void nativeSetNull(long nativePtr, String fieldName);
private static native void nativeSetBoolean(long nativePtr, String fieldName, boolean value);
private static native void nativeSetInt(long nativePtr, String fieldName, long value);
private static native void nativeSetFloat(long nativePtr, String fieldName, float value);
private static native void nativeSetDouble(long nativePtr, String fieldName, double value);
private static native void nativeSetString(long nativePtr, String fieldName, @Nullable String value);
private static native void nativeSetBinary(long nativePtr, String fieldName, @Nullable byte[] value);
private static native void nativeSetTimestamp(long nativePtr, String fieldName, long value);
private static native void nativeSetDecimal128(long nativePtr, String fieldName, long low, long high);
private static native void nativeSetObjectId(long nativePtr, String fieldName, String data);
private static native void nativeSetUUID(long nativePtr, String fieldName, String data);
private static native void nativeSetObject(long nativePtr, String fieldName, long rowNativePtr);
private static native void nativeSetList(long nativePtr, String fieldName, long builderNativePtr);
// Non-static, we need this OsResults object in JNI.
private native void nativeStartListening(long nativePtr);
private native void nativeStopListening(long nativePtr);
private static native long nativeGetTable(long nativePtr);
private static native long nativeWhere(long nativePtr);
private static native String toJSON(long nativePtr, int maxDepth);
private static native long nativeIndexOf(long nativePtr, long rowNativePtr);
private static native boolean nativeIsValid(long nativePtr);
private static native byte nativeGetMode(long nativePtr);
private static native long nativeCreateResultsFromBacklinks(long sharedRealmNativePtr, long rowNativePtr, long srcTableNativePtr, long srColIndex);
private static native void nativeEvaluateQueryIfNeeded(long nativePtr, boolean wantsNotifications);
private static native Object nativeGetValue(long nativePtr, int index);
}
|
96718_48 | package module;
import com.messages.ChatMessage;
import game.objects.GameObject;
//import java.awt.Point;
//import java.util.Arrays;
//
//import com.messages.GameContentMessage;
//import com.messages.MessageType;
//
//import match.KiHandler;
//import module.MatchModuleServer;
//import game.actions.AttackAction;
//import game.actions.MoveAction;
//import game.attributes.Attribute;
//import game.content.effects.active.Following;
//import game.content.effects.direct.Damage;
//import game.content.heros.Hero;
//import game.content.heros.Sprintomanius;
//import game.content.heros.geronimo.GeronimoVonNazareth;
//import game.content.ki.Default;
//import game.content.ki.behavior.KiGroup;
//import game.content.ki.behavior.KiTypes;
//import game.content.statics.Gras;
//import game.content.statics.Path;
//import game.content.statics.Tree;
//import game.effects.ActiveEffect;
//import game.effects.DirectEffect;
//import game.effects.Effect;
//import game.effects.PermanentEffect;
//import game.objects.Fraction;
//import game.objects.Map;
//import game.objects.Match;
//import game.objects.NonStatic;
//import game.objects.WorldObject;
/**
* TestMatchModul.
* @author Tristan
*
* CHECKSTYLE:OFF
*
*/
public class MatchModuleServerTest extends MatchModuleServer {
public void run() {
// this.initializeTestWorld();
// this.kampf();
// this.geroParty();
// this.wettrennen();
// this.schoeneNeueWelt();
// this.konfrontation();
// this.verfolgungsjagt();
// this.lonleyWulf();
// this.zweiJungsInnerMitte();
//new KiGroup(KiTypes.DEFAULT, 6, Fraction.TeamA, match.getMap());
super.run();
}
public void turn() {
// System.out.println("Runde " + (this.turn+1));
// System.out.println("Neue Runde");
super.turn();
// System.out.println(this.turn);
// if(turn == 20) {
// System.out.println(GameObject.getAllGameObjectsSize());
// GameObject.sendAllGameObjects();
// }
if (turn%100 == 0) {
// int[][] mapArray1 = this.getMatch().getMap().toArray();
// GameObject.testSaveNLoad();
// this.match = Match.getMatch();
// int[][] mapArray2 = this.getMatch().getMap().toArray();
//
// if(Arrays.equals(mapArray1, mapArray2)) {
// System.out.println("JAAAAAAA");
// } else {
//
// for (int x = 0; x < mapArray2.length; x++) {
// for (int y = 0; y < mapArray2.length; y++) {
// if (mapArray1[x][y] != mapArray2[x][y]) {
// System.out.println("mapArray1: " + mapArray1[x][y]);
// System.out.println("mapArray2: " + mapArray2[x][y]);
// }
// }
// }
//
// for (int x = mapArray2.length/4; x < mapArray2.length/2; x++) {
// for (int y = mapArray2.length/4; y < mapArray2.length/2; y++) {
// System.out.print(mapArray2[x][y]);
// }
// System.out.println();
// }
//
// System.out.println();
// System.out.println("================================================================================================================================================================================================================================================");
// System.out.println();
//
// for (int x = mapArray2.length/4; x < mapArray2.length/2; x++) {
// for (int y = mapArray2.length/4; y < mapArray2.length/2; y++) {
// System.out.print(mapArray2[x][y]);
// }
// System.out.println();
// }
//
// System.exit(0);
// }
System.out.print("Runde " + this.turn + ", ");
System.out.println(GameObject.getAllGameObjectsSize() + " GameObjects, ");
ModuleHandler.COM.pushMessage((new ChatMessage("Runde " + this.turn)));
// System.out.print( ((double) GameObject.getNextId())*100 / ((double) Integer.MAX_VALUE) );
// System.out.println("% ausgelastet." );
// aufZuNeuenUfern();
}
// Hero gero = GameObject.getById(4);
// System.out.print("Geros Effekte: "); gero.printEffects();
// System.out.println("Geros Position: " + gero.getCoord().toString());
}
// public void geroParty() {
// for(int i=0; i<150; i++) {
//
// Hero gero = new Sprintomanius();
// if (i % 2 == 0) {
// gero.setFraction(Fraction.TeamA);
// } else {
// gero.setFraction(Fraction.TeamB);
// }
//
// gero.placeOnMap(match.getMap(), findEmptyJunglePoint() );
//
// new MoveAction(gero, findEmptyJunglePoint()).plan();
// }
// }
//
// public Point findEmptyJunglePoint() {
// return findEmptyPoint("static/floor/gras");
// }
//
// private Point findEmptyPoint(final String imageURL) {
// Point coord;
// do {
// coord = new Point((int) (Math.random() * Map.DIMENSION.x), (int) (Math.random() * Map.DIMENSION.y));
// } while(this.getMatch().getMap().ifWalkable(coord) || !this.getMatch().getMap().getList(coord).getFirst().getImageURL().equals(imageURL) );
// return coord;
// }
//
// public void schoeneNeueWelt() {
// Hero gero1 = new Sprintomanius();
// gero1.placeOnMap(match.getMap(), new Point(0, 199) );
// new MoveAction(gero1, new Point(162, 42) ).plan();
// }
//
//
// private void konfrontation() {
// for(int x=0; x<20; x=x+2) {
// for(int y=0; y<20; y=y+2) {
//
// Point coord1 = new Point(5+x, 195-y );
// Point coord3 = new Point(25+x, 175-y );
//
// Point coord2 = new Point(195-x, 5+y);
// Point coord4 = new Point(175-x, 25+y);
//
// Hero gero1 = new Sprintomanius();
// Hero gero2 = new Sprintomanius();
//
// gero1.setFraction(Fraction.TeamA);
// gero2.setFraction(Fraction.TeamB);
//
// gero1.placeOnMap(match.getMap(), coord1 );
// gero2.placeOnMap(match.getMap(), coord2 );
//
// new MoveAction(gero1, coord4).plan();
// new MoveAction(gero2, coord3).plan();
// }
// }
// }
//
// private void verfolgungsjagt() {
//
// Hero gero1 = new Sprintomanius();
// Hero gero2 = new Sprintomanius();
//
//
// gero1.placeOnMap(match.getMap(), new Point(90, 110) );
// gero2.placeOnMap(match.getMap(), new Point(110, 90) );
//
//
// new MoveAction(gero1, new Point(199, 0) ).plan();
// new Following(gero2, gero1, 0).ready();
//// new ActionOnNonStatic(gero2, Follow.getInstance(), gero1).plan();
//
//
//// System.out.println("Held 1 : "+gero1.getId());
//// System.out.println("Held 2 : "+gero2.getId());
// }
//
//
// private void kampf() {
//
// Hero gero1 = new GeronimoVonNazareth();
// Hero gero2 = new GeronimoVonNazareth();
//
//
// gero1.placeOnMap(match.getMap(), new Point(90, 110));
// gero2.placeOnMap(match.getMap(), new Point(110, 90));
//
// new AttackAction(gero1, gero2).plan();
//
// }
//
// private void aufZuNeuenUfern() {
// for (NonStatic ns : NonStatic.getAllNonStatics()) {
// new MoveAction(ns, findEmptyJunglePoint()).plan();
// }
// }
//
// private void lonleyWulf() {
// Hero gero1 = new GeronimoVonNazareth();
//
// gero1.placeOnMap(match.getMap(), this.findEmptyPoint() );
// }
//
// private void zweiJungsInnerMitte() {
//
// Hero gero1 = new GeronimoVonNazareth();
// Hero gero2 = new game.content.heros.brocky.BrockyAloa();
//
//
// Hero gero3 = new GeronimoVonNazareth();
// Hero gero4 = new game.content.heros.brocky.BrockyAloa();
//
// gero1.setFraction(Fraction.TeamA);
// gero2.setFraction(Fraction.TeamB);
// gero4.setFraction(Fraction.TeamA);
// gero3.setFraction(Fraction.TeamB);
//
//
// gero1.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 - 1, this.getMatch().getMap().DIMENSION.x / 2 + 1));
// gero2.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.y / 2 + 1, this.getMatch().getMap().DIMENSION.y / 2 - 1));
// gero3.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 + 1, this.getMatch().getMap().DIMENSION.x / 2 + 1));
// gero4.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 - 1, this.getMatch().getMap().DIMENSION.x / 2 - 1));
//
// }
}
| rechenberger/arno-wird-60 | Server/src/module/MatchModuleServerTest.java | 3,058 | // gero2.placeOnMap(match.getMap(), coord2 ); | line_comment | nl | package module;
import com.messages.ChatMessage;
import game.objects.GameObject;
//import java.awt.Point;
//import java.util.Arrays;
//
//import com.messages.GameContentMessage;
//import com.messages.MessageType;
//
//import match.KiHandler;
//import module.MatchModuleServer;
//import game.actions.AttackAction;
//import game.actions.MoveAction;
//import game.attributes.Attribute;
//import game.content.effects.active.Following;
//import game.content.effects.direct.Damage;
//import game.content.heros.Hero;
//import game.content.heros.Sprintomanius;
//import game.content.heros.geronimo.GeronimoVonNazareth;
//import game.content.ki.Default;
//import game.content.ki.behavior.KiGroup;
//import game.content.ki.behavior.KiTypes;
//import game.content.statics.Gras;
//import game.content.statics.Path;
//import game.content.statics.Tree;
//import game.effects.ActiveEffect;
//import game.effects.DirectEffect;
//import game.effects.Effect;
//import game.effects.PermanentEffect;
//import game.objects.Fraction;
//import game.objects.Map;
//import game.objects.Match;
//import game.objects.NonStatic;
//import game.objects.WorldObject;
/**
* TestMatchModul.
* @author Tristan
*
* CHECKSTYLE:OFF
*
*/
public class MatchModuleServerTest extends MatchModuleServer {
public void run() {
// this.initializeTestWorld();
// this.kampf();
// this.geroParty();
// this.wettrennen();
// this.schoeneNeueWelt();
// this.konfrontation();
// this.verfolgungsjagt();
// this.lonleyWulf();
// this.zweiJungsInnerMitte();
//new KiGroup(KiTypes.DEFAULT, 6, Fraction.TeamA, match.getMap());
super.run();
}
public void turn() {
// System.out.println("Runde " + (this.turn+1));
// System.out.println("Neue Runde");
super.turn();
// System.out.println(this.turn);
// if(turn == 20) {
// System.out.println(GameObject.getAllGameObjectsSize());
// GameObject.sendAllGameObjects();
// }
if (turn%100 == 0) {
// int[][] mapArray1 = this.getMatch().getMap().toArray();
// GameObject.testSaveNLoad();
// this.match = Match.getMatch();
// int[][] mapArray2 = this.getMatch().getMap().toArray();
//
// if(Arrays.equals(mapArray1, mapArray2)) {
// System.out.println("JAAAAAAA");
// } else {
//
// for (int x = 0; x < mapArray2.length; x++) {
// for (int y = 0; y < mapArray2.length; y++) {
// if (mapArray1[x][y] != mapArray2[x][y]) {
// System.out.println("mapArray1: " + mapArray1[x][y]);
// System.out.println("mapArray2: " + mapArray2[x][y]);
// }
// }
// }
//
// for (int x = mapArray2.length/4; x < mapArray2.length/2; x++) {
// for (int y = mapArray2.length/4; y < mapArray2.length/2; y++) {
// System.out.print(mapArray2[x][y]);
// }
// System.out.println();
// }
//
// System.out.println();
// System.out.println("================================================================================================================================================================================================================================================");
// System.out.println();
//
// for (int x = mapArray2.length/4; x < mapArray2.length/2; x++) {
// for (int y = mapArray2.length/4; y < mapArray2.length/2; y++) {
// System.out.print(mapArray2[x][y]);
// }
// System.out.println();
// }
//
// System.exit(0);
// }
System.out.print("Runde " + this.turn + ", ");
System.out.println(GameObject.getAllGameObjectsSize() + " GameObjects, ");
ModuleHandler.COM.pushMessage((new ChatMessage("Runde " + this.turn)));
// System.out.print( ((double) GameObject.getNextId())*100 / ((double) Integer.MAX_VALUE) );
// System.out.println("% ausgelastet." );
// aufZuNeuenUfern();
}
// Hero gero = GameObject.getById(4);
// System.out.print("Geros Effekte: "); gero.printEffects();
// System.out.println("Geros Position: " + gero.getCoord().toString());
}
// public void geroParty() {
// for(int i=0; i<150; i++) {
//
// Hero gero = new Sprintomanius();
// if (i % 2 == 0) {
// gero.setFraction(Fraction.TeamA);
// } else {
// gero.setFraction(Fraction.TeamB);
// }
//
// gero.placeOnMap(match.getMap(), findEmptyJunglePoint() );
//
// new MoveAction(gero, findEmptyJunglePoint()).plan();
// }
// }
//
// public Point findEmptyJunglePoint() {
// return findEmptyPoint("static/floor/gras");
// }
//
// private Point findEmptyPoint(final String imageURL) {
// Point coord;
// do {
// coord = new Point((int) (Math.random() * Map.DIMENSION.x), (int) (Math.random() * Map.DIMENSION.y));
// } while(this.getMatch().getMap().ifWalkable(coord) || !this.getMatch().getMap().getList(coord).getFirst().getImageURL().equals(imageURL) );
// return coord;
// }
//
// public void schoeneNeueWelt() {
// Hero gero1 = new Sprintomanius();
// gero1.placeOnMap(match.getMap(), new Point(0, 199) );
// new MoveAction(gero1, new Point(162, 42) ).plan();
// }
//
//
// private void konfrontation() {
// for(int x=0; x<20; x=x+2) {
// for(int y=0; y<20; y=y+2) {
//
// Point coord1 = new Point(5+x, 195-y );
// Point coord3 = new Point(25+x, 175-y );
//
// Point coord2 = new Point(195-x, 5+y);
// Point coord4 = new Point(175-x, 25+y);
//
// Hero gero1 = new Sprintomanius();
// Hero gero2 = new Sprintomanius();
//
// gero1.setFraction(Fraction.TeamA);
// gero2.setFraction(Fraction.TeamB);
//
// gero1.placeOnMap(match.getMap(), coord1 );
// gero2.placeOnMap(match.getMap(), coord2<SUF>
//
// new MoveAction(gero1, coord4).plan();
// new MoveAction(gero2, coord3).plan();
// }
// }
// }
//
// private void verfolgungsjagt() {
//
// Hero gero1 = new Sprintomanius();
// Hero gero2 = new Sprintomanius();
//
//
// gero1.placeOnMap(match.getMap(), new Point(90, 110) );
// gero2.placeOnMap(match.getMap(), new Point(110, 90) );
//
//
// new MoveAction(gero1, new Point(199, 0) ).plan();
// new Following(gero2, gero1, 0).ready();
//// new ActionOnNonStatic(gero2, Follow.getInstance(), gero1).plan();
//
//
//// System.out.println("Held 1 : "+gero1.getId());
//// System.out.println("Held 2 : "+gero2.getId());
// }
//
//
// private void kampf() {
//
// Hero gero1 = new GeronimoVonNazareth();
// Hero gero2 = new GeronimoVonNazareth();
//
//
// gero1.placeOnMap(match.getMap(), new Point(90, 110));
// gero2.placeOnMap(match.getMap(), new Point(110, 90));
//
// new AttackAction(gero1, gero2).plan();
//
// }
//
// private void aufZuNeuenUfern() {
// for (NonStatic ns : NonStatic.getAllNonStatics()) {
// new MoveAction(ns, findEmptyJunglePoint()).plan();
// }
// }
//
// private void lonleyWulf() {
// Hero gero1 = new GeronimoVonNazareth();
//
// gero1.placeOnMap(match.getMap(), this.findEmptyPoint() );
// }
//
// private void zweiJungsInnerMitte() {
//
// Hero gero1 = new GeronimoVonNazareth();
// Hero gero2 = new game.content.heros.brocky.BrockyAloa();
//
//
// Hero gero3 = new GeronimoVonNazareth();
// Hero gero4 = new game.content.heros.brocky.BrockyAloa();
//
// gero1.setFraction(Fraction.TeamA);
// gero2.setFraction(Fraction.TeamB);
// gero4.setFraction(Fraction.TeamA);
// gero3.setFraction(Fraction.TeamB);
//
//
// gero1.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 - 1, this.getMatch().getMap().DIMENSION.x / 2 + 1));
// gero2.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.y / 2 + 1, this.getMatch().getMap().DIMENSION.y / 2 - 1));
// gero3.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 + 1, this.getMatch().getMap().DIMENSION.x / 2 + 1));
// gero4.placeOnMap(match.getMap(), new Point(this.getMatch().getMap().DIMENSION.x / 2 - 1, this.getMatch().getMap().DIMENSION.x / 2 - 1));
//
// }
}
|
111337_2 | /*
* Firebird Open Source JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* 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
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.gds.ng.jna;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import org.firebirdsql.gds.JaybirdSystemProperties;
import org.firebirdsql.gds.ng.IAttachProperties;
import org.firebirdsql.jaybird.util.Cleaners;
import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup;
import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary;
import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary;
import org.firebirdsql.jna.fbclient.FbClientLibrary;
import org.firebirdsql.jna.fbclient.WinFbClientLibrary;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the
* Firebird embedded library.
*
* @author Mark Rotteveel
* @since 3.0
*/
public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory {
private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName());
// Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12)
private static final List<String> LIBRARIES_TO_TRY =
List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT);
private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory();
private FbEmbeddedDatabaseFactory() {
// only through getInstance()
}
public static FbEmbeddedDatabaseFactory getInstance() {
return INSTANCE;
}
@Override
protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) {
T attachPropertiesCopy = attachProperties.asNewMutable();
// Clear server name
attachPropertiesCopy.setServerName(null);
return attachPropertiesCopy;
}
@Override
protected Collection<String> defaultLibraryNames() {
return LIBRARIES_TO_TRY;
}
@Override
protected FbClientLibrary createClientLibrary() {
final List<Throwable> throwables = new ArrayList<>();
final List<String> librariesToTry = findLibrariesToTry();
for (String libraryName : librariesToTry) {
try {
if (Platform.isWindows()) {
return Native.load(libraryName, WinFbClientLibrary.class);
} else {
return Native.load(libraryName, FbClientLibrary.class);
}
} catch (RuntimeException | UnsatisfiedLinkError e) {
throwables.add(e);
log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e);
// continue with next
}
}
assert throwables.size() == librariesToTry.size();
if (log.isLoggable(ERROR)) {
log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry);
for (int idx = 0; idx < librariesToTry.size(); idx++) {
log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx));
}
}
throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception",
throwables.get(0));
}
private List<String> findLibrariesToTry() {
final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient();
if (libraryPath != null) {
return Collections.singletonList(libraryPath);
}
Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded();
if (optionalFbEmbeddedInstance.isPresent()) {
FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get();
log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion());
if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) {
NativeResourceTracker.strongRegisterNativeResource(
new FirebirdEmbeddedLibraryNativeResource(disposableLibrary));
}
Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath();
List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1);
librariesToTry.add(entryPointPath.toString());
librariesToTry.addAll(LIBRARIES_TO_TRY);
return librariesToTry;
}
return LIBRARIES_TO_TRY;
}
private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource {
private final Cleaner.Cleanable cleanable;
private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) {
requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary");
cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary));
}
@Override
void dispose() {
cleanable.clean();
}
private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable {
@Override
public void run() {
firebirdEmbeddedLibrary.dispose();
}
}
}
}
| red-soft-ru/jaybird | jaybird-native/src/main/java/org/firebirdsql/gds/ng/jna/FbEmbeddedDatabaseFactory.java | 1,755 | // Note Firebird 3+ embedded is fbclient + engineNN (e.g. engine12 for Firebird 3.0 / ODS 12) | line_comment | nl | /*
* Firebird Open Source JDBC Driver
*
* Distributable under LGPL license.
* You may obtain a copy of the License at http://www.gnu.org/copyleft/lgpl.html
*
* 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
* LGPL License for more details.
*
* This file was created by members of the firebird development team.
* All individual contributions remain the Copyright (C) of those
* individuals. Contributors to this file are either listed here or
* can be obtained from a source control history command.
*
* All rights reserved.
*/
package org.firebirdsql.gds.ng.jna;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import org.firebirdsql.gds.JaybirdSystemProperties;
import org.firebirdsql.gds.ng.IAttachProperties;
import org.firebirdsql.jaybird.util.Cleaners;
import org.firebirdsql.jna.embedded.FirebirdEmbeddedLookup;
import org.firebirdsql.jna.embedded.spi.DisposableFirebirdEmbeddedLibrary;
import org.firebirdsql.jna.embedded.spi.FirebirdEmbeddedLibrary;
import org.firebirdsql.jna.fbclient.FbClientLibrary;
import org.firebirdsql.jna.fbclient.WinFbClientLibrary;
import java.lang.ref.Cleaner;
import java.nio.file.Path;
import java.util.*;
import static java.lang.System.Logger.Level.DEBUG;
import static java.lang.System.Logger.Level.ERROR;
import static java.lang.System.Logger.Level.INFO;
import static java.util.Objects.requireNonNull;
/**
* Implementation of {@link org.firebirdsql.gds.ng.FbDatabaseFactory} for establishing connection using the
* Firebird embedded library.
*
* @author Mark Rotteveel
* @since 3.0
*/
public final class FbEmbeddedDatabaseFactory extends AbstractNativeDatabaseFactory {
private static final System.Logger log = System.getLogger(FbEmbeddedDatabaseFactory.class.getName());
// Note Firebird<SUF>
private static final List<String> LIBRARIES_TO_TRY =
List.of("fbembed", FbClientDatabaseFactory.LIBRARY_NAME_FBCLIENT);
private static final FbEmbeddedDatabaseFactory INSTANCE = new FbEmbeddedDatabaseFactory();
private FbEmbeddedDatabaseFactory() {
// only through getInstance()
}
public static FbEmbeddedDatabaseFactory getInstance() {
return INSTANCE;
}
@Override
protected <T extends IAttachProperties<T>> T filterProperties(T attachProperties) {
T attachPropertiesCopy = attachProperties.asNewMutable();
// Clear server name
attachPropertiesCopy.setServerName(null);
return attachPropertiesCopy;
}
@Override
protected Collection<String> defaultLibraryNames() {
return LIBRARIES_TO_TRY;
}
@Override
protected FbClientLibrary createClientLibrary() {
final List<Throwable> throwables = new ArrayList<>();
final List<String> librariesToTry = findLibrariesToTry();
for (String libraryName : librariesToTry) {
try {
if (Platform.isWindows()) {
return Native.load(libraryName, WinFbClientLibrary.class);
} else {
return Native.load(libraryName, FbClientLibrary.class);
}
} catch (RuntimeException | UnsatisfiedLinkError e) {
throwables.add(e);
log.log(DEBUG, () -> "Attempt to load %s failed".formatted(libraryName), e);
// continue with next
}
}
assert throwables.size() == librariesToTry.size();
if (log.isLoggable(ERROR)) {
log.log(ERROR, "Could not load any of the libraries in {0}:", librariesToTry);
for (int idx = 0; idx < librariesToTry.size(); idx++) {
log.log(ERROR, "Loading %s failed".formatted(librariesToTry.get(idx)), throwables.get(idx));
}
}
throw new NativeLibraryLoadException("Could not load any of " + librariesToTry + "; linking first exception",
throwables.get(0));
}
private List<String> findLibrariesToTry() {
final String libraryPath = JaybirdSystemProperties.getNativeLibraryFbclient();
if (libraryPath != null) {
return Collections.singletonList(libraryPath);
}
Optional<FirebirdEmbeddedLibrary> optionalFbEmbeddedInstance = FirebirdEmbeddedLookup.findFirebirdEmbedded();
if (optionalFbEmbeddedInstance.isPresent()) {
FirebirdEmbeddedLibrary firebirdEmbeddedLibrary = optionalFbEmbeddedInstance.get();
log.log(INFO, "Found Firebird Embedded {0} on classpath", firebirdEmbeddedLibrary.getVersion());
if (firebirdEmbeddedLibrary instanceof DisposableFirebirdEmbeddedLibrary disposableLibrary) {
NativeResourceTracker.strongRegisterNativeResource(
new FirebirdEmbeddedLibraryNativeResource(disposableLibrary));
}
Path entryPointPath = firebirdEmbeddedLibrary.getEntryPointPath().toAbsolutePath();
List<String> librariesToTry = new ArrayList<>(LIBRARIES_TO_TRY.size() + 1);
librariesToTry.add(entryPointPath.toString());
librariesToTry.addAll(LIBRARIES_TO_TRY);
return librariesToTry;
}
return LIBRARIES_TO_TRY;
}
private static final class FirebirdEmbeddedLibraryNativeResource extends NativeResourceTracker.NativeResource {
private final Cleaner.Cleanable cleanable;
private FirebirdEmbeddedLibraryNativeResource(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) {
requireNonNull(firebirdEmbeddedLibrary, "firebirdEmbeddedLibrary");
cleanable = Cleaners.getJbCleaner().register(this, new DisposeAction(firebirdEmbeddedLibrary));
}
@Override
void dispose() {
cleanable.clean();
}
private record DisposeAction(DisposableFirebirdEmbeddedLibrary firebirdEmbeddedLibrary) implements Runnable {
@Override
public void run() {
firebirdEmbeddedLibrary.dispose();
}
}
}
}
|
122326_18 | package org.bouncycastle.asn1.isismtt.x509;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.x500.DirectoryString;
/**
* Professions, specializations, disciplines, fields of activity, etc.
*
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @see org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax
*/
public class ProfessionInfo
extends ASN1Object
{
/**
* Rechtsanw�ltin
*/
public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1");
/**
* Rechtsanwalt
*/
public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2");
/**
* Rechtsbeistand
*/
public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3");
/**
* Steuerberaterin
*/
public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4");
/**
* Steuerberater
*/
public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5");
/**
* Steuerbevollm�chtigte
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6");
/**
* Steuerbevollm�chtigter
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7");
/**
* Notarin
*/
public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8");
/**
* Notar
*/
public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9");
/**
* Notarvertreterin
*/
public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10");
/**
* Notarvertreter
*/
public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11");
/**
* Notariatsverwalterin
*/
public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12");
/**
* Notariatsverwalter
*/
public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13");
/**
* Wirtschaftspr�ferin
*/
public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14");
/**
* Wirtschaftspr�fer
*/
public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15");
/**
* Vereidigte Buchpr�ferin
*/
public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16");
/**
* Vereidigter Buchpr�fer
*/
public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17");
/**
* Patentanw�ltin
*/
public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18");
/**
* Patentanwalt
*/
public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19");
private NamingAuthority namingAuthority;
private ASN1Sequence professionItems;
private ASN1Sequence professionOIDs;
private String registrationNumber;
private ASN1OctetString addProfessionInfo;
public static ProfessionInfo getInstance(Object obj)
{
if (obj == null || obj instanceof ProfessionInfo)
{
return (ProfessionInfo)obj;
}
if (obj instanceof ASN1Sequence)
{
return new ProfessionInfo((ASN1Sequence)obj);
}
throw new IllegalArgumentException("illegal object in getInstance: "
+ obj.getClass().getName());
}
/**
* Constructor from ASN1Sequence.
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @param seq The ASN.1 sequence.
*/
private ProfessionInfo(ASN1Sequence seq)
{
if (seq.size() > 5)
{
throw new IllegalArgumentException("Bad sequence size: "
+ seq.size());
}
Enumeration e = seq.getObjects();
ASN1Encodable o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1TaggedObject)
{
if (((ASN1TaggedObject)o).getTagNo() != 0)
{
throw new IllegalArgumentException("Bad tag number: "
+ ((ASN1TaggedObject)o).getTagNo());
}
namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true);
o = (ASN1Encodable)e.nextElement();
}
professionItems = ASN1Sequence.getInstance(o);
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1Sequence)
{
professionOIDs = ASN1Sequence.getInstance(o);
}
else if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof ASN1OctetString)
{
addProfessionInfo = ASN1OctetString.getInstance(o);
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
}
/**
* Constructor from given details.
* <p>
* <code>professionItems</code> is mandatory, all other parameters are
* optional.
*
* @param namingAuthority The naming authority.
* @param professionItems Directory strings of the profession.
* @param professionOIDs DERObjectIdentfier objects for the
* profession.
* @param registrationNumber Registration number.
* @param addProfessionInfo Additional infos in encoded form.
*/
public ProfessionInfo(NamingAuthority namingAuthority,
DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs,
String registrationNumber, ASN1OctetString addProfessionInfo)
{
this.namingAuthority = namingAuthority;
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != professionItems.length; i++)
{
v.add(professionItems[i]);
}
this.professionItems = new DERSequence(v);
if (professionOIDs != null)
{
v = new ASN1EncodableVector();
for (int i = 0; i != professionOIDs.length; i++)
{
v.add(professionOIDs[i]);
}
this.professionOIDs = new DERSequence(v);
}
this.registrationNumber = registrationNumber;
this.addProfessionInfo = addProfessionInfo;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <p>
* Returns:
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @return a DERObject
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector vec = new ASN1EncodableVector();
if (namingAuthority != null)
{
vec.add(new DERTaggedObject(true, 0, namingAuthority));
}
vec.add(professionItems);
if (professionOIDs != null)
{
vec.add(professionOIDs);
}
if (registrationNumber != null)
{
vec.add(new DERPrintableString(registrationNumber, true));
}
if (addProfessionInfo != null)
{
vec.add(addProfessionInfo);
}
return new DERSequence(vec);
}
/**
* @return Returns the addProfessionInfo.
*/
public ASN1OctetString getAddProfessionInfo()
{
return addProfessionInfo;
}
/**
* @return Returns the namingAuthority.
*/
public NamingAuthority getNamingAuthority()
{
return namingAuthority;
}
/**
* @return Returns the professionItems.
*/
public DirectoryString[] getProfessionItems()
{
DirectoryString[] items = new DirectoryString[professionItems.size()];
int count = 0;
for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();)
{
items[count++] = DirectoryString.getInstance(e.nextElement());
}
return items;
}
/**
* @return Returns the professionOIDs.
*/
public ASN1ObjectIdentifier[] getProfessionOIDs()
{
if (professionOIDs == null)
{
return new ASN1ObjectIdentifier[0];
}
ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()];
int count = 0;
for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();)
{
oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement());
}
return oids;
}
/**
* @return Returns the registrationNumber.
*/
public String getRegistrationNumber()
{
return registrationNumber;
}
}
| redfish64/TinyTravelTracker | app/src/main/java/org/bouncycastle/asn1/isismtt/x509/ProfessionInfo.java | 3,995 | /**
* Patentanw�ltin
*/ | block_comment | nl | package org.bouncycastle.asn1.isismtt.x509;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1TaggedObject;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.DERPrintableString;
import org.bouncycastle.asn1.DERSequence;
import org.bouncycastle.asn1.DERTaggedObject;
import org.bouncycastle.asn1.x500.DirectoryString;
/**
* Professions, specializations, disciplines, fields of activity, etc.
*
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @see org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax
*/
public class ProfessionInfo
extends ASN1Object
{
/**
* Rechtsanw�ltin
*/
public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1");
/**
* Rechtsanwalt
*/
public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2");
/**
* Rechtsbeistand
*/
public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3");
/**
* Steuerberaterin
*/
public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4");
/**
* Steuerberater
*/
public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5");
/**
* Steuerbevollm�chtigte
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6");
/**
* Steuerbevollm�chtigter
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7");
/**
* Notarin
*/
public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8");
/**
* Notar
*/
public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9");
/**
* Notarvertreterin
*/
public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10");
/**
* Notarvertreter
*/
public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11");
/**
* Notariatsverwalterin
*/
public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12");
/**
* Notariatsverwalter
*/
public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13");
/**
* Wirtschaftspr�ferin
*/
public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14");
/**
* Wirtschaftspr�fer
*/
public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15");
/**
* Vereidigte Buchpr�ferin
*/
public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16");
/**
* Vereidigter Buchpr�fer
*/
public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17");
/**
* Patentanw�ltin
<SUF>*/
public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18");
/**
* Patentanwalt
*/
public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19");
private NamingAuthority namingAuthority;
private ASN1Sequence professionItems;
private ASN1Sequence professionOIDs;
private String registrationNumber;
private ASN1OctetString addProfessionInfo;
public static ProfessionInfo getInstance(Object obj)
{
if (obj == null || obj instanceof ProfessionInfo)
{
return (ProfessionInfo)obj;
}
if (obj instanceof ASN1Sequence)
{
return new ProfessionInfo((ASN1Sequence)obj);
}
throw new IllegalArgumentException("illegal object in getInstance: "
+ obj.getClass().getName());
}
/**
* Constructor from ASN1Sequence.
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @param seq The ASN.1 sequence.
*/
private ProfessionInfo(ASN1Sequence seq)
{
if (seq.size() > 5)
{
throw new IllegalArgumentException("Bad sequence size: "
+ seq.size());
}
Enumeration e = seq.getObjects();
ASN1Encodable o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1TaggedObject)
{
if (((ASN1TaggedObject)o).getTagNo() != 0)
{
throw new IllegalArgumentException("Bad tag number: "
+ ((ASN1TaggedObject)o).getTagNo());
}
namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true);
o = (ASN1Encodable)e.nextElement();
}
professionItems = ASN1Sequence.getInstance(o);
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1Sequence)
{
professionOIDs = ASN1Sequence.getInstance(o);
}
else if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof ASN1OctetString)
{
addProfessionInfo = ASN1OctetString.getInstance(o);
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
}
/**
* Constructor from given details.
* <p>
* <code>professionItems</code> is mandatory, all other parameters are
* optional.
*
* @param namingAuthority The naming authority.
* @param professionItems Directory strings of the profession.
* @param professionOIDs DERObjectIdentfier objects for the
* profession.
* @param registrationNumber Registration number.
* @param addProfessionInfo Additional infos in encoded form.
*/
public ProfessionInfo(NamingAuthority namingAuthority,
DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs,
String registrationNumber, ASN1OctetString addProfessionInfo)
{
this.namingAuthority = namingAuthority;
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != professionItems.length; i++)
{
v.add(professionItems[i]);
}
this.professionItems = new DERSequence(v);
if (professionOIDs != null)
{
v = new ASN1EncodableVector();
for (int i = 0; i != professionOIDs.length; i++)
{
v.add(professionOIDs[i]);
}
this.professionOIDs = new DERSequence(v);
}
this.registrationNumber = registrationNumber;
this.addProfessionInfo = addProfessionInfo;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <p>
* Returns:
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @return a DERObject
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector vec = new ASN1EncodableVector();
if (namingAuthority != null)
{
vec.add(new DERTaggedObject(true, 0, namingAuthority));
}
vec.add(professionItems);
if (professionOIDs != null)
{
vec.add(professionOIDs);
}
if (registrationNumber != null)
{
vec.add(new DERPrintableString(registrationNumber, true));
}
if (addProfessionInfo != null)
{
vec.add(addProfessionInfo);
}
return new DERSequence(vec);
}
/**
* @return Returns the addProfessionInfo.
*/
public ASN1OctetString getAddProfessionInfo()
{
return addProfessionInfo;
}
/**
* @return Returns the namingAuthority.
*/
public NamingAuthority getNamingAuthority()
{
return namingAuthority;
}
/**
* @return Returns the professionItems.
*/
public DirectoryString[] getProfessionItems()
{
DirectoryString[] items = new DirectoryString[professionItems.size()];
int count = 0;
for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();)
{
items[count++] = DirectoryString.getInstance(e.nextElement());
}
return items;
}
/**
* @return Returns the professionOIDs.
*/
public ASN1ObjectIdentifier[] getProfessionOIDs()
{
if (professionOIDs == null)
{
return new ASN1ObjectIdentifier[0];
}
ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()];
int count = 0;
for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();)
{
oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement());
}
return oids;
}
/**
* @return Returns the registrationNumber.
*/
public String getRegistrationNumber()
{
return registrationNumber;
}
}
|
13410_2 | package redis.clients.jedis.graph;
import static java.util.Collections.emptyList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import redis.clients.jedis.Builder;
import redis.clients.jedis.BuilderFactory;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.graph.entities.*;
import redis.clients.jedis.util.SafeEncoder;
/**
* @deprecated Redis Graph support is deprecated.
*/
@Deprecated
class ResultSetBuilder extends Builder<ResultSet> {
private final GraphCache graphCache;
ResultSetBuilder(GraphCache cache) {
this.graphCache = cache;
}
@Override
public ResultSet build(Object data) {
List<Object> rawResponse = (List<Object>) data;
// If a run-time error occurred, the last member of the rawResponse will be a
// JedisDataException.
if (rawResponse.get(rawResponse.size() - 1) instanceof JedisDataException) {
throw (JedisDataException) rawResponse.get(rawResponse.size() - 1);
}
//
// HeaderImpl header = parseHeader(rawResponse.get(0));
// List<Record> records = parseRecords(header, rawResponse.get(1));
// StatisticsImpl statistics = parseStatistics(rawResponse.get(2));
// return new ResultSetImpl(header, records, statistics);
final Object headerObject;
final Object recordsObject;
final Object statisticsObject;
if (rawResponse.size() == 1) {
headerObject = emptyList();
recordsObject = emptyList();
statisticsObject = rawResponse.get(0);
} else if (rawResponse.size() == 3) {
headerObject = rawResponse.get(0);
recordsObject = rawResponse.get(1);
statisticsObject = rawResponse.get(2);
} else {
throw new JedisException("Unrecognized graph response format.");
}
HeaderImpl header = parseHeader(headerObject);
List<Record> records = parseRecords(header, recordsObject);
StatisticsImpl statistics = parseStatistics(statisticsObject);
return new ResultSetImpl(header, records, statistics);
}
private class ResultSetImpl implements ResultSet {
private final Header header;
private final List<Record> results;
private final Statistics statistics;
private ResultSetImpl(Header header, List<Record> results, Statistics statistics) {
this.header = header;
this.results = results;
this.statistics = statistics;
}
@Override
public Header getHeader() {
return header;
}
@Override
public Statistics getStatistics() {
return statistics;
}
@Override
public int size() {
return results.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ResultSetImpl)) {
return false;
}
ResultSetImpl resultSet = (ResultSetImpl) o;
return Objects.equals(getHeader(), resultSet.getHeader())
&& Objects.equals(getStatistics(), resultSet.getStatistics())
&& Objects.equals(results, resultSet.results);
}
@Override
public int hashCode() {
return Objects.hash(getHeader(), getStatistics(), results);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ResultSetImpl{");
sb.append("header=").append(header);
sb.append(", statistics=").append(statistics);
sb.append(", results=").append(results);
sb.append('}');
return sb.toString();
}
@Override
public Iterator<Record> iterator() {
return results.iterator();
}
}
@SuppressWarnings("unchecked")
private List<Record> parseRecords(Header header, Object data) {
List<List<Object>> rawResultSet = (List<List<Object>>) data;
if (rawResultSet == null || rawResultSet.isEmpty()) {
return new ArrayList<>(0);
}
List<Record> results = new ArrayList<>(rawResultSet.size());
// go over each raw result
for (List<Object> row : rawResultSet) {
List<Object> parsedRow = new ArrayList<>(row.size());
// go over each object in the result
for (int i = 0; i < row.size(); i++) {
// get raw representation of the object
List<Object> obj = (List<Object>) row.get(i);
// get object type
ResultSet.ColumnType objType = header.getSchemaTypes().get(i);
// deserialize according to type and
switch (objType) {
case NODE:
parsedRow.add(deserializeNode(obj));
break;
case RELATION:
parsedRow.add(deserializeEdge(obj));
break;
case SCALAR:
parsedRow.add(deserializeScalar(obj));
break;
default:
parsedRow.add(null);
break;
}
}
// create new record from deserialized objects
Record record = new RecordImpl(header.getSchemaNames(), parsedRow);
results.add(record);
}
return results;
}
/**
* @param rawNodeData - raw node object in the form of list of object rawNodeData.get(0) - id
* (long) rawNodeData.get(1) - a list y which contains the labels of this node. Each entry is a
* label id from the type of long rawNodeData.get(2) - a list which contains the properties of the
* node.
* @return Node object
*/
@SuppressWarnings("unchecked")
private Node deserializeNode(List<Object> rawNodeData) {
List<Long> labelsIndices = (List<Long>) rawNodeData.get(1);
List<List<Object>> rawProperties = (List<List<Object>>) rawNodeData.get(2);
Node node = new Node(labelsIndices.size(), rawProperties.size());
deserializeGraphEntityId(node, (Long) rawNodeData.get(0));
for (Long labelIndex : labelsIndices) {
String label = graphCache.getLabel(labelIndex.intValue());
node.addLabel(label);
}
deserializeGraphEntityProperties(node, rawProperties);
return node;
}
/**
* @param graphEntity graph entity
* @param id entity id to be set to the graph entity
*/
private void deserializeGraphEntityId(GraphEntity graphEntity, long id) {
graphEntity.setId(id);
}
/**
* @param rawEdgeData - a list of objects rawEdgeData[0] - edge id rawEdgeData[1] - edge
* relationship type rawEdgeData[2] - edge source rawEdgeData[3] - edge destination rawEdgeData[4]
* - edge properties
* @return Edge object
*/
@SuppressWarnings("unchecked")
private Edge deserializeEdge(List<Object> rawEdgeData) {
List<List<Object>> rawProperties = (List<List<Object>>) rawEdgeData.get(4);
Edge edge = new Edge(rawProperties.size());
deserializeGraphEntityId(edge, (Long) rawEdgeData.get(0));
String relationshipType = graphCache.getRelationshipType(((Long) rawEdgeData.get(1)).intValue());
edge.setRelationshipType(relationshipType);
edge.setSource((long) rawEdgeData.get(2));
edge.setDestination((long) rawEdgeData.get(3));
deserializeGraphEntityProperties(edge, rawProperties);
return edge;
}
/**
* @param entity graph entity for adding the properties to
* @param rawProperties raw representation of a list of graph entity properties. Each entry is a
* list (rawProperty) is a raw representation of property, as follows: rawProperty.get(0) -
* property key rawProperty.get(1) - property type rawProperty.get(2) - property value
*/
private void deserializeGraphEntityProperties(GraphEntity entity, List<List<Object>> rawProperties) {
for (List<Object> rawProperty : rawProperties) {
String name = graphCache.getPropertyName(((Long) rawProperty.get(0)).intValue());
// trimmed for getting to value using deserializeScalar
List<Object> propertyScalar = rawProperty.subList(1, rawProperty.size());
entity.addProperty(name, deserializeScalar(propertyScalar));
}
}
/**
* @param rawScalarData - a list of object. list[0] is the scalar type, list[1] is the scalar
* value
* @return value of the specific scalar type
*/
@SuppressWarnings("unchecked")
private Object deserializeScalar(List<Object> rawScalarData) {
ScalarType type = getValueTypeFromObject(rawScalarData.get(0));
Object obj = rawScalarData.get(1);
switch (type) {
case NULL:
return null;
case BOOLEAN:
return Boolean.parseBoolean(SafeEncoder.encode((byte[]) obj));
case DOUBLE:
return BuilderFactory.DOUBLE.build(obj);
case INTEGER:
return (Long) obj;
case STRING:
return SafeEncoder.encode((byte[]) obj);
case ARRAY:
return deserializeArray(obj);
case NODE:
return deserializeNode((List<Object>) obj);
case EDGE:
return deserializeEdge((List<Object>) obj);
case PATH:
return deserializePath(obj);
case MAP:
return deserializeMap(obj);
case POINT:
return deserializePoint(obj);
case UNKNOWN:
default:
return obj;
}
}
private Object deserializePoint(Object rawScalarData) {
return new Point(BuilderFactory.DOUBLE_LIST.build(rawScalarData));
}
@SuppressWarnings("unchecked")
private Map<String, Object> deserializeMap(Object rawScalarData) {
List<Object> keyTypeValueEntries = (List<Object>) rawScalarData;
int size = keyTypeValueEntries.size();
Map<String, Object> map = new HashMap<>(size >> 1); // set the capacity to half of the list
for (int i = 0; i < size; i += 2) {
String key = SafeEncoder.encode((byte[]) keyTypeValueEntries.get(i));
Object value = deserializeScalar((List<Object>) keyTypeValueEntries.get(i + 1));
map.put(key, value);
}
return map;
}
@SuppressWarnings("unchecked")
private Path deserializePath(Object rawScalarData) {
List<List<Object>> array = (List<List<Object>>) rawScalarData;
List<Node> nodes = (List<Node>) deserializeScalar(array.get(0));
List<Edge> edges = (List<Edge>) deserializeScalar(array.get(1));
return new Path(nodes, edges);
}
@SuppressWarnings("unchecked")
private List<Object> deserializeArray(Object rawScalarData) {
List<List<Object>> array = (List<List<Object>>) rawScalarData;
List<Object> res = new ArrayList<>(array.size());
for (List<Object> arrayValue : array) {
res.add(deserializeScalar(arrayValue));
}
return res;
}
/**
* Auxiliary function to retrieve scalar types
*
* @param rawScalarType
* @return scalar type
*/
private ScalarType getValueTypeFromObject(Object rawScalarType) {
return getScalarType(((Long) rawScalarType).intValue());
}
private static enum ScalarType {
UNKNOWN,
NULL,
STRING,
INTEGER, // 64-bit long.
BOOLEAN,
DOUBLE,
ARRAY,
EDGE,
NODE,
PATH,
MAP,
POINT;
}
private static final ScalarType[] SCALAR_TYPES = ScalarType.values();
private static ScalarType getScalarType(int index) {
try {
return SCALAR_TYPES[index];
} catch (IndexOutOfBoundsException e) {
throw new JedisException("Unrecognized response type");
}
}
private class RecordImpl implements Record {
private final List<String> header;
private final List<Object> values;
public RecordImpl(List<String> header, List<Object> values) {
this.header = header;
this.values = values;
}
@Override
public <T> T getValue(int index) {
return (T) this.values.get(index);
}
@Override
public <T> T getValue(String key) {
return getValue(this.header.indexOf(key));
}
@Override
public String getString(int index) {
return this.values.get(index).toString();
}
@Override
public String getString(String key) {
return getString(this.header.indexOf(key));
}
@Override
public List<String> keys() {
return header;
}
@Override
public List<Object> values() {
return this.values;
}
@Override
public boolean containsKey(String key) {
return this.header.contains(key);
}
@Override
public int size() {
return this.header.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RecordImpl)) {
return false;
}
RecordImpl record = (RecordImpl) o;
return Objects.equals(header, record.header)
&& Objects.equals(values, record.values);
}
@Override
public int hashCode() {
return Objects.hash(header, values);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Record{");
sb.append("values=").append(values);
sb.append('}');
return sb.toString();
}
}
private static final ResultSet.ColumnType[] COLUMN_TYPES = ResultSet.ColumnType.values();
private class HeaderImpl implements Header {
private final List<ResultSet.ColumnType> schemaTypes;
private final List<String> schemaNames;
private HeaderImpl() {
this.schemaTypes = emptyList();
this.schemaNames = emptyList();
}
private HeaderImpl(List<ResultSet.ColumnType> schemaTypes, List<String> schemaNames) {
this.schemaTypes = schemaTypes;
this.schemaNames = schemaNames;
}
/**
* @return a list of column names, ordered by they appearance in the query
*/
@Override
public List<String> getSchemaNames() {
return schemaNames;
}
/**
* @return a list of column types, ordered by they appearance in the query
*/
@Override
public List<ResultSet.ColumnType> getSchemaTypes() {
return schemaTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HeaderImpl)) {
return false;
}
HeaderImpl header = (HeaderImpl) o;
return Objects.equals(getSchemaTypes(), header.getSchemaTypes())
&& Objects.equals(getSchemaNames(), header.getSchemaNames());
}
@Override
public int hashCode() {
return Objects.hash(getSchemaTypes(), getSchemaNames());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("HeaderImpl{");
sb.append("schemaTypes=").append(schemaTypes);
sb.append(", schemaNames=").append(schemaNames);
sb.append('}');
return sb.toString();
}
}
private HeaderImpl parseHeader(Object data) {
if (data == null) {
return new HeaderImpl();
}
List<List<Object>> list = (List<List<Object>>) data;
List<ResultSet.ColumnType> types = new ArrayList<>(list.size());
List<String> texts = new ArrayList<>(list.size());
for (List<Object> tuple : list) {
types.add(COLUMN_TYPES[((Long) tuple.get(0)).intValue()]);
texts.add(SafeEncoder.encode((byte[]) tuple.get(1)));
}
return new HeaderImpl(types, texts);
}
private class StatisticsImpl implements Statistics {
private final Map<String, String> statistics;
private StatisticsImpl(Map<String, String> statistics) {
this.statistics = statistics;
}
/**
*
* @param label the requested statistic label as key
* @return a string with the value, if key exists, null otherwise
*/
public String getStringValue(String label) {
return statistics.get(label);
}
/**
*
* @param label the requested statistic label as key
* @return a string with the value, if key exists, 0 otherwise
*/
private int getIntValue(String label) {
String value = getStringValue(label);
return value == null ? 0 : Integer.parseInt(value);
}
/**
*
* @return number of nodes created after query execution
*/
@Override
public int nodesCreated() {
return getIntValue("Nodes created");
}
/**
*
* @return number of nodes deleted after query execution
*/
@Override
public int nodesDeleted() {
return getIntValue("Nodes deleted");
}
/**
*
* @return number of indices added after query execution
*/
@Override
public int indicesCreated() {
return getIntValue("Indices created");
}
@Override
public int indicesDeleted() {
return getIntValue("Indices deleted");
}
/**
*
* @return number of labels added after query execution
*/
@Override
public int labelsAdded() {
return getIntValue("Labels added");
}
/**
*
* @return number of relationship deleted after query execution
*/
@Override
public int relationshipsDeleted() {
return getIntValue("Relationships deleted");
}
/**
*
* @return number of relationship created after query execution
*/
@Override
public int relationshipsCreated() {
return getIntValue("Relationships created");
}
/**
*
* @return number of properties set after query execution
*/
@Override
public int propertiesSet() {
return getIntValue("Properties set");
}
/**
*
* @return The execution plan was cached on RedisGraph.
*/
@Override
public boolean cachedExecution() {
return "1".equals(getStringValue("Cached execution"));
}
@Override
public String queryIntervalExecutionTime() {
return getStringValue("Query internal execution time");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof StatisticsImpl)) {
return false;
}
StatisticsImpl that = (StatisticsImpl) o;
return Objects.equals(statistics, that.statistics);
}
@Override
public int hashCode() {
return Objects.hash(statistics);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Statistics{");
sb.append(statistics);
sb.append('}');
return sb.toString();
}
}
private StatisticsImpl parseStatistics(Object data) {
Map<String, String> map = ((List<byte[]>) data).stream()
.map(SafeEncoder::encode).map(s -> s.split(": "))
.collect(Collectors.toMap(sa -> sa[0], sa -> sa[1]));
return new StatisticsImpl(map);
}
}
| redis/jedis | src/main/java/redis/clients/jedis/graph/ResultSetBuilder.java | 5,468 | // HeaderImpl header = parseHeader(rawResponse.get(0)); | line_comment | nl | package redis.clients.jedis.graph;
import static java.util.Collections.emptyList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import redis.clients.jedis.Builder;
import redis.clients.jedis.BuilderFactory;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.graph.entities.*;
import redis.clients.jedis.util.SafeEncoder;
/**
* @deprecated Redis Graph support is deprecated.
*/
@Deprecated
class ResultSetBuilder extends Builder<ResultSet> {
private final GraphCache graphCache;
ResultSetBuilder(GraphCache cache) {
this.graphCache = cache;
}
@Override
public ResultSet build(Object data) {
List<Object> rawResponse = (List<Object>) data;
// If a run-time error occurred, the last member of the rawResponse will be a
// JedisDataException.
if (rawResponse.get(rawResponse.size() - 1) instanceof JedisDataException) {
throw (JedisDataException) rawResponse.get(rawResponse.size() - 1);
}
//
// HeaderImpl header<SUF>
// List<Record> records = parseRecords(header, rawResponse.get(1));
// StatisticsImpl statistics = parseStatistics(rawResponse.get(2));
// return new ResultSetImpl(header, records, statistics);
final Object headerObject;
final Object recordsObject;
final Object statisticsObject;
if (rawResponse.size() == 1) {
headerObject = emptyList();
recordsObject = emptyList();
statisticsObject = rawResponse.get(0);
} else if (rawResponse.size() == 3) {
headerObject = rawResponse.get(0);
recordsObject = rawResponse.get(1);
statisticsObject = rawResponse.get(2);
} else {
throw new JedisException("Unrecognized graph response format.");
}
HeaderImpl header = parseHeader(headerObject);
List<Record> records = parseRecords(header, recordsObject);
StatisticsImpl statistics = parseStatistics(statisticsObject);
return new ResultSetImpl(header, records, statistics);
}
private class ResultSetImpl implements ResultSet {
private final Header header;
private final List<Record> results;
private final Statistics statistics;
private ResultSetImpl(Header header, List<Record> results, Statistics statistics) {
this.header = header;
this.results = results;
this.statistics = statistics;
}
@Override
public Header getHeader() {
return header;
}
@Override
public Statistics getStatistics() {
return statistics;
}
@Override
public int size() {
return results.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ResultSetImpl)) {
return false;
}
ResultSetImpl resultSet = (ResultSetImpl) o;
return Objects.equals(getHeader(), resultSet.getHeader())
&& Objects.equals(getStatistics(), resultSet.getStatistics())
&& Objects.equals(results, resultSet.results);
}
@Override
public int hashCode() {
return Objects.hash(getHeader(), getStatistics(), results);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ResultSetImpl{");
sb.append("header=").append(header);
sb.append(", statistics=").append(statistics);
sb.append(", results=").append(results);
sb.append('}');
return sb.toString();
}
@Override
public Iterator<Record> iterator() {
return results.iterator();
}
}
@SuppressWarnings("unchecked")
private List<Record> parseRecords(Header header, Object data) {
List<List<Object>> rawResultSet = (List<List<Object>>) data;
if (rawResultSet == null || rawResultSet.isEmpty()) {
return new ArrayList<>(0);
}
List<Record> results = new ArrayList<>(rawResultSet.size());
// go over each raw result
for (List<Object> row : rawResultSet) {
List<Object> parsedRow = new ArrayList<>(row.size());
// go over each object in the result
for (int i = 0; i < row.size(); i++) {
// get raw representation of the object
List<Object> obj = (List<Object>) row.get(i);
// get object type
ResultSet.ColumnType objType = header.getSchemaTypes().get(i);
// deserialize according to type and
switch (objType) {
case NODE:
parsedRow.add(deserializeNode(obj));
break;
case RELATION:
parsedRow.add(deserializeEdge(obj));
break;
case SCALAR:
parsedRow.add(deserializeScalar(obj));
break;
default:
parsedRow.add(null);
break;
}
}
// create new record from deserialized objects
Record record = new RecordImpl(header.getSchemaNames(), parsedRow);
results.add(record);
}
return results;
}
/**
* @param rawNodeData - raw node object in the form of list of object rawNodeData.get(0) - id
* (long) rawNodeData.get(1) - a list y which contains the labels of this node. Each entry is a
* label id from the type of long rawNodeData.get(2) - a list which contains the properties of the
* node.
* @return Node object
*/
@SuppressWarnings("unchecked")
private Node deserializeNode(List<Object> rawNodeData) {
List<Long> labelsIndices = (List<Long>) rawNodeData.get(1);
List<List<Object>> rawProperties = (List<List<Object>>) rawNodeData.get(2);
Node node = new Node(labelsIndices.size(), rawProperties.size());
deserializeGraphEntityId(node, (Long) rawNodeData.get(0));
for (Long labelIndex : labelsIndices) {
String label = graphCache.getLabel(labelIndex.intValue());
node.addLabel(label);
}
deserializeGraphEntityProperties(node, rawProperties);
return node;
}
/**
* @param graphEntity graph entity
* @param id entity id to be set to the graph entity
*/
private void deserializeGraphEntityId(GraphEntity graphEntity, long id) {
graphEntity.setId(id);
}
/**
* @param rawEdgeData - a list of objects rawEdgeData[0] - edge id rawEdgeData[1] - edge
* relationship type rawEdgeData[2] - edge source rawEdgeData[3] - edge destination rawEdgeData[4]
* - edge properties
* @return Edge object
*/
@SuppressWarnings("unchecked")
private Edge deserializeEdge(List<Object> rawEdgeData) {
List<List<Object>> rawProperties = (List<List<Object>>) rawEdgeData.get(4);
Edge edge = new Edge(rawProperties.size());
deserializeGraphEntityId(edge, (Long) rawEdgeData.get(0));
String relationshipType = graphCache.getRelationshipType(((Long) rawEdgeData.get(1)).intValue());
edge.setRelationshipType(relationshipType);
edge.setSource((long) rawEdgeData.get(2));
edge.setDestination((long) rawEdgeData.get(3));
deserializeGraphEntityProperties(edge, rawProperties);
return edge;
}
/**
* @param entity graph entity for adding the properties to
* @param rawProperties raw representation of a list of graph entity properties. Each entry is a
* list (rawProperty) is a raw representation of property, as follows: rawProperty.get(0) -
* property key rawProperty.get(1) - property type rawProperty.get(2) - property value
*/
private void deserializeGraphEntityProperties(GraphEntity entity, List<List<Object>> rawProperties) {
for (List<Object> rawProperty : rawProperties) {
String name = graphCache.getPropertyName(((Long) rawProperty.get(0)).intValue());
// trimmed for getting to value using deserializeScalar
List<Object> propertyScalar = rawProperty.subList(1, rawProperty.size());
entity.addProperty(name, deserializeScalar(propertyScalar));
}
}
/**
* @param rawScalarData - a list of object. list[0] is the scalar type, list[1] is the scalar
* value
* @return value of the specific scalar type
*/
@SuppressWarnings("unchecked")
private Object deserializeScalar(List<Object> rawScalarData) {
ScalarType type = getValueTypeFromObject(rawScalarData.get(0));
Object obj = rawScalarData.get(1);
switch (type) {
case NULL:
return null;
case BOOLEAN:
return Boolean.parseBoolean(SafeEncoder.encode((byte[]) obj));
case DOUBLE:
return BuilderFactory.DOUBLE.build(obj);
case INTEGER:
return (Long) obj;
case STRING:
return SafeEncoder.encode((byte[]) obj);
case ARRAY:
return deserializeArray(obj);
case NODE:
return deserializeNode((List<Object>) obj);
case EDGE:
return deserializeEdge((List<Object>) obj);
case PATH:
return deserializePath(obj);
case MAP:
return deserializeMap(obj);
case POINT:
return deserializePoint(obj);
case UNKNOWN:
default:
return obj;
}
}
private Object deserializePoint(Object rawScalarData) {
return new Point(BuilderFactory.DOUBLE_LIST.build(rawScalarData));
}
@SuppressWarnings("unchecked")
private Map<String, Object> deserializeMap(Object rawScalarData) {
List<Object> keyTypeValueEntries = (List<Object>) rawScalarData;
int size = keyTypeValueEntries.size();
Map<String, Object> map = new HashMap<>(size >> 1); // set the capacity to half of the list
for (int i = 0; i < size; i += 2) {
String key = SafeEncoder.encode((byte[]) keyTypeValueEntries.get(i));
Object value = deserializeScalar((List<Object>) keyTypeValueEntries.get(i + 1));
map.put(key, value);
}
return map;
}
@SuppressWarnings("unchecked")
private Path deserializePath(Object rawScalarData) {
List<List<Object>> array = (List<List<Object>>) rawScalarData;
List<Node> nodes = (List<Node>) deserializeScalar(array.get(0));
List<Edge> edges = (List<Edge>) deserializeScalar(array.get(1));
return new Path(nodes, edges);
}
@SuppressWarnings("unchecked")
private List<Object> deserializeArray(Object rawScalarData) {
List<List<Object>> array = (List<List<Object>>) rawScalarData;
List<Object> res = new ArrayList<>(array.size());
for (List<Object> arrayValue : array) {
res.add(deserializeScalar(arrayValue));
}
return res;
}
/**
* Auxiliary function to retrieve scalar types
*
* @param rawScalarType
* @return scalar type
*/
private ScalarType getValueTypeFromObject(Object rawScalarType) {
return getScalarType(((Long) rawScalarType).intValue());
}
private static enum ScalarType {
UNKNOWN,
NULL,
STRING,
INTEGER, // 64-bit long.
BOOLEAN,
DOUBLE,
ARRAY,
EDGE,
NODE,
PATH,
MAP,
POINT;
}
private static final ScalarType[] SCALAR_TYPES = ScalarType.values();
private static ScalarType getScalarType(int index) {
try {
return SCALAR_TYPES[index];
} catch (IndexOutOfBoundsException e) {
throw new JedisException("Unrecognized response type");
}
}
private class RecordImpl implements Record {
private final List<String> header;
private final List<Object> values;
public RecordImpl(List<String> header, List<Object> values) {
this.header = header;
this.values = values;
}
@Override
public <T> T getValue(int index) {
return (T) this.values.get(index);
}
@Override
public <T> T getValue(String key) {
return getValue(this.header.indexOf(key));
}
@Override
public String getString(int index) {
return this.values.get(index).toString();
}
@Override
public String getString(String key) {
return getString(this.header.indexOf(key));
}
@Override
public List<String> keys() {
return header;
}
@Override
public List<Object> values() {
return this.values;
}
@Override
public boolean containsKey(String key) {
return this.header.contains(key);
}
@Override
public int size() {
return this.header.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof RecordImpl)) {
return false;
}
RecordImpl record = (RecordImpl) o;
return Objects.equals(header, record.header)
&& Objects.equals(values, record.values);
}
@Override
public int hashCode() {
return Objects.hash(header, values);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Record{");
sb.append("values=").append(values);
sb.append('}');
return sb.toString();
}
}
private static final ResultSet.ColumnType[] COLUMN_TYPES = ResultSet.ColumnType.values();
private class HeaderImpl implements Header {
private final List<ResultSet.ColumnType> schemaTypes;
private final List<String> schemaNames;
private HeaderImpl() {
this.schemaTypes = emptyList();
this.schemaNames = emptyList();
}
private HeaderImpl(List<ResultSet.ColumnType> schemaTypes, List<String> schemaNames) {
this.schemaTypes = schemaTypes;
this.schemaNames = schemaNames;
}
/**
* @return a list of column names, ordered by they appearance in the query
*/
@Override
public List<String> getSchemaNames() {
return schemaNames;
}
/**
* @return a list of column types, ordered by they appearance in the query
*/
@Override
public List<ResultSet.ColumnType> getSchemaTypes() {
return schemaTypes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof HeaderImpl)) {
return false;
}
HeaderImpl header = (HeaderImpl) o;
return Objects.equals(getSchemaTypes(), header.getSchemaTypes())
&& Objects.equals(getSchemaNames(), header.getSchemaNames());
}
@Override
public int hashCode() {
return Objects.hash(getSchemaTypes(), getSchemaNames());
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("HeaderImpl{");
sb.append("schemaTypes=").append(schemaTypes);
sb.append(", schemaNames=").append(schemaNames);
sb.append('}');
return sb.toString();
}
}
private HeaderImpl parseHeader(Object data) {
if (data == null) {
return new HeaderImpl();
}
List<List<Object>> list = (List<List<Object>>) data;
List<ResultSet.ColumnType> types = new ArrayList<>(list.size());
List<String> texts = new ArrayList<>(list.size());
for (List<Object> tuple : list) {
types.add(COLUMN_TYPES[((Long) tuple.get(0)).intValue()]);
texts.add(SafeEncoder.encode((byte[]) tuple.get(1)));
}
return new HeaderImpl(types, texts);
}
private class StatisticsImpl implements Statistics {
private final Map<String, String> statistics;
private StatisticsImpl(Map<String, String> statistics) {
this.statistics = statistics;
}
/**
*
* @param label the requested statistic label as key
* @return a string with the value, if key exists, null otherwise
*/
public String getStringValue(String label) {
return statistics.get(label);
}
/**
*
* @param label the requested statistic label as key
* @return a string with the value, if key exists, 0 otherwise
*/
private int getIntValue(String label) {
String value = getStringValue(label);
return value == null ? 0 : Integer.parseInt(value);
}
/**
*
* @return number of nodes created after query execution
*/
@Override
public int nodesCreated() {
return getIntValue("Nodes created");
}
/**
*
* @return number of nodes deleted after query execution
*/
@Override
public int nodesDeleted() {
return getIntValue("Nodes deleted");
}
/**
*
* @return number of indices added after query execution
*/
@Override
public int indicesCreated() {
return getIntValue("Indices created");
}
@Override
public int indicesDeleted() {
return getIntValue("Indices deleted");
}
/**
*
* @return number of labels added after query execution
*/
@Override
public int labelsAdded() {
return getIntValue("Labels added");
}
/**
*
* @return number of relationship deleted after query execution
*/
@Override
public int relationshipsDeleted() {
return getIntValue("Relationships deleted");
}
/**
*
* @return number of relationship created after query execution
*/
@Override
public int relationshipsCreated() {
return getIntValue("Relationships created");
}
/**
*
* @return number of properties set after query execution
*/
@Override
public int propertiesSet() {
return getIntValue("Properties set");
}
/**
*
* @return The execution plan was cached on RedisGraph.
*/
@Override
public boolean cachedExecution() {
return "1".equals(getStringValue("Cached execution"));
}
@Override
public String queryIntervalExecutionTime() {
return getStringValue("Query internal execution time");
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof StatisticsImpl)) {
return false;
}
StatisticsImpl that = (StatisticsImpl) o;
return Objects.equals(statistics, that.statistics);
}
@Override
public int hashCode() {
return Objects.hash(statistics);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("Statistics{");
sb.append(statistics);
sb.append('}');
return sb.toString();
}
}
private StatisticsImpl parseStatistics(Object data) {
Map<String, String> map = ((List<byte[]>) data).stream()
.map(SafeEncoder::encode).map(s -> s.split(": "))
.collect(Collectors.toMap(sa -> sa[0], sa -> sa[1]));
return new StatisticsImpl(map);
}
}
|
119378_26 | package io.lettuce.core;
import io.lettuce.core.internal.LettuceAssert;
import io.lettuce.core.protocol.CommandArgs;
import io.lettuce.core.protocol.CommandKeyword;
import io.lettuce.core.protocol.ProtocolKeyword;
/**
*
* Argument list builder for the Redis <a href="https://redis.io/commands/georadius">GEORADIUS</a> and
* <a href="https://redis.io/commands/georadiusbymember">GEORADIUSBYMEMBER</a> commands.
* <p>
* {@link GeoArgs} is a mutable object and instances should be used only once to avoid shared mutable state.
*
* @author Mark Paluch
*/
public class GeoArgs implements CompositeArgument {
private boolean withdistance;
private boolean withcoordinates;
private boolean withhash;
private Long count;
private boolean any;
private Sort sort = Sort.none;
/**
* Builder entry points for {@link GeoArgs}.
*/
public static class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GeoArgs} with {@literal WITHDIST} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST} enabled.
* @see GeoArgs#withDistance()
*/
public static GeoArgs distance() {
return new GeoArgs().withDistance();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHCOORD} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHCOORD} enabled.
* @see GeoArgs#withCoordinates()
*/
public static GeoArgs coordinates() {
return new GeoArgs().withCoordinates();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHHASH} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHHASH} enabled.
* @see GeoArgs#withHash()
*/
public static GeoArgs hash() {
return new GeoArgs().withHash();
}
/**
* Creates new {@link GeoArgs} with distance, coordinates and hash enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST}, {@literal WITHCOORD}, {@literal WITHHASH} enabled.
* @see GeoArgs#withDistance()
* @see GeoArgs#withCoordinates()
* @see GeoArgs#withHash()
*/
public static GeoArgs full() {
return new GeoArgs().withDistance().withCoordinates().withHash();
}
/**
* Creates new {@link GeoArgs} with {@literal COUNT} set.
*
* @param count number greater 0.
* @return new {@link GeoArgs} with {@literal COUNT} set.
* @see GeoArgs#withCount(long)
*/
public static GeoArgs count(long count) {
return new GeoArgs().withCount(count);
}
}
/**
* Request distance for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withDistance() {
withdistance = true;
return this;
}
/**
* Request coordinates for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCoordinates() {
withcoordinates = true;
return this;
}
/**
* Request geohash for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withHash() {
withhash = true;
return this;
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCount(long count) {
return withCount(count, false);
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @param any whether to complete the command as soon as enough matches are found, so the results may not be the ones
* closest to the specified point.
* @return {@code this} {@link GeoArgs}.
* @since 6.1
*/
public GeoArgs withCount(long count, boolean any) {
LettuceAssert.isTrue(count > 0, "Count must be greater 0");
this.count = count;
this.any = any;
return this;
}
/**
*
* @return {@code true} if distance is requested.
*/
public boolean isWithDistance() {
return withdistance;
}
/**
*
* @return {@code true} if coordinates are requested.
*/
public boolean isWithCoordinates() {
return withcoordinates;
}
/**
*
* @return {@code true} if geohash is requested.
*/
public boolean isWithHash() {
return withhash;
}
/**
* Sort results ascending.
*
* @return {@code this}
*/
public GeoArgs asc() {
return sort(Sort.asc);
}
/**
* Sort results descending.
*
* @return {@code this}
*/
public GeoArgs desc() {
return sort(Sort.desc);
}
/**
* Sort results.
*
* @param sort sort order, must not be {@code null}
* @return {@code this}
*/
public GeoArgs sort(Sort sort) {
LettuceAssert.notNull(sort, "Sort must not be null");
this.sort = sort;
return this;
}
/**
* Sort order.
*/
public enum Sort {
/**
* ascending.
*/
asc,
/**
* descending.
*/
desc,
/**
* no sort order.
*/
none;
}
/**
* Supported geo unit.
*/
public enum Unit implements ProtocolKeyword {
/**
* meter.
*/
m,
/**
* kilometer.
*/
km,
/**
* feet.
*/
ft,
/**
* mile.
*/
mi;
private final byte[] asBytes;
Unit() {
asBytes = name().getBytes();
}
@Override
public byte[] getBytes() {
return asBytes;
}
}
public <K, V> void build(CommandArgs<K, V> args) {
if (withdistance) {
args.add("WITHDIST");
}
if (withhash) {
args.add("WITHHASH");
}
if (withcoordinates) {
args.add("WITHCOORD");
}
if (sort != null && sort != Sort.none) {
args.add(sort.name());
}
if (count != null) {
args.add(CommandKeyword.COUNT).add(count);
if (any) {
args.add("ANY");
}
}
}
}
| redis/lettuce | src/main/java/io/lettuce/core/GeoArgs.java | 1,900 | /**
* feet.
*/ | block_comment | nl | package io.lettuce.core;
import io.lettuce.core.internal.LettuceAssert;
import io.lettuce.core.protocol.CommandArgs;
import io.lettuce.core.protocol.CommandKeyword;
import io.lettuce.core.protocol.ProtocolKeyword;
/**
*
* Argument list builder for the Redis <a href="https://redis.io/commands/georadius">GEORADIUS</a> and
* <a href="https://redis.io/commands/georadiusbymember">GEORADIUSBYMEMBER</a> commands.
* <p>
* {@link GeoArgs} is a mutable object and instances should be used only once to avoid shared mutable state.
*
* @author Mark Paluch
*/
public class GeoArgs implements CompositeArgument {
private boolean withdistance;
private boolean withcoordinates;
private boolean withhash;
private Long count;
private boolean any;
private Sort sort = Sort.none;
/**
* Builder entry points for {@link GeoArgs}.
*/
public static class Builder {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link GeoArgs} with {@literal WITHDIST} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST} enabled.
* @see GeoArgs#withDistance()
*/
public static GeoArgs distance() {
return new GeoArgs().withDistance();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHCOORD} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHCOORD} enabled.
* @see GeoArgs#withCoordinates()
*/
public static GeoArgs coordinates() {
return new GeoArgs().withCoordinates();
}
/**
* Creates new {@link GeoArgs} with {@literal WITHHASH} enabled.
*
* @return new {@link GeoArgs} with {@literal WITHHASH} enabled.
* @see GeoArgs#withHash()
*/
public static GeoArgs hash() {
return new GeoArgs().withHash();
}
/**
* Creates new {@link GeoArgs} with distance, coordinates and hash enabled.
*
* @return new {@link GeoArgs} with {@literal WITHDIST}, {@literal WITHCOORD}, {@literal WITHHASH} enabled.
* @see GeoArgs#withDistance()
* @see GeoArgs#withCoordinates()
* @see GeoArgs#withHash()
*/
public static GeoArgs full() {
return new GeoArgs().withDistance().withCoordinates().withHash();
}
/**
* Creates new {@link GeoArgs} with {@literal COUNT} set.
*
* @param count number greater 0.
* @return new {@link GeoArgs} with {@literal COUNT} set.
* @see GeoArgs#withCount(long)
*/
public static GeoArgs count(long count) {
return new GeoArgs().withCount(count);
}
}
/**
* Request distance for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withDistance() {
withdistance = true;
return this;
}
/**
* Request coordinates for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCoordinates() {
withcoordinates = true;
return this;
}
/**
* Request geohash for results.
*
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withHash() {
withhash = true;
return this;
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @return {@code this} {@link GeoArgs}.
*/
public GeoArgs withCount(long count) {
return withCount(count, false);
}
/**
* Limit results to {@code count} entries.
*
* @param count number greater 0.
* @param any whether to complete the command as soon as enough matches are found, so the results may not be the ones
* closest to the specified point.
* @return {@code this} {@link GeoArgs}.
* @since 6.1
*/
public GeoArgs withCount(long count, boolean any) {
LettuceAssert.isTrue(count > 0, "Count must be greater 0");
this.count = count;
this.any = any;
return this;
}
/**
*
* @return {@code true} if distance is requested.
*/
public boolean isWithDistance() {
return withdistance;
}
/**
*
* @return {@code true} if coordinates are requested.
*/
public boolean isWithCoordinates() {
return withcoordinates;
}
/**
*
* @return {@code true} if geohash is requested.
*/
public boolean isWithHash() {
return withhash;
}
/**
* Sort results ascending.
*
* @return {@code this}
*/
public GeoArgs asc() {
return sort(Sort.asc);
}
/**
* Sort results descending.
*
* @return {@code this}
*/
public GeoArgs desc() {
return sort(Sort.desc);
}
/**
* Sort results.
*
* @param sort sort order, must not be {@code null}
* @return {@code this}
*/
public GeoArgs sort(Sort sort) {
LettuceAssert.notNull(sort, "Sort must not be null");
this.sort = sort;
return this;
}
/**
* Sort order.
*/
public enum Sort {
/**
* ascending.
*/
asc,
/**
* descending.
*/
desc,
/**
* no sort order.
*/
none;
}
/**
* Supported geo unit.
*/
public enum Unit implements ProtocolKeyword {
/**
* meter.
*/
m,
/**
* kilometer.
*/
km,
/**
* feet.
<SUF>*/
ft,
/**
* mile.
*/
mi;
private final byte[] asBytes;
Unit() {
asBytes = name().getBytes();
}
@Override
public byte[] getBytes() {
return asBytes;
}
}
public <K, V> void build(CommandArgs<K, V> args) {
if (withdistance) {
args.add("WITHDIST");
}
if (withhash) {
args.add("WITHHASH");
}
if (withcoordinates) {
args.add("WITHCOORD");
}
if (sort != null && sort != Sort.none) {
args.add(sort.name());
}
if (count != null) {
args.add(CommandKeyword.COUNT).add(count);
if (any) {
args.add("ANY");
}
}
}
}
|
192166_13 | /**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.api;
/**
* Distributed async implementation of {@link java.util.concurrent.atomic.AtomicLong}
*
* @author Nikita Koksharov
*
*/
public interface RAtomicLongAsync extends RExpirableAsync {
/**
* Atomically sets the value to the given updated value
* only if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful; or false if the actual value
* was not equal to the expected value.
*/
RFuture<Boolean> compareAndSetAsync(long expect, long update);
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
RFuture<Long> addAndGetAsync(long delta);
/**
* Atomically decrements the current value by one.
*
* @return the updated value
*/
RFuture<Long> decrementAndGetAsync();
/**
* Returns current value.
*
* @return the current value
*/
RFuture<Long> getAsync();
/**
* Returns and deletes object
*
* @return the current value
*/
RFuture<Long> getAndDeleteAsync();
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the old value before the add
*/
RFuture<Long> getAndAddAsync(long delta);
/**
* Atomically sets the given value and returns the old value.
*
* @param newValue the new value
* @return the old value
*/
RFuture<Long> getAndSetAsync(long newValue);
/**
* Atomically increments the current value by one.
*
* @return the updated value
*/
RFuture<Long> incrementAndGetAsync();
/**
* Atomically increments the current value by one.
*
* @return the old value
*/
RFuture<Long> getAndIncrementAsync();
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
RFuture<Long> getAndDecrementAsync();
/**
* Atomically sets the given value.
*
* @param newValue the new value
* @return void
*/
RFuture<Void> setAsync(long newValue);
/**
* Adds object event listener
*
* @see org.redisson.api.listener.IncrByListener
* @see org.redisson.api.ExpiredObjectListener
* @see org.redisson.api.DeletedObjectListener
*
* @param listener - object event listener
* @return listener id
*/
RFuture<Integer> addListenerAsync(ObjectListener listener);
}
| redisson/redisson | redisson/src/main/java/org/redisson/api/RAtomicLongAsync.java | 904 | /**
* Adds object event listener
*
* @see org.redisson.api.listener.IncrByListener
* @see org.redisson.api.ExpiredObjectListener
* @see org.redisson.api.DeletedObjectListener
*
* @param listener - object event listener
* @return listener id
*/ | block_comment | nl | /**
* Copyright (c) 2013-2024 Nikita Koksharov
*
* 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.redisson.api;
/**
* Distributed async implementation of {@link java.util.concurrent.atomic.AtomicLong}
*
* @author Nikita Koksharov
*
*/
public interface RAtomicLongAsync extends RExpirableAsync {
/**
* Atomically sets the value to the given updated value
* only if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful; or false if the actual value
* was not equal to the expected value.
*/
RFuture<Boolean> compareAndSetAsync(long expect, long update);
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
RFuture<Long> addAndGetAsync(long delta);
/**
* Atomically decrements the current value by one.
*
* @return the updated value
*/
RFuture<Long> decrementAndGetAsync();
/**
* Returns current value.
*
* @return the current value
*/
RFuture<Long> getAsync();
/**
* Returns and deletes object
*
* @return the current value
*/
RFuture<Long> getAndDeleteAsync();
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the old value before the add
*/
RFuture<Long> getAndAddAsync(long delta);
/**
* Atomically sets the given value and returns the old value.
*
* @param newValue the new value
* @return the old value
*/
RFuture<Long> getAndSetAsync(long newValue);
/**
* Atomically increments the current value by one.
*
* @return the updated value
*/
RFuture<Long> incrementAndGetAsync();
/**
* Atomically increments the current value by one.
*
* @return the old value
*/
RFuture<Long> getAndIncrementAsync();
/**
* Atomically decrements by one the current value.
*
* @return the previous value
*/
RFuture<Long> getAndDecrementAsync();
/**
* Atomically sets the given value.
*
* @param newValue the new value
* @return void
*/
RFuture<Void> setAsync(long newValue);
/**
* Adds object event<SUF>*/
RFuture<Integer> addListenerAsync(ObjectListener listener);
}
|
134393_13 | package domein;
import exceptions.SpelNaamInGebruikException;
import exceptions.SpelerBestaatNietException;
import exceptions.SpelersNaamInGebruikException;
import exceptions.UitdagingNietGevondenException;
import exceptions.VerplichtVeldException;
import exceptions.WachtwoordException;
import java.util.List;
import java.util.Scanner;
import talen.Taal;
/**
* begin van de klasse DomeinController
*
* @author reeve
*/
public class DomeinController {
private final MoeilijkheidsgraadRepository moeilijkheidsgraadRepository;
private Speler speler;
private final SpelerRepository spelerRepository;
private final SpelRepository spelRepository;
private final UitdagingRepository uitdagingRepo;
private Spel spel;
private Uitdaging uitdaging;
/**
* constructor van de DomeinController
*/
public DomeinController() {
spelerRepository = new SpelerRepository();
spelRepository = new SpelRepository();
moeilijkheidsgraadRepository = new MoeilijkheidsgraadRepository();
uitdagingRepo = new UitdagingRepository();
}
/**
* een methode die de gebruiker toelaat zich aan te melden, via een al
* bestaande naam met wachtwoord, als de speler zich probeert aan te melden
* met een niet bestaande naam in de DB wordt een exception geworpen
*
* @param spelersnaam
* @param wachtwoord
*/
public void meldAan(String spelersnaam, String wachtwoord) { //als de speler in spelerRepository zit en het wachtwoord overeenkomt kan hij zich aanmelden
if (spelerRepository.bestaatSpeler(spelersnaam) == false) {
throw new SpelerBestaatNietException("registreer");
} else {
Speler gevondenSpeler = spelerRepository.geefSpeler(spelersnaam, wachtwoord);
if (gevondenSpeler != null) {
setSpeler(gevondenSpeler);
} else {
throw new WachtwoordException(Taal.getString("passFalse"));
}
}
}
/**
*stelt de speler als een lege speler in
*/
public void logUit() {
setSpeler(new Speler());
}
/**
* een methode die de gebruiker toelaat zich te registreren met een nieuwe
* gebruikersnaam (spelersnaam) en wachtwoord, indien het de gebruikersnaam
* al in gebruik is wordt en het wachtwoord niet klopt met de wachtwoord
* eisen, wordt een exception geworpen
*
* @param spelersnaam
* @param wachtwoord
* @param bevestigingWachtwoord
*/
public void registreer(String spelersnaam, String wachtwoord, String bevestigingWachtwoord) {
if (spelerRepository.bestaatSpeler(spelersnaam) == true) {
throw new SpelersNaamInGebruikException("probeer opnieuw");
} else {
if (!wachtwoord.equals(bevestigingWachtwoord)) { //als het wachtwoord niet gelijk is aan het bevestigings wachtwoord dan wordt er een iae gegeven
throw new VerplichtVeldException("Wachtwoorden komen niet overeen.");
}
Speler nieuwSpeler = new Speler(spelersnaam, wachtwoord); //anders wordt de speler aangemaakt
spelerRepository.voegToe(nieuwSpeler);
setSpeler(nieuwSpeler);
}
}
/**
* geeft een de gebruikersnaam (spelersnaam) terug
*
* @return
*/
public String geefSpeler() {
return speler.getSpelersnaam();
}
/**
* geeft een lijst van Speler objecten terug
*
* @return
*/
public String geefSpelers() {
List<Speler> spelers = spelerRepository.geefSpelers();
int teller = 1;
String output = "";
for (Speler speler : spelers) {
output += String.format("%s %s", teller, speler);
teller++;
}
return output;
}
private void setSpeler(Speler speler) {
this.speler = speler;
}
/**
* geeft een overzicht terug
*
* @return
*/
public int[] geefOverzichtSpel() {
return speler.getGewonnenMoeilijkheidsgraden();
}
/**
* geeft de gebruiker de keuze om een spel te starten met 1 van de 3
* moeilijkheidsgraden, als de gebruiker een ongeldige moeilijkheidsgraad
* kiest wordt een exception geworpen
*
* @param keuze
*/
public void startSpel(int keuze) {
String naam = "";
if (keuze == 1 || keuze == 2 || keuze == 3) {
switch (keuze) {
case 1:
naam = "gemakkelijk";
break;
case 2:
naam = "normaal";
break;
default:
naam = "moeilijk";
break;
}
Moeilijkheidsgraad graad;
graad = moeilijkheidsgraadRepository.geefOpNaam(naam);
setSpel(new Spel(speler, graad));
} else {
throw new VerplichtVeldException("moeilijkheidsgraad ongeldig");
}
}
private void setSpel(Spel spel) {
this.spel = spel;
}
/**
* geeft een spelbord terug
*
* @return
*/
public String geefSpelbord() {
Spelbord spelbord = spel.getSpelbord();
int[][] guess = spelbord.getBord();
String bord;
bord = String.format("%16s%50s%n", Taal.getString("positions"), Taal.getString("controlpin"));
for (int[] gues : guess) {
for (int col = 0; col < gues.length; col++) {
String s = String.format(Taal.getString(Integer.toString(gues[col]) + Integer.toString(gues[col])));
bord += String.format("%s ", s);
}
bord += String.format("%n");
}
bord += String.format(getTeRadenCode());
return bord;
}
/**
* geeft de te raden code terug
*
* @return
*/
public String getTeRadenCode() {
int[] code = spel.getTeRadenCode();
String teRadenCode = "";
for (int deCode : code) {
teRadenCode += String.format("%s", Taal.getString(Integer.toString(deCode)) + " "); //String.valueOf
}
return String.format("%s %s%n", Taal.getString("codetoguess"), teRadenCode);
}
/**
* geeft een lijst van codepinnen terug
*
* @return
*/
public List<Integer> geefCodePinnen() {
return spel.geefCodePinnen();
}
/**
* geeft de pogingen terug
*
* @return
*/
public int[][] geefPoging() {
return spel.geefPoging();
}
/**
*geeft tegenspelers als een array van Speler objecten
* @param gekozenMG
* @return
*/
public String[] geefTegenspelersArray(String gekozenMG) {
Speler[] tegenspelers = spelerRepository.geefTegenspelersVoor(gekozenMG);
String[] uit = new String[tegenspelers.length];
for (int i = 0; i < uit.length; i++) {
uit[i] = tegenspelers[i].getSpelersnaam();
}
return uit;
}
/**
* geeft een lijst van mogelijke tegenspelers weer
*
* @param gekozenMG
* @return
*/
public String geefTegenspelers(int gekozenMG) {
Scanner s = new Scanner(System.in);
System.out.printf("%s%n", Taal.getString("qChoosePlayerToChallange"));
Speler[] tegenspelers = spelerRepository.geefTegenspelersVoor(decodeerMoeilijkheidsgraad(gekozenMG));
if (tegenspelers.length <= 0) {
throw new IllegalArgumentException("geen speler gevonden voor die moeilijkheidsgraad");
}
String lijstSpelers = String.format("%15s %15s%n", Taal.getString("player"), Taal.getString("LT"));
for (Speler tegenspeler : tegenspelers) {
lijstSpelers += String.format("%15s %15d%n", tegenspeler.getSpelersnaam(), tegenspeler.geefAantalKeerGewonnenPerMoeilijkheidsgraad((gekozenMG - 1)));
}
System.out.print(lijstSpelers);
boolean gevonden = false;
String gekozenSpeler = s.next();
for (Speler eenSpeler : tegenspelers) {
if (gekozenSpeler.equals(eenSpeler.getSpelersnaam())) {
gevonden = true;
break;
}
}
while (!gevonden) {
System.out.printf("%s%n", Taal.getString("nameUsed"));
gekozenSpeler = s.next();
for (Speler eenSpeler : tegenspelers) {
if (gekozenSpeler.equals(eenSpeler.getSpelersnaam())) {
gevonden = true;
break;
}
}
}
return gekozenSpeler;
}
/**
* decodeert de moeilijkheidsgraad
*
* @param moeilijkheidsgraad
* @return
*/
public String decodeerMoeilijkheidsgraad(int moeilijkheidsgraad) {
String mg;
switch (moeilijkheidsgraad) {
case 1:
mg = "gemakkelijk";
break;
case 2:
mg = "normaal";
break;
default:
mg = "moeilijk";
break;
}
return mg;
}
/**
* valideert en registreert een poging
*
* @param poging
*/
public void speelWedstrijd(int[] poging) {
spel.valideerPoging(poging);
spel.registreerPoging(poging);
}
/**
* geeft het aantal sterren terug
*
* @return
*/
public String geefAantalSterren() {
int graad = this.geefGraad(spel.getMoeilijkheidsgraad());
int[] sterren = speler.geefAantalSterren();
String resul = String.format("%s %15s%n", Taal.getString("L"), Taal.getString("stars"));
String[] graden
= {
Taal.getString("L1"), Taal.getString("L2"), Taal.getString("L3")
};
resul += String.format("%s %20d%n", graden[graad], sterren[graad]);
return resul;
}
/**
* geeft het aantal keer winnen per moeilijkheidsgraad tot volgende ster
* terug
*
* @return
*/
public String geefVerschil() {
int graad = this.geefGraad(spel.getMoeilijkheidsgraad());
return speler.geefSterVerschil(graad);
}
/**
* geeft terug of het einde van het spel al dan niet bereikt is
*
* @return
*/
public boolean isEindeSpel() {
return spel.isEindeSpel();
}
/**
* geeft terug of de gebruiker gewonnen heeft of niet
*
* @return
*/
public boolean isGewonnen() {
return spel.isGewonnen();
}
/**
* registreert/verhoogt de winst per moeilijkheidsgraad
*/
public void registreerWinst() {
speler.verhoogMoeilijkheidsgraadMetEen(spel.getMoeilijkheidsgraad());
spelerRepository.slaWinstOp(speler);
}
/**
* checkt of een spel in de databank kan opgeslagen worden, indien dit
* mogelijk is voegt de methode dit spel toe, als de spelersnaam al in
* gebruik is wordt een exception geworpen
*
* @param naam
* @param bord
* @throws exceptions.SpelNaamInGebruikException
*/
public void registreerSpel(String naam, int bord[][]) throws SpelNaamInGebruikException, VerplichtVeldException {
if (naam.trim() == null && naam.trim().equals("")) {
throw new VerplichtVeldException("nameUsed");
} else {
if (spelRepository.bestaatNaam(naam, speler.getSpelersnaam()) == false) {
spel.setNaam(naam);
spelRepository.voegToe(spel, bord);
} else {
throw new SpelNaamInGebruikException("spelnaam in gebruik");
}
}
}
/**
* geeft het aantal pogingen terug
*
* @return
*/
public String getAantalPogingen() {
return String.format("%s %d", Taal.getString("NOG"), spel.geefAantalPogingen());
}
/**
* geeft een bord terug
*
* @return
*/
public int[][] getBord() {
return spel.getBord();
}
/**
* geeft een Speler object terug van de Speler die momenteel aan het spelen
* is
*
* @param naam
* @return
*/
public Speler geefSpeler(String naam) {
return spelerRepository.geefSpelerOpNaam(naam);
}
/**
* geeft de moeilijkheidsgraad terug
*
* @param mg
* @return
*/
public int geefGraad(Moeilijkheidsgraad mg) {
int graad;
switch (mg.getNaam()) {
case "gemakkelijk":
graad = 0;
break;
case "normaal":
graad = 1;
break;
default:
graad = 2;
break;
}
return graad;
}
/**
* set het gevraagde spel om verder te spelen
*
* @param naam
*/
public void laadSpel(String naam) {
Spel hetSpel = spelRepository.geefSpel(naam);
setSpel(hetSpel);
}
/**
* geeft een overzicht van het aantal gespeelde spelletjes weer
*
* @return
*/
public List<String> geefOverzichtSpelletjes() {
return spelRepository.geefOverzichtSpelletjes(geefSpeler());
}
/**
* checkt of de/een naam al bestaat
*
* @param naam
* @return
*/
public boolean bestaatNaam(String naam) {
return spelRepository.bestaatNaam(naam, speler.getSpelersnaam());
}
/**
* verwijdert een gespeeld spel
*/
public void verwijderSpel() {
spelRepository.verwijderSpel(speler.getSpelersnaam(), spel.getNaam());
}
/**
* start een uitdaging met een bepaalde moeilijkheidsgraad en tegenspeler
*
* @param mg
* @param tegenspeler
*/
public void startUitdaging(int mg, String tegenspeler) {
setUitdaging(
new Uitdaging(
speler,
spelerRepository.geefSpelerOpNaam(tegenspeler),
moeilijkheidsgraadRepository.geefOpNaam(decodeerMoeilijkheidsgraad(mg)))
);
}
/**
* @param aantalPogingen
*/
public final void setAantalPogingen(int aantalPogingen) {
spel.setAantalPogingen(aantalPogingen);
}
private void setUitdaging(Uitdaging uitdaging) {
this.uitdaging = uitdaging;
}
/**
* start de uitdaging als een spel
*/
public void startUitdagingAlspel() {
this.spel = new Spel(speler, this.uitdaging.getMoeilijkheidsgraad(), this.uitdaging.getCode(), this.uitdaging.getId());
}
/**
* geeft een overzicht weer aan het einde van een spel
*
* @return
*/
public String geefEindOverzicht() {
String result = "";
result += String.format("%s%n", getTeRadenCode());
result += String.format("%s%n", getAantalPogingen());
result += String.format("%s%n", geefAantalSterren());
result += String.format("%s%n", geefVerschil());
return result;
}
/**
*voegt een uitdaging toe aan de repository
*/
public void registreerUitdaging() {
uitdagingRepo.voegUitdagingToe(uitdaging);
}
/**
*update de score in de database
*/
public void updateScore() {
// int getal= spel.getUitdagingnr();
// int getal2= uitdaging.getId();
// if(getal==getal2){
uitdagingRepo.updateScore(spel.getUitdagingnr(), spel.geefAantalPogingen(), speler); //}
}
/**
* stelt de uitdaging in via zijn ID
*/
public void stelUitdagingIdIn() {
int nummer = uitdagingRepo.geefLaatsteNummerUitdaging(speler);
uitdaging.setId(nummer);
}
/**
* haalt een uitdaging op uit de DB via het ID en de naam van de speler
* @param id
* @throws UitdagingNietGevondenException
*/
public void stelUitdagingInVanID(int id) throws UitdagingNietGevondenException {
uitdaging = uitdagingRepo.geefUitdagingOpNaamTegenSpelerEnID(speler.getSpelersnaam(), id);
}
/**
* geeft alle uitdagingen terug die nog niet geaccepteerd zijn
* @return
* @throws UitdagingNietGevondenException
*/
public String geefUitdagingenTeAccepteren() throws UitdagingNietGevondenException {
Uitdaging[] uitdagingen = uitdagingRepo.geefUitdagingenTeAccepteren(speler.getSpelersnaam());
String uit = "";
if (uitdagingen.length <= 0) {
throw new UitdagingNietGevondenException();
}
// String uit = String.format("%4s%15s%20s%10s%n", Taal.getString("id"), Taal.getString("tegenspeler"), Taal.getString("L"), Taal.getString("LT"));
for (Uitdaging dezeuitdaging : uitdagingen) {
uit += String.format("%d%15s%20s%10s%n", dezeuitdaging.getId(), dezeuitdaging.getSpeler().getSpelersnaam(), dezeuitdaging.getMoeilijkheidsgraad().getNaam(), geefGraad(dezeuitdaging.getMoeilijkheidsgraad()));
}
return uit;
}
/**
* haalt de de klassementen op en maakt ze klaar om geprint te worden
* @return
*/
public String toonKlassement() {
String uit = "";
uit += String.format("%s:%n", Taal.getString("gemakkelijk")) + maakKlassementVoorMG("gemakkelijk") + String.format("%n");
uit += String.format("%s:%n", Taal.getString("normaal")) + maakKlassementVoorMG("normaal") + String.format("%n");
uit += String.format("%s:%n", Taal.getString("moeilijk")) + maakKlassementVoorMG("moeilijk") + String.format("%n");
return uit;
}
private String maakKlassementVoorMG(String mg) {
String[][] klassement = uitdagingRepo.toonKlassementVoorMG(mg);
if (klassement[0].length <= 0) {
return String.format("%s%n", Taal.getString("nogGeenKlassementVoorMG"));
}
String uit = "";
uit += String.format("%20s%20s%n", Taal.getString("speler"), Taal.getString("score"));
for (int i = klassement[0].length - 1; i >= 0; i--) {
uit += String.format("%20s%20s%n", klassement[0][i], klassement[1][i]);
}
return uit;
}
/**
* geeft een klassement terug per mg als array van strings
* @param mg
* @return
*/
public String[] geefKlassementStringArray(String mg) {
String[][] klassement = uitdagingRepo.toonKlassementVoorMG(mg);
String[] uit = new String[klassement[0].length];
for (int i = 0; i < uit.length; i++) {
uit[i] = String.format("%s%n%s", klassement[0][i], klassement[1][i]);
}
return uit;
}
}//einde klasse domeincontroller
| reeveng/Master-mind-2017 | NetbeansProject/NetbeansProject[[G15]14052018]/src/domein/DomeinController.java | 6,083 | /**
* geeft de te raden code terug
*
* @return
*/ | block_comment | nl | package domein;
import exceptions.SpelNaamInGebruikException;
import exceptions.SpelerBestaatNietException;
import exceptions.SpelersNaamInGebruikException;
import exceptions.UitdagingNietGevondenException;
import exceptions.VerplichtVeldException;
import exceptions.WachtwoordException;
import java.util.List;
import java.util.Scanner;
import talen.Taal;
/**
* begin van de klasse DomeinController
*
* @author reeve
*/
public class DomeinController {
private final MoeilijkheidsgraadRepository moeilijkheidsgraadRepository;
private Speler speler;
private final SpelerRepository spelerRepository;
private final SpelRepository spelRepository;
private final UitdagingRepository uitdagingRepo;
private Spel spel;
private Uitdaging uitdaging;
/**
* constructor van de DomeinController
*/
public DomeinController() {
spelerRepository = new SpelerRepository();
spelRepository = new SpelRepository();
moeilijkheidsgraadRepository = new MoeilijkheidsgraadRepository();
uitdagingRepo = new UitdagingRepository();
}
/**
* een methode die de gebruiker toelaat zich aan te melden, via een al
* bestaande naam met wachtwoord, als de speler zich probeert aan te melden
* met een niet bestaande naam in de DB wordt een exception geworpen
*
* @param spelersnaam
* @param wachtwoord
*/
public void meldAan(String spelersnaam, String wachtwoord) { //als de speler in spelerRepository zit en het wachtwoord overeenkomt kan hij zich aanmelden
if (spelerRepository.bestaatSpeler(spelersnaam) == false) {
throw new SpelerBestaatNietException("registreer");
} else {
Speler gevondenSpeler = spelerRepository.geefSpeler(spelersnaam, wachtwoord);
if (gevondenSpeler != null) {
setSpeler(gevondenSpeler);
} else {
throw new WachtwoordException(Taal.getString("passFalse"));
}
}
}
/**
*stelt de speler als een lege speler in
*/
public void logUit() {
setSpeler(new Speler());
}
/**
* een methode die de gebruiker toelaat zich te registreren met een nieuwe
* gebruikersnaam (spelersnaam) en wachtwoord, indien het de gebruikersnaam
* al in gebruik is wordt en het wachtwoord niet klopt met de wachtwoord
* eisen, wordt een exception geworpen
*
* @param spelersnaam
* @param wachtwoord
* @param bevestigingWachtwoord
*/
public void registreer(String spelersnaam, String wachtwoord, String bevestigingWachtwoord) {
if (spelerRepository.bestaatSpeler(spelersnaam) == true) {
throw new SpelersNaamInGebruikException("probeer opnieuw");
} else {
if (!wachtwoord.equals(bevestigingWachtwoord)) { //als het wachtwoord niet gelijk is aan het bevestigings wachtwoord dan wordt er een iae gegeven
throw new VerplichtVeldException("Wachtwoorden komen niet overeen.");
}
Speler nieuwSpeler = new Speler(spelersnaam, wachtwoord); //anders wordt de speler aangemaakt
spelerRepository.voegToe(nieuwSpeler);
setSpeler(nieuwSpeler);
}
}
/**
* geeft een de gebruikersnaam (spelersnaam) terug
*
* @return
*/
public String geefSpeler() {
return speler.getSpelersnaam();
}
/**
* geeft een lijst van Speler objecten terug
*
* @return
*/
public String geefSpelers() {
List<Speler> spelers = spelerRepository.geefSpelers();
int teller = 1;
String output = "";
for (Speler speler : spelers) {
output += String.format("%s %s", teller, speler);
teller++;
}
return output;
}
private void setSpeler(Speler speler) {
this.speler = speler;
}
/**
* geeft een overzicht terug
*
* @return
*/
public int[] geefOverzichtSpel() {
return speler.getGewonnenMoeilijkheidsgraden();
}
/**
* geeft de gebruiker de keuze om een spel te starten met 1 van de 3
* moeilijkheidsgraden, als de gebruiker een ongeldige moeilijkheidsgraad
* kiest wordt een exception geworpen
*
* @param keuze
*/
public void startSpel(int keuze) {
String naam = "";
if (keuze == 1 || keuze == 2 || keuze == 3) {
switch (keuze) {
case 1:
naam = "gemakkelijk";
break;
case 2:
naam = "normaal";
break;
default:
naam = "moeilijk";
break;
}
Moeilijkheidsgraad graad;
graad = moeilijkheidsgraadRepository.geefOpNaam(naam);
setSpel(new Spel(speler, graad));
} else {
throw new VerplichtVeldException("moeilijkheidsgraad ongeldig");
}
}
private void setSpel(Spel spel) {
this.spel = spel;
}
/**
* geeft een spelbord terug
*
* @return
*/
public String geefSpelbord() {
Spelbord spelbord = spel.getSpelbord();
int[][] guess = spelbord.getBord();
String bord;
bord = String.format("%16s%50s%n", Taal.getString("positions"), Taal.getString("controlpin"));
for (int[] gues : guess) {
for (int col = 0; col < gues.length; col++) {
String s = String.format(Taal.getString(Integer.toString(gues[col]) + Integer.toString(gues[col])));
bord += String.format("%s ", s);
}
bord += String.format("%n");
}
bord += String.format(getTeRadenCode());
return bord;
}
/**
* geeft de te<SUF>*/
public String getTeRadenCode() {
int[] code = spel.getTeRadenCode();
String teRadenCode = "";
for (int deCode : code) {
teRadenCode += String.format("%s", Taal.getString(Integer.toString(deCode)) + " "); //String.valueOf
}
return String.format("%s %s%n", Taal.getString("codetoguess"), teRadenCode);
}
/**
* geeft een lijst van codepinnen terug
*
* @return
*/
public List<Integer> geefCodePinnen() {
return spel.geefCodePinnen();
}
/**
* geeft de pogingen terug
*
* @return
*/
public int[][] geefPoging() {
return spel.geefPoging();
}
/**
*geeft tegenspelers als een array van Speler objecten
* @param gekozenMG
* @return
*/
public String[] geefTegenspelersArray(String gekozenMG) {
Speler[] tegenspelers = spelerRepository.geefTegenspelersVoor(gekozenMG);
String[] uit = new String[tegenspelers.length];
for (int i = 0; i < uit.length; i++) {
uit[i] = tegenspelers[i].getSpelersnaam();
}
return uit;
}
/**
* geeft een lijst van mogelijke tegenspelers weer
*
* @param gekozenMG
* @return
*/
public String geefTegenspelers(int gekozenMG) {
Scanner s = new Scanner(System.in);
System.out.printf("%s%n", Taal.getString("qChoosePlayerToChallange"));
Speler[] tegenspelers = spelerRepository.geefTegenspelersVoor(decodeerMoeilijkheidsgraad(gekozenMG));
if (tegenspelers.length <= 0) {
throw new IllegalArgumentException("geen speler gevonden voor die moeilijkheidsgraad");
}
String lijstSpelers = String.format("%15s %15s%n", Taal.getString("player"), Taal.getString("LT"));
for (Speler tegenspeler : tegenspelers) {
lijstSpelers += String.format("%15s %15d%n", tegenspeler.getSpelersnaam(), tegenspeler.geefAantalKeerGewonnenPerMoeilijkheidsgraad((gekozenMG - 1)));
}
System.out.print(lijstSpelers);
boolean gevonden = false;
String gekozenSpeler = s.next();
for (Speler eenSpeler : tegenspelers) {
if (gekozenSpeler.equals(eenSpeler.getSpelersnaam())) {
gevonden = true;
break;
}
}
while (!gevonden) {
System.out.printf("%s%n", Taal.getString("nameUsed"));
gekozenSpeler = s.next();
for (Speler eenSpeler : tegenspelers) {
if (gekozenSpeler.equals(eenSpeler.getSpelersnaam())) {
gevonden = true;
break;
}
}
}
return gekozenSpeler;
}
/**
* decodeert de moeilijkheidsgraad
*
* @param moeilijkheidsgraad
* @return
*/
public String decodeerMoeilijkheidsgraad(int moeilijkheidsgraad) {
String mg;
switch (moeilijkheidsgraad) {
case 1:
mg = "gemakkelijk";
break;
case 2:
mg = "normaal";
break;
default:
mg = "moeilijk";
break;
}
return mg;
}
/**
* valideert en registreert een poging
*
* @param poging
*/
public void speelWedstrijd(int[] poging) {
spel.valideerPoging(poging);
spel.registreerPoging(poging);
}
/**
* geeft het aantal sterren terug
*
* @return
*/
public String geefAantalSterren() {
int graad = this.geefGraad(spel.getMoeilijkheidsgraad());
int[] sterren = speler.geefAantalSterren();
String resul = String.format("%s %15s%n", Taal.getString("L"), Taal.getString("stars"));
String[] graden
= {
Taal.getString("L1"), Taal.getString("L2"), Taal.getString("L3")
};
resul += String.format("%s %20d%n", graden[graad], sterren[graad]);
return resul;
}
/**
* geeft het aantal keer winnen per moeilijkheidsgraad tot volgende ster
* terug
*
* @return
*/
public String geefVerschil() {
int graad = this.geefGraad(spel.getMoeilijkheidsgraad());
return speler.geefSterVerschil(graad);
}
/**
* geeft terug of het einde van het spel al dan niet bereikt is
*
* @return
*/
public boolean isEindeSpel() {
return spel.isEindeSpel();
}
/**
* geeft terug of de gebruiker gewonnen heeft of niet
*
* @return
*/
public boolean isGewonnen() {
return spel.isGewonnen();
}
/**
* registreert/verhoogt de winst per moeilijkheidsgraad
*/
public void registreerWinst() {
speler.verhoogMoeilijkheidsgraadMetEen(spel.getMoeilijkheidsgraad());
spelerRepository.slaWinstOp(speler);
}
/**
* checkt of een spel in de databank kan opgeslagen worden, indien dit
* mogelijk is voegt de methode dit spel toe, als de spelersnaam al in
* gebruik is wordt een exception geworpen
*
* @param naam
* @param bord
* @throws exceptions.SpelNaamInGebruikException
*/
public void registreerSpel(String naam, int bord[][]) throws SpelNaamInGebruikException, VerplichtVeldException {
if (naam.trim() == null && naam.trim().equals("")) {
throw new VerplichtVeldException("nameUsed");
} else {
if (spelRepository.bestaatNaam(naam, speler.getSpelersnaam()) == false) {
spel.setNaam(naam);
spelRepository.voegToe(spel, bord);
} else {
throw new SpelNaamInGebruikException("spelnaam in gebruik");
}
}
}
/**
* geeft het aantal pogingen terug
*
* @return
*/
public String getAantalPogingen() {
return String.format("%s %d", Taal.getString("NOG"), spel.geefAantalPogingen());
}
/**
* geeft een bord terug
*
* @return
*/
public int[][] getBord() {
return spel.getBord();
}
/**
* geeft een Speler object terug van de Speler die momenteel aan het spelen
* is
*
* @param naam
* @return
*/
public Speler geefSpeler(String naam) {
return spelerRepository.geefSpelerOpNaam(naam);
}
/**
* geeft de moeilijkheidsgraad terug
*
* @param mg
* @return
*/
public int geefGraad(Moeilijkheidsgraad mg) {
int graad;
switch (mg.getNaam()) {
case "gemakkelijk":
graad = 0;
break;
case "normaal":
graad = 1;
break;
default:
graad = 2;
break;
}
return graad;
}
/**
* set het gevraagde spel om verder te spelen
*
* @param naam
*/
public void laadSpel(String naam) {
Spel hetSpel = spelRepository.geefSpel(naam);
setSpel(hetSpel);
}
/**
* geeft een overzicht van het aantal gespeelde spelletjes weer
*
* @return
*/
public List<String> geefOverzichtSpelletjes() {
return spelRepository.geefOverzichtSpelletjes(geefSpeler());
}
/**
* checkt of de/een naam al bestaat
*
* @param naam
* @return
*/
public boolean bestaatNaam(String naam) {
return spelRepository.bestaatNaam(naam, speler.getSpelersnaam());
}
/**
* verwijdert een gespeeld spel
*/
public void verwijderSpel() {
spelRepository.verwijderSpel(speler.getSpelersnaam(), spel.getNaam());
}
/**
* start een uitdaging met een bepaalde moeilijkheidsgraad en tegenspeler
*
* @param mg
* @param tegenspeler
*/
public void startUitdaging(int mg, String tegenspeler) {
setUitdaging(
new Uitdaging(
speler,
spelerRepository.geefSpelerOpNaam(tegenspeler),
moeilijkheidsgraadRepository.geefOpNaam(decodeerMoeilijkheidsgraad(mg)))
);
}
/**
* @param aantalPogingen
*/
public final void setAantalPogingen(int aantalPogingen) {
spel.setAantalPogingen(aantalPogingen);
}
private void setUitdaging(Uitdaging uitdaging) {
this.uitdaging = uitdaging;
}
/**
* start de uitdaging als een spel
*/
public void startUitdagingAlspel() {
this.spel = new Spel(speler, this.uitdaging.getMoeilijkheidsgraad(), this.uitdaging.getCode(), this.uitdaging.getId());
}
/**
* geeft een overzicht weer aan het einde van een spel
*
* @return
*/
public String geefEindOverzicht() {
String result = "";
result += String.format("%s%n", getTeRadenCode());
result += String.format("%s%n", getAantalPogingen());
result += String.format("%s%n", geefAantalSterren());
result += String.format("%s%n", geefVerschil());
return result;
}
/**
*voegt een uitdaging toe aan de repository
*/
public void registreerUitdaging() {
uitdagingRepo.voegUitdagingToe(uitdaging);
}
/**
*update de score in de database
*/
public void updateScore() {
// int getal= spel.getUitdagingnr();
// int getal2= uitdaging.getId();
// if(getal==getal2){
uitdagingRepo.updateScore(spel.getUitdagingnr(), spel.geefAantalPogingen(), speler); //}
}
/**
* stelt de uitdaging in via zijn ID
*/
public void stelUitdagingIdIn() {
int nummer = uitdagingRepo.geefLaatsteNummerUitdaging(speler);
uitdaging.setId(nummer);
}
/**
* haalt een uitdaging op uit de DB via het ID en de naam van de speler
* @param id
* @throws UitdagingNietGevondenException
*/
public void stelUitdagingInVanID(int id) throws UitdagingNietGevondenException {
uitdaging = uitdagingRepo.geefUitdagingOpNaamTegenSpelerEnID(speler.getSpelersnaam(), id);
}
/**
* geeft alle uitdagingen terug die nog niet geaccepteerd zijn
* @return
* @throws UitdagingNietGevondenException
*/
public String geefUitdagingenTeAccepteren() throws UitdagingNietGevondenException {
Uitdaging[] uitdagingen = uitdagingRepo.geefUitdagingenTeAccepteren(speler.getSpelersnaam());
String uit = "";
if (uitdagingen.length <= 0) {
throw new UitdagingNietGevondenException();
}
// String uit = String.format("%4s%15s%20s%10s%n", Taal.getString("id"), Taal.getString("tegenspeler"), Taal.getString("L"), Taal.getString("LT"));
for (Uitdaging dezeuitdaging : uitdagingen) {
uit += String.format("%d%15s%20s%10s%n", dezeuitdaging.getId(), dezeuitdaging.getSpeler().getSpelersnaam(), dezeuitdaging.getMoeilijkheidsgraad().getNaam(), geefGraad(dezeuitdaging.getMoeilijkheidsgraad()));
}
return uit;
}
/**
* haalt de de klassementen op en maakt ze klaar om geprint te worden
* @return
*/
public String toonKlassement() {
String uit = "";
uit += String.format("%s:%n", Taal.getString("gemakkelijk")) + maakKlassementVoorMG("gemakkelijk") + String.format("%n");
uit += String.format("%s:%n", Taal.getString("normaal")) + maakKlassementVoorMG("normaal") + String.format("%n");
uit += String.format("%s:%n", Taal.getString("moeilijk")) + maakKlassementVoorMG("moeilijk") + String.format("%n");
return uit;
}
private String maakKlassementVoorMG(String mg) {
String[][] klassement = uitdagingRepo.toonKlassementVoorMG(mg);
if (klassement[0].length <= 0) {
return String.format("%s%n", Taal.getString("nogGeenKlassementVoorMG"));
}
String uit = "";
uit += String.format("%20s%20s%n", Taal.getString("speler"), Taal.getString("score"));
for (int i = klassement[0].length - 1; i >= 0; i--) {
uit += String.format("%20s%20s%n", klassement[0][i], klassement[1][i]);
}
return uit;
}
/**
* geeft een klassement terug per mg als array van strings
* @param mg
* @return
*/
public String[] geefKlassementStringArray(String mg) {
String[][] klassement = uitdagingRepo.toonKlassementVoorMG(mg);
String[] uit = new String[klassement[0].length];
for (int i = 0; i < uit.length; i++) {
uit[i] = String.format("%s%n%s", klassement[0][i], klassement[1][i]);
}
return uit;
}
}//einde klasse domeincontroller
|
179426_10 | package nl.ou.debm.common.feature2;
import nl.ou.debm.assessor.ETestCategories;
import nl.ou.debm.common.CompilerConfig;
import nl.ou.debm.common.EArchitecture;
import nl.ou.debm.common.ECompiler;
import nl.ou.debm.common.EOptimize;
import nl.ou.debm.common.antlr.CBaseVisitor;
import nl.ou.debm.common.antlr.CLexer;
import nl.ou.debm.common.antlr.CParser;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.misc.Utils;
import org.antlr.v4.runtime.tree.Tree;
import org.antlr.v4.runtime.tree.Trees;
import nl.ou.debm.common.BaseCodeMarker;
import nl.ou.debm.common.CodeMarker;
import nl.ou.debm.common.task.ProcessTask;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// This is a program used to test things during development. todo: convert some things to unit tests
public class TestMain {
// source: https://stackoverflow.com/a/50068645
public static class TreeUtils {
/** Platform dependent end-of-line marker */
public static final String Eol = System.lineSeparator();
/** The literal indent char(s) used for pretty-printing */
public static final String Indents = " ";
private static int level;
private TreeUtils() {}
public static String toPrettyTree(final Tree t, final List<String> ruleNames) {
level = 0;
return process(t, ruleNames).replaceAll("(?m)^\\s+$", "").replaceAll("\\r?\\n\\r?\\n", Eol);
}
private static String process(final Tree t, final List<String> ruleNames) {
if (t.getChildCount() == 0) return Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);
StringBuilder sb = new StringBuilder();
sb.append(lead(level));
level++;
String s = Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);
sb.append(s + ' ');
for (int i = 0; i < t.getChildCount(); i++) {
sb.append(process(t.getChild(i), ruleNames));
}
level--;
sb.append(lead(level));
return sb.toString();
}
private static String lead(int level) {
StringBuilder sb = new StringBuilder();
if (level > 0) {
sb.append(Eol);
for (int cnt = 0; cnt < level; cnt++) {
sb.append(Indents);
}
}
return sb.toString();
}
}
// contains the rulenames for C
public static class CTreeShower {
public static List<String> ruleNamesList;
public CTreeShower() {
var lexer = new CLexer(CharStreams.fromString(""));
var parser = new CParser(new CommonTokenStream(lexer));
ruleNamesList = Arrays.asList(parser.getRuleNames());
}
public String show(ParseTree tree) {
return TreeUtils.toPrettyTree(tree, ruleNamesList);
}
}
public static String cm(String varname) {
return new DataStructureCodeMarker(varname).toCode();
}
public static String mini_CGenerator()
{
var sb = new StringBuilder();
// wat voor soorten typereferenties zijn er in C:
// - ingebouwd:
// int, float, unsigned enz.
// - typedefnamen:
// alle mogelijke identifiers
// - struct zonder naam:
// struct {int i;}
// - struct met naam:
// struct Naam {int i;}
// - referentie naar een eerder benoemd struct:
// struct Naam
//helps to make this test code compileable
sb.append("""
void DataStructureCodeMarker(char*, void*){};
int main() { return 0; }
""");
sb.append("""
struct {
int i;
} varname;
struct S {
int i;
};
typedef struct {
int i;
} S2;
struct S2 {
struct localname {
int i;
};
struct localname l;
int i;
};
typedef int* int_ptr;
typedef int int_no_ptr;
typedef struct{int i;}* struct_ptr;
typedef struct{int i;} struct_no_ptr;
typedef some_name* some_name_ptr;
typedef some_name some_name_no_ptr;
""");
sb.append("""
void blockscope_test() {
int i = 10;
%s
{
unsigned i;
%s
}
%s
}
""".formatted(
cm("i"),
cm("i"),
cm("i")
));
sb.append("""
void struct_type_test() {
{
struct S s;
%s
} {
struct Named {
int i;
} s;
%s
} {
struct {
int i;
} s;
%s
}
}
""".formatted(
cm("s"),
cm("s"),
cm("s")
));
return sb.toString();
}
public static void main(String[] args) throws Exception
{
var treeShower = new CTreeShower();
//test the C visitor on testcode:
if(false)
{
String code = mini_CGenerator();
System.out.println("mini_CGenerator code:\n" + code);
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(parser.compilationUnit());
System.out.println("found testcases: ");
for (var t : visitor.recovered_testcases) {
System.out.println("codemarker: " + t.codemarker);
System.out.println("status: " + t.status);
if (t.varInfo != null) {
System.out.println(t.varInfo);
}
else {
System.out.println("no variable info because status is not ok");
}
System.out.println("");
}
}
//test behavior of getIdentifiers (todo turn these kinds of tests into unit tests)
// getIdentifiers uses (java) reflection as a workaround for the fact that, due to how the C grammar we use is constructed, the visitor pattern cannot be used to find identifiers.
if(false)
{
String code = "rabbit + (1 + (int)monkey * 10) + 7";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
var dest = new ArrayList<String>();
Parsing.getIdentifiers(parser.expression(), dest);
System.out.println("gevonden identifiers:");
for (var s : dest) {
System.out.println(s);
}
System.out.println("");
}
// test if declarations in a for loop can be reparsed as a normal declaration (because the C grammas treats them separately, and I don't want to write duplicate code)
if(false)
{
String code = """
int i;
for (int i=10; i<100; i++) { int i=20; }
for (i=0; i<100; i++) { int i=30; }
for (int i=10, *j; i<100; i++);
""";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
//find all forDeclarations
var forDeclarations = new ArrayList<String>();
(new CBaseVisitor<Void>() {
@Override
public Void visitForDeclaration(CParser.ForDeclarationContext ctx) {
forDeclarations.add(Parsing.normalizedCode(ctx));
return null;
}
}).visit(parser.blockItemList());
// now interpret those as normal declarations. This should work fine.
for (var forDeclaration : forDeclarations) {
var lexer1 = new CLexer(CharStreams.fromString(forDeclaration + ";"));
var parser1 = new CParser(new CommonTokenStream(lexer1));
var as_normal_declaration = parser1.declaration();
System.out.println("found forDeclaration: " + forDeclaration);
System.out.println("parsed as normal declaration: " + Parsing.normalizedCode(as_normal_declaration));
}
System.out.println("");
}
// Test extraction of function parameters
if(false)
{
String code = """
void function(int i, void* ptr, void *ptr2, struct S s, some_typename t) {
}
""";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
(new CBaseVisitor<Void>() {
@Override
public Void visitParameterTypeList(CParser.ParameterTypeListContext ctx) {
var parameterDeclarations = ctx.parameterList().parameterDeclaration();
for (var parameterDeclaration : parameterDeclarations) {
System.out.println("parameter found: " + Parsing.normalizedCode(parameterDeclaration));
}
return null;
}
}).visit(parser.compilationUnit());
System.out.println("");
}
// Test what is considered a type specifier.
if(false)
{
//parse this code as a typename. Result: const is not a type specifier, but unsigned and int are (so even though unsigned int is one type, it consists of multiple type specifiers!)
var lexer = new CLexer(CharStreams.fromString("const unsigned int"));
var parser = new CParser(new CommonTokenStream(lexer));
var typeName = parser.typeName();
var foundTypes = new ArrayList<CParser.TypeSpecifierContext>();
class Visitor extends CBaseVisitor<Object> {
public Object visitTypeSpecifier(CParser.TypeSpecifierContext ctx) {
foundTypes.add(ctx);
return null;
}
}
var visitor = new Visitor();
visitor.visit(typeName);
System.out.println("found type specifiers:");
for (var t : foundTypes) {
System.out.println(Parsing.normalizedCode(t));
}
}
if(false)
{
// Typedefs are considered declarations by the C parser, so I parse this as a declaration. Result: the entire struct is considered one type specifier.
var lexer = new CLexer(CharStreams.fromString("typedef struct {int i;} S;"));
var parser = new CParser(new CommonTokenStream(lexer));
var declaration = parser.declaration();
var foundTypes = new ArrayList<CParser.TypeSpecifierContext>();
class Visitor extends CBaseVisitor<Object> {
public Object visitTypeSpecifier(CParser.TypeSpecifierContext ctx) {
foundTypes.add(ctx);
return null;
}
}
var visitor = new Visitor();
visitor.visit(declaration);
System.out.println("found type specifiers:");
for (var t : foundTypes) {
System.out.println(Parsing.normalizedCode(t));
}
}
// Test parsing of type declarations. A type declaration is really the same as a normal declaration, because you can create a new type and make variables of that type in 1 statement. Example:
// struct S {int i;} variablename;
// The struct that was named by that declaration can be used again, which shows that there really is no difference between type declarations and variable declarations.
if(false)
{
var lexer = new CLexer(CharStreams.fromString("""
typedef struct {int i;} S;
struct struct_name {int i;};
struct struct_name2 {int i;} variable_name;
struct {int i;} variable_name2;
typedef int* int_ptr;
typedef int int_no_ptr;
typedef int int_no_ptr1, int_no_ptr2;
typedef struct{int i;}* struct_ptr;
typedef struct{int i;} struct_no_ptr;
typedef some_name* some_name_ptr;
typedef some_name some_name_no_ptr;
float arr[10];
float vla[n];
int i;
int i,j;
int* i;
int *i;
int i, *j;
int *i, j;
int* i, j;
int *i[10];
int i, *j[10];
int *j[10], i;
int *difficultArrayExpression[rabbits + functioncall(monkeys) - 20], i;
int j[ arr[0] ];
union U { int i; float f; } u, us[10];
int i[10][20];
int i[n][20];
int **i;
int **i[10];
int **i[10][20];
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
int (*((arr4[8])));
int (*((arr5[8]))) = {(int*)90};
int (*(*(arr5[8]))) = {(int*)90}, next;
int ****( *nested[5] )[10][20][30];
int function();
int function(int i);
struct incomplete;
struct incomplete varname;
struct MyStruct { float f; } inst;
struct MyStruct inst2;
struct WithComment {
int i; //comment
void /*comment*/ *v;
};
typedef enum {
LOW = 25,
MEDIUM = 50,
HIGH = 75
} enumName;
enum enumName2 {
TEST = 10
};
"""));
var parser = new CParser(new CommonTokenStream(lexer));
var declarations = new ArrayList<String>();
(new CBaseVisitor<Void>() {
@Override
public Void visitDeclaration(CParser.DeclarationContext ctx) {
declarations.add(Parsing.normalizedCode(ctx));
return null;
}
}).visit(parser.compilationUnit());
//assert declarations.size() == 12;
var dest = new NameInfo();
for (var declaration : declarations)
{
System.out.println("parsing as declaration: " + declaration);
var lexer2 = new CLexer(CharStreams.fromString(declaration));
var parser2 = new CParser(new CommonTokenStream(lexer2));
var tree = parser2.declaration();
System.out.println("parsetree: " + treeShower.show(tree));
DataStructureCVisitor.parseDeclaration(tree, dest, NameInfo.EScope.global);
}
System.out.println("\nfound names: ");
for (var nameInfo : dest.currentScope().getNames()) {
System.out.println(nameInfo);
}
}
// test DeclaratorParser
if(false)
{
assert DataStructureCVisitor.DeclaratorParser.stripParens("").equals("");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a)").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens(" a ").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("a()").equals("a()");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(( (a)) )").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a").equals("(a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("((a)").equals("(a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a))").equals("a)");
// assumptions made in the implementation
var decl = Parsing.makeParser("**arr[10][n]))[m]").declarator();
assert Parsing.normalizedCode(decl).equals("* * arr [ 10 ] [ n ]");
decl = Parsing.makeParser("name").declarator();
assert Parsing.normalizedCode(decl).equals("name");
var expr = Parsing.makeParser("a][10]").expression();
assert Parsing.normalizedCode(expr).equals("a");
// behavior tests
var strDeclarators = new ArrayList<String>();
strDeclarators.add("arr");
strDeclarators.add("arr[10]");
strDeclarators.add("*arr");
strDeclarators.add("*arr[n]");
strDeclarators.add("**arr[10][n]");
strDeclarators.add("*(arr)[10]");
strDeclarators.add("*(*arr)[10]");
strDeclarators.add("*(*arr[n])[10]");
for (var strDeclarator : strDeclarators) {
var declarator = Parsing.makeParser(strDeclarator).declarator();
var baseType = new NormalForm.Builtin("int");
var ret = new DataStructureCVisitor.DeclaratorParser(baseType, declarator);
System.out.println("declarator parse test: " + strDeclarator);
System.out.println("variableName: " + ret.name);
System.out.println("T: " + ret.T);
}
}
// test removeBitfields
if(false)
{
var structSpec = Parsing.makeParser("""
struct {
int i, j : 10;
unsigned : 5;
unsigned k, : 10;
unsigned : 10, L;
int ****( *nested[5] )[10][20][30];
};
""").structOrUnionSpecifier();
(new CBaseVisitor<Void>() {
@Override
public Void visitStructDeclaration(CParser.StructDeclarationContext ctx) {
System.out.println("struct declaration found: " + Parsing.normalizedCode(ctx));
System.out.println("with bitfields removed : " + DataStructureCVisitor.removeBitfields(ctx));
return null;
}
}).visit(structSpec);
}
if(false)
{
// does this throw? answer: no but getNumberOfSyntaxErrors is nonzero
try {
var parser = Parsing.makeParser("121312");
var result = parser.typedefName();
System.out.println("result is null? " + (result == null));
System.out.println("result text: " + result.getText());
System.out.println("number of errors: " + parser.getNumberOfSyntaxErrors());
}
catch (Exception e) {
System.out.println("in the handler");
}
{
// the second call to typeSpecifier returns the "int" part
var parser = Parsing.makeParser("unsigned int");
System.out.println(parser.typeSpecifier().getText());
System.out.println(parser.typeSpecifier().getText());
}
}
// test normalization with consecutive string literals
if(false)
{
var parser = Parsing.makeParser("""
void f() {
printf("a" "b");
printf("c""d");
printf(
"e"
"f"
);
printf(
"\\""
"a\\"b"
);
}
""");
var tree = parser.functionDefinition();
System.out.println( treeShower.show(tree) );
System.out.println("normalized: " + Parsing.normalizedCode(tree));
}
// test parseCompletely
if(false)
{
var nameInfo = new NameInfo();
{
var x = new NameInfo.TypeInfo();
x.T = new NormalForm.Builtin("int");
x.scope = NameInfo.EScope.global;
x.name = "someName";
nameInfo.add(x);
}
var toParse = new NormalForm.Unprocessed("""
struct StructName {
struct LocalStructName {
float f;
} inst;
someName x;
someName *y, *z[10];
struct LocalStructName inst2;
struct NonExisting *ptr;
struct NonExisting nonExistingInst; //invalid C. instance of incomplete type
struct StructName* selfReference;
unsigned int u1;
int unsigned u2;
signed s;
unsigned u;
void* ptr2;
_Bool b : 1; //bitfield
unsigned : 10; //unnamed bitfield
}
""");
var result = DataStructureCVisitor.parseCompletely(toParse, nameInfo);
System.out.println("parseCompletely: " + result);
{
var parser = Parsing.makeParser("int **( *(name)[10][n] )[20];");
var declaration = parser.declaration();
Parsing.assertNoErrors(parser);
DataStructureCVisitor.parseDeclaration(declaration, nameInfo, NameInfo.EScope.local);
var partiallyParsed = nameInfo.getVariableInfo("name").typeInfo.T;
result = DataStructureCVisitor.parseCompletely(partiallyParsed, nameInfo);
System.out.println("parseCompletely: " + result);
}
//test what happens with enums
//currently the answer is: named enums are ignored. enums in a typedef are kept as unparsed. If an attempt is made to parse, an exception is thrown because an enum does not match any expected case.
{
var parser = Parsing.makeParser("""
typedef enum {
LOW = 25,
MEDIUM = 50,
HIGH = 75
} enumName;
enum enumName2 {
TEST = 10
};
""");
var compUnit = parser.compilationUnit();
Parsing.assertNoErrors(parser);
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(compUnit);
visitor.nameInfo.getTypeInfo("int64_t");
try {
var typeInfo = visitor.nameInfo.getTypeInfo("enumName");
System.out.println("enumName found");
try {
var parsedCompletely = DataStructureCVisitor.parseCompletely(typeInfo.T, nameInfo);
System.out.println("completely parsed type of enumName: " + parsedCompletely);
} catch (Exception e) {
System.out.println("unable to completely parse the type of enumName");
}
} catch (Exception e) { System.out.println("enumName not found"); }
try {
var typeInfo = visitor.nameInfo.getTypeInfo("enumName2");
System.out.println("enumName2 found");
} catch (Exception e) { System.out.println("enumName2 not found"); }
System.out.println("all names:");
//visitor.nameInfo.currentScope().printNames();
}
}
if(false) {
// test reinterpretation of a datastructure codemarker as a general codemarker. I need to recover only the ID. The functionality of the DataStructureCodeMarker class is only necessary in the producer.
var cm = new DataStructureCodeMarker("varname");
var id = cm.lngGetID();
var str = cm.toString();
var recovered = new BaseCodeMarker(str);
var id_recovered = recovered.lngGetID();
System.out.println("original ID: " + id);
System.out.println("recovered ID: " + id_recovered);
}
//test problematic behavior of the c-parser. A statement like "typename* t;" is parsed as a multiplication, even if typename is indeed a typename, but "int* i;" is parsed as a declaration.
if(false) {
var parser = Parsing.makeParser("""
_DWORD DS_var_3[10]; // weak
void f() {
char* c;
char *c;
typename* inst;
typename * inst;
typename *inst;
typename * inst, inst2;
typename * inst, a * inst2; //this should actually be parsed as multiplications
undefined1 ( * in_RDX ) [ 10 ] ;
}
""");
var tree = parser.compilationUnit();
System.out.println( treeShower.show(tree) );
}
if(true) {
var parser = Parsing.makeParser("""
float DS_var_8;
int* test;
void f() {
// has no ampersand, so should refer to i
{
int i;
void* p = &i;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b835,__POINTER_FIELD__:%p,CHECKSUM:E3FD", (__int64)p);
}
// already has ampersand, so refers to DS_var_8
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", (__int64)&DS_var_8);
}
// should both be assumed to refer to variable test because there is no assignment expression to replace the "test" without ampersand with
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", test);
}
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", &test);
}
// following multiple assignment expressions
{
int i;
void* p1 = &i;
void* p2 = p1;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", p2);
}
// the same, except the assignments are not part of the declaration
{
int i;
void* p1;
p1 = &i;
void* p2;
p2 = p1;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", p2);
}
double v10[30]; // [esp+48h] [ebp-F0h] BYREF
{
__CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:2d,__POINTER_FIELD__:%p,CHECKSUM:7EC5", (int)v10);
}
}
""");
var tree = parser.compilationUnit();
//System.out.println( treeShower.show(tree) );
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(tree);
for (var testcase : visitor.recovered_testcases) {
System.out.println("testcase recovered: " + testcase.codemarker + ", " + testcase.varInfo);
}
}
if(false) {
for (int i=0; i<1000; i++) {
int r = DataStructureProducer.randomIntBiased(3, Integer.MAX_VALUE);
System.out.println(r);
}
}
if(false) {
var parser = Parsing.makeParser("""
struct_type s;
""");
var tree = parser.declaration();
System.out.println( treeShower.show(tree) );
var nameInfo = new NameInfo();
DataStructureCVisitor.parseDeclaration(tree, nameInfo, NameInfo.EScope.global);
System.out.println("defined names: ");
nameInfo.currentScope().printNames();
}
}
}
| reijer-dev/decompiler-benchmarking | src/main/java/nl/ou/debm/common/feature2/TestMain.java | 8,078 | // struct Naam {int i;} | line_comment | nl | package nl.ou.debm.common.feature2;
import nl.ou.debm.assessor.ETestCategories;
import nl.ou.debm.common.CompilerConfig;
import nl.ou.debm.common.EArchitecture;
import nl.ou.debm.common.ECompiler;
import nl.ou.debm.common.EOptimize;
import nl.ou.debm.common.antlr.CBaseVisitor;
import nl.ou.debm.common.antlr.CLexer;
import nl.ou.debm.common.antlr.CParser;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.misc.Utils;
import org.antlr.v4.runtime.tree.Tree;
import org.antlr.v4.runtime.tree.Trees;
import nl.ou.debm.common.BaseCodeMarker;
import nl.ou.debm.common.CodeMarker;
import nl.ou.debm.common.task.ProcessTask;
import javax.xml.crypto.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// This is a program used to test things during development. todo: convert some things to unit tests
public class TestMain {
// source: https://stackoverflow.com/a/50068645
public static class TreeUtils {
/** Platform dependent end-of-line marker */
public static final String Eol = System.lineSeparator();
/** The literal indent char(s) used for pretty-printing */
public static final String Indents = " ";
private static int level;
private TreeUtils() {}
public static String toPrettyTree(final Tree t, final List<String> ruleNames) {
level = 0;
return process(t, ruleNames).replaceAll("(?m)^\\s+$", "").replaceAll("\\r?\\n\\r?\\n", Eol);
}
private static String process(final Tree t, final List<String> ruleNames) {
if (t.getChildCount() == 0) return Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);
StringBuilder sb = new StringBuilder();
sb.append(lead(level));
level++;
String s = Utils.escapeWhitespace(Trees.getNodeText(t, ruleNames), false);
sb.append(s + ' ');
for (int i = 0; i < t.getChildCount(); i++) {
sb.append(process(t.getChild(i), ruleNames));
}
level--;
sb.append(lead(level));
return sb.toString();
}
private static String lead(int level) {
StringBuilder sb = new StringBuilder();
if (level > 0) {
sb.append(Eol);
for (int cnt = 0; cnt < level; cnt++) {
sb.append(Indents);
}
}
return sb.toString();
}
}
// contains the rulenames for C
public static class CTreeShower {
public static List<String> ruleNamesList;
public CTreeShower() {
var lexer = new CLexer(CharStreams.fromString(""));
var parser = new CParser(new CommonTokenStream(lexer));
ruleNamesList = Arrays.asList(parser.getRuleNames());
}
public String show(ParseTree tree) {
return TreeUtils.toPrettyTree(tree, ruleNamesList);
}
}
public static String cm(String varname) {
return new DataStructureCodeMarker(varname).toCode();
}
public static String mini_CGenerator()
{
var sb = new StringBuilder();
// wat voor soorten typereferenties zijn er in C:
// - ingebouwd:
// int, float, unsigned enz.
// - typedefnamen:
// alle mogelijke identifiers
// - struct zonder naam:
// struct {int i;}
// - struct met naam:
// struct Naam<SUF>
// - referentie naar een eerder benoemd struct:
// struct Naam
//helps to make this test code compileable
sb.append("""
void DataStructureCodeMarker(char*, void*){};
int main() { return 0; }
""");
sb.append("""
struct {
int i;
} varname;
struct S {
int i;
};
typedef struct {
int i;
} S2;
struct S2 {
struct localname {
int i;
};
struct localname l;
int i;
};
typedef int* int_ptr;
typedef int int_no_ptr;
typedef struct{int i;}* struct_ptr;
typedef struct{int i;} struct_no_ptr;
typedef some_name* some_name_ptr;
typedef some_name some_name_no_ptr;
""");
sb.append("""
void blockscope_test() {
int i = 10;
%s
{
unsigned i;
%s
}
%s
}
""".formatted(
cm("i"),
cm("i"),
cm("i")
));
sb.append("""
void struct_type_test() {
{
struct S s;
%s
} {
struct Named {
int i;
} s;
%s
} {
struct {
int i;
} s;
%s
}
}
""".formatted(
cm("s"),
cm("s"),
cm("s")
));
return sb.toString();
}
public static void main(String[] args) throws Exception
{
var treeShower = new CTreeShower();
//test the C visitor on testcode:
if(false)
{
String code = mini_CGenerator();
System.out.println("mini_CGenerator code:\n" + code);
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(parser.compilationUnit());
System.out.println("found testcases: ");
for (var t : visitor.recovered_testcases) {
System.out.println("codemarker: " + t.codemarker);
System.out.println("status: " + t.status);
if (t.varInfo != null) {
System.out.println(t.varInfo);
}
else {
System.out.println("no variable info because status is not ok");
}
System.out.println("");
}
}
//test behavior of getIdentifiers (todo turn these kinds of tests into unit tests)
// getIdentifiers uses (java) reflection as a workaround for the fact that, due to how the C grammar we use is constructed, the visitor pattern cannot be used to find identifiers.
if(false)
{
String code = "rabbit + (1 + (int)monkey * 10) + 7";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
var dest = new ArrayList<String>();
Parsing.getIdentifiers(parser.expression(), dest);
System.out.println("gevonden identifiers:");
for (var s : dest) {
System.out.println(s);
}
System.out.println("");
}
// test if declarations in a for loop can be reparsed as a normal declaration (because the C grammas treats them separately, and I don't want to write duplicate code)
if(false)
{
String code = """
int i;
for (int i=10; i<100; i++) { int i=20; }
for (i=0; i<100; i++) { int i=30; }
for (int i=10, *j; i<100; i++);
""";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
//find all forDeclarations
var forDeclarations = new ArrayList<String>();
(new CBaseVisitor<Void>() {
@Override
public Void visitForDeclaration(CParser.ForDeclarationContext ctx) {
forDeclarations.add(Parsing.normalizedCode(ctx));
return null;
}
}).visit(parser.blockItemList());
// now interpret those as normal declarations. This should work fine.
for (var forDeclaration : forDeclarations) {
var lexer1 = new CLexer(CharStreams.fromString(forDeclaration + ";"));
var parser1 = new CParser(new CommonTokenStream(lexer1));
var as_normal_declaration = parser1.declaration();
System.out.println("found forDeclaration: " + forDeclaration);
System.out.println("parsed as normal declaration: " + Parsing.normalizedCode(as_normal_declaration));
}
System.out.println("");
}
// Test extraction of function parameters
if(false)
{
String code = """
void function(int i, void* ptr, void *ptr2, struct S s, some_typename t) {
}
""";
var lexer = new CLexer(CharStreams.fromString(code));
var parser = new CParser(new CommonTokenStream(lexer));
(new CBaseVisitor<Void>() {
@Override
public Void visitParameterTypeList(CParser.ParameterTypeListContext ctx) {
var parameterDeclarations = ctx.parameterList().parameterDeclaration();
for (var parameterDeclaration : parameterDeclarations) {
System.out.println("parameter found: " + Parsing.normalizedCode(parameterDeclaration));
}
return null;
}
}).visit(parser.compilationUnit());
System.out.println("");
}
// Test what is considered a type specifier.
if(false)
{
//parse this code as a typename. Result: const is not a type specifier, but unsigned and int are (so even though unsigned int is one type, it consists of multiple type specifiers!)
var lexer = new CLexer(CharStreams.fromString("const unsigned int"));
var parser = new CParser(new CommonTokenStream(lexer));
var typeName = parser.typeName();
var foundTypes = new ArrayList<CParser.TypeSpecifierContext>();
class Visitor extends CBaseVisitor<Object> {
public Object visitTypeSpecifier(CParser.TypeSpecifierContext ctx) {
foundTypes.add(ctx);
return null;
}
}
var visitor = new Visitor();
visitor.visit(typeName);
System.out.println("found type specifiers:");
for (var t : foundTypes) {
System.out.println(Parsing.normalizedCode(t));
}
}
if(false)
{
// Typedefs are considered declarations by the C parser, so I parse this as a declaration. Result: the entire struct is considered one type specifier.
var lexer = new CLexer(CharStreams.fromString("typedef struct {int i;} S;"));
var parser = new CParser(new CommonTokenStream(lexer));
var declaration = parser.declaration();
var foundTypes = new ArrayList<CParser.TypeSpecifierContext>();
class Visitor extends CBaseVisitor<Object> {
public Object visitTypeSpecifier(CParser.TypeSpecifierContext ctx) {
foundTypes.add(ctx);
return null;
}
}
var visitor = new Visitor();
visitor.visit(declaration);
System.out.println("found type specifiers:");
for (var t : foundTypes) {
System.out.println(Parsing.normalizedCode(t));
}
}
// Test parsing of type declarations. A type declaration is really the same as a normal declaration, because you can create a new type and make variables of that type in 1 statement. Example:
// struct S {int i;} variablename;
// The struct that was named by that declaration can be used again, which shows that there really is no difference between type declarations and variable declarations.
if(false)
{
var lexer = new CLexer(CharStreams.fromString("""
typedef struct {int i;} S;
struct struct_name {int i;};
struct struct_name2 {int i;} variable_name;
struct {int i;} variable_name2;
typedef int* int_ptr;
typedef int int_no_ptr;
typedef int int_no_ptr1, int_no_ptr2;
typedef struct{int i;}* struct_ptr;
typedef struct{int i;} struct_no_ptr;
typedef some_name* some_name_ptr;
typedef some_name some_name_no_ptr;
float arr[10];
float vla[n];
int i;
int i,j;
int* i;
int *i;
int i, *j;
int *i, j;
int* i, j;
int *i[10];
int i, *j[10];
int *j[10], i;
int *difficultArrayExpression[rabbits + functioncall(monkeys) - 20], i;
int j[ arr[0] ];
union U { int i; float f; } u, us[10];
int i[10][20];
int i[n][20];
int **i;
int **i[10];
int **i[10][20];
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
int (*((arr4[8])));
int (*((arr5[8]))) = {(int*)90};
int (*(*(arr5[8]))) = {(int*)90}, next;
int ****( *nested[5] )[10][20][30];
int function();
int function(int i);
struct incomplete;
struct incomplete varname;
struct MyStruct { float f; } inst;
struct MyStruct inst2;
struct WithComment {
int i; //comment
void /*comment*/ *v;
};
typedef enum {
LOW = 25,
MEDIUM = 50,
HIGH = 75
} enumName;
enum enumName2 {
TEST = 10
};
"""));
var parser = new CParser(new CommonTokenStream(lexer));
var declarations = new ArrayList<String>();
(new CBaseVisitor<Void>() {
@Override
public Void visitDeclaration(CParser.DeclarationContext ctx) {
declarations.add(Parsing.normalizedCode(ctx));
return null;
}
}).visit(parser.compilationUnit());
//assert declarations.size() == 12;
var dest = new NameInfo();
for (var declaration : declarations)
{
System.out.println("parsing as declaration: " + declaration);
var lexer2 = new CLexer(CharStreams.fromString(declaration));
var parser2 = new CParser(new CommonTokenStream(lexer2));
var tree = parser2.declaration();
System.out.println("parsetree: " + treeShower.show(tree));
DataStructureCVisitor.parseDeclaration(tree, dest, NameInfo.EScope.global);
}
System.out.println("\nfound names: ");
for (var nameInfo : dest.currentScope().getNames()) {
System.out.println(nameInfo);
}
}
// test DeclaratorParser
if(false)
{
assert DataStructureCVisitor.DeclaratorParser.stripParens("").equals("");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a)").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens(" a ").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("a()").equals("a()");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(( (a)) )").equals("a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a").equals("(a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("((a)").equals("(a");
assert DataStructureCVisitor.DeclaratorParser.stripParens("(a))").equals("a)");
// assumptions made in the implementation
var decl = Parsing.makeParser("**arr[10][n]))[m]").declarator();
assert Parsing.normalizedCode(decl).equals("* * arr [ 10 ] [ n ]");
decl = Parsing.makeParser("name").declarator();
assert Parsing.normalizedCode(decl).equals("name");
var expr = Parsing.makeParser("a][10]").expression();
assert Parsing.normalizedCode(expr).equals("a");
// behavior tests
var strDeclarators = new ArrayList<String>();
strDeclarators.add("arr");
strDeclarators.add("arr[10]");
strDeclarators.add("*arr");
strDeclarators.add("*arr[n]");
strDeclarators.add("**arr[10][n]");
strDeclarators.add("*(arr)[10]");
strDeclarators.add("*(*arr)[10]");
strDeclarators.add("*(*arr[n])[10]");
for (var strDeclarator : strDeclarators) {
var declarator = Parsing.makeParser(strDeclarator).declarator();
var baseType = new NormalForm.Builtin("int");
var ret = new DataStructureCVisitor.DeclaratorParser(baseType, declarator);
System.out.println("declarator parse test: " + strDeclarator);
System.out.println("variableName: " + ret.name);
System.out.println("T: " + ret.T);
}
}
// test removeBitfields
if(false)
{
var structSpec = Parsing.makeParser("""
struct {
int i, j : 10;
unsigned : 5;
unsigned k, : 10;
unsigned : 10, L;
int ****( *nested[5] )[10][20][30];
};
""").structOrUnionSpecifier();
(new CBaseVisitor<Void>() {
@Override
public Void visitStructDeclaration(CParser.StructDeclarationContext ctx) {
System.out.println("struct declaration found: " + Parsing.normalizedCode(ctx));
System.out.println("with bitfields removed : " + DataStructureCVisitor.removeBitfields(ctx));
return null;
}
}).visit(structSpec);
}
if(false)
{
// does this throw? answer: no but getNumberOfSyntaxErrors is nonzero
try {
var parser = Parsing.makeParser("121312");
var result = parser.typedefName();
System.out.println("result is null? " + (result == null));
System.out.println("result text: " + result.getText());
System.out.println("number of errors: " + parser.getNumberOfSyntaxErrors());
}
catch (Exception e) {
System.out.println("in the handler");
}
{
// the second call to typeSpecifier returns the "int" part
var parser = Parsing.makeParser("unsigned int");
System.out.println(parser.typeSpecifier().getText());
System.out.println(parser.typeSpecifier().getText());
}
}
// test normalization with consecutive string literals
if(false)
{
var parser = Parsing.makeParser("""
void f() {
printf("a" "b");
printf("c""d");
printf(
"e"
"f"
);
printf(
"\\""
"a\\"b"
);
}
""");
var tree = parser.functionDefinition();
System.out.println( treeShower.show(tree) );
System.out.println("normalized: " + Parsing.normalizedCode(tree));
}
// test parseCompletely
if(false)
{
var nameInfo = new NameInfo();
{
var x = new NameInfo.TypeInfo();
x.T = new NormalForm.Builtin("int");
x.scope = NameInfo.EScope.global;
x.name = "someName";
nameInfo.add(x);
}
var toParse = new NormalForm.Unprocessed("""
struct StructName {
struct LocalStructName {
float f;
} inst;
someName x;
someName *y, *z[10];
struct LocalStructName inst2;
struct NonExisting *ptr;
struct NonExisting nonExistingInst; //invalid C. instance of incomplete type
struct StructName* selfReference;
unsigned int u1;
int unsigned u2;
signed s;
unsigned u;
void* ptr2;
_Bool b : 1; //bitfield
unsigned : 10; //unnamed bitfield
}
""");
var result = DataStructureCVisitor.parseCompletely(toParse, nameInfo);
System.out.println("parseCompletely: " + result);
{
var parser = Parsing.makeParser("int **( *(name)[10][n] )[20];");
var declaration = parser.declaration();
Parsing.assertNoErrors(parser);
DataStructureCVisitor.parseDeclaration(declaration, nameInfo, NameInfo.EScope.local);
var partiallyParsed = nameInfo.getVariableInfo("name").typeInfo.T;
result = DataStructureCVisitor.parseCompletely(partiallyParsed, nameInfo);
System.out.println("parseCompletely: " + result);
}
//test what happens with enums
//currently the answer is: named enums are ignored. enums in a typedef are kept as unparsed. If an attempt is made to parse, an exception is thrown because an enum does not match any expected case.
{
var parser = Parsing.makeParser("""
typedef enum {
LOW = 25,
MEDIUM = 50,
HIGH = 75
} enumName;
enum enumName2 {
TEST = 10
};
""");
var compUnit = parser.compilationUnit();
Parsing.assertNoErrors(parser);
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(compUnit);
visitor.nameInfo.getTypeInfo("int64_t");
try {
var typeInfo = visitor.nameInfo.getTypeInfo("enumName");
System.out.println("enumName found");
try {
var parsedCompletely = DataStructureCVisitor.parseCompletely(typeInfo.T, nameInfo);
System.out.println("completely parsed type of enumName: " + parsedCompletely);
} catch (Exception e) {
System.out.println("unable to completely parse the type of enumName");
}
} catch (Exception e) { System.out.println("enumName not found"); }
try {
var typeInfo = visitor.nameInfo.getTypeInfo("enumName2");
System.out.println("enumName2 found");
} catch (Exception e) { System.out.println("enumName2 not found"); }
System.out.println("all names:");
//visitor.nameInfo.currentScope().printNames();
}
}
if(false) {
// test reinterpretation of a datastructure codemarker as a general codemarker. I need to recover only the ID. The functionality of the DataStructureCodeMarker class is only necessary in the producer.
var cm = new DataStructureCodeMarker("varname");
var id = cm.lngGetID();
var str = cm.toString();
var recovered = new BaseCodeMarker(str);
var id_recovered = recovered.lngGetID();
System.out.println("original ID: " + id);
System.out.println("recovered ID: " + id_recovered);
}
//test problematic behavior of the c-parser. A statement like "typename* t;" is parsed as a multiplication, even if typename is indeed a typename, but "int* i;" is parsed as a declaration.
if(false) {
var parser = Parsing.makeParser("""
_DWORD DS_var_3[10]; // weak
void f() {
char* c;
char *c;
typename* inst;
typename * inst;
typename *inst;
typename * inst, inst2;
typename * inst, a * inst2; //this should actually be parsed as multiplications
undefined1 ( * in_RDX ) [ 10 ] ;
}
""");
var tree = parser.compilationUnit();
System.out.println( treeShower.show(tree) );
}
if(true) {
var parser = Parsing.makeParser("""
float DS_var_8;
int* test;
void f() {
// has no ampersand, so should refer to i
{
int i;
void* p = &i;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b835,__POINTER_FIELD__:%p,CHECKSUM:E3FD", (__int64)p);
}
// already has ampersand, so refers to DS_var_8
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", (__int64)&DS_var_8);
}
// should both be assumed to refer to variable test because there is no assignment expression to replace the "test" without ampersand with
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", test);
}
{
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", &test);
}
// following multiple assignment expressions
{
int i;
void* p1 = &i;
void* p2 = p1;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", p2);
}
// the same, except the assignments are not part of the declaration
{
int i;
void* p1;
p1 = &i;
void* p2;
p2 = p1;
_CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:b833,__POINTER_FIELD__:%p,CHECKSUM:C91B", p2);
}
double v10[30]; // [esp+48h] [ebp-F0h] BYREF
{
__CM_printf_ptr("c5852db2-7acb-cba3-7f81-e7ef3cd1d3b8DS>>ID:2d,__POINTER_FIELD__:%p,CHECKSUM:7EC5", (int)v10);
}
}
""");
var tree = parser.compilationUnit();
//System.out.println( treeShower.show(tree) );
var visitor = new DataStructureCVisitor(EArchitecture.X64ARCH);
visitor.visit(tree);
for (var testcase : visitor.recovered_testcases) {
System.out.println("testcase recovered: " + testcase.codemarker + ", " + testcase.varInfo);
}
}
if(false) {
for (int i=0; i<1000; i++) {
int r = DataStructureProducer.randomIntBiased(3, Integer.MAX_VALUE);
System.out.println(r);
}
}
if(false) {
var parser = Parsing.makeParser("""
struct_type s;
""");
var tree = parser.declaration();
System.out.println( treeShower.show(tree) );
var nameInfo = new NameInfo();
DataStructureCVisitor.parseDeclaration(tree, nameInfo, NameInfo.EScope.global);
System.out.println("defined names: ");
nameInfo.currentScope().printNames();
}
}
}
|
2220_3 | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 3 of
* the License, or any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package be.derycke.pieter.com;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Pieter De Rycke
*/
public class COMReference {
private static Set<WeakReference<COMReference>> references;
private static Object lock;
static {
lock = new Object();
references = new HashSet<WeakReference<COMReference>>();
//dit wordt nog voor de finalizers aangeroepen als finalizen
//bij exit aan staat
//dit is voor de objecten die niet of nog niet door de gc
//gefinalized werden
//http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
synchronized(lock) {
for(WeakReference<COMReference> reference : references) {
try {
reference.get().release();
}
catch(NullPointerException e) {}
}
}
}
});
}
private WeakReference<COMReference> reference;
private long pIUnknown;
public COMReference(long pIUnkown) {
this.pIUnknown = pIUnkown;
reference = new WeakReference<COMReference>(this);
synchronized(lock) {
references.add(reference);
}
}
public long getMemoryAddress() {
return pIUnknown;
}
native long release();
native long addRef();
@Override
protected void finalize() {
synchronized(lock) {
references.remove(reference);
release();
}
}
}
| reindahl/jmtp | java/src/be/derycke/pieter/com/COMReference.java | 693 | //bij exit aan staat | line_comment | nl | /*
* Copyright 2007 Pieter De Rycke
*
* This file is part of JMTP.
*
* JTMP 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 3 of
* the License, or any later version.
*
* JMTP 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 LesserGeneral Public
* License along with JMTP. If not, see <http://www.gnu.org/licenses/>.
*/
package be.derycke.pieter.com;
import java.lang.ref.WeakReference;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Pieter De Rycke
*/
public class COMReference {
private static Set<WeakReference<COMReference>> references;
private static Object lock;
static {
lock = new Object();
references = new HashSet<WeakReference<COMReference>>();
//dit wordt nog voor de finalizers aangeroepen als finalizen
//bij exit<SUF>
//dit is voor de objecten die niet of nog niet door de gc
//gefinalized werden
//http://en.allexperts.com/q/Java-1046/Constructor-destructor.htm
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
synchronized(lock) {
for(WeakReference<COMReference> reference : references) {
try {
reference.get().release();
}
catch(NullPointerException e) {}
}
}
}
});
}
private WeakReference<COMReference> reference;
private long pIUnknown;
public COMReference(long pIUnkown) {
this.pIUnknown = pIUnkown;
reference = new WeakReference<COMReference>(this);
synchronized(lock) {
references.add(reference);
}
}
public long getMemoryAddress() {
return pIUnknown;
}
native long release();
native long addRef();
@Override
protected void finalize() {
synchronized(lock) {
references.remove(reference);
release();
}
}
}
|
40042_15 | package com.reinder42.TodoApp.model;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
public class TodoServicePersisted implements TodoServiceInterface
{
// Array met Todo objecten (single source of truth)
private ArrayList<Todo> todos;
// String met bestandsnaam
private static String filename = "todos.obj";
public TodoServicePersisted()
{
// Laad Todo's uit todos.obj, returnt een lege array
// als er iets fout gaat of het bestand niet bestaat.
todos = todosLadenUitBestand();
}
public void voegTodoToe(String text) {
Todo todo = new Todo();
todo.setText(text);
voegTodoToe(todo);
}
public void voegTodoToe(Todo todo)
{
// Voeg toe aan array
todos.add(todo);
// Sla Todo objecten op in todos.obj
todosOpslaanInBestand();
}
@Override
public void markeerTodoAlsGedaan(Todo todo, boolean gedaan)
{
if(!todos.contains(todo)) {
throw new RuntimeException("todo zit niet in todos; integriteit klopt niet!");
}
// Markeer todo als gedaan
todo.setGedaan(gedaan);
// Sla Todo objecten op in todos.obj
todosOpslaanInBestand();
}
public ArrayList<Todo> getTodos() {
return todos;
}
private ArrayList<Todo> todosLadenUitBestand()
{
// Maak lege array
ArrayList<Todo> nieuweTodos = new ArrayList<Todo>();
try {
// Zet een nieuwe stream op naar het bestand
InputStream inputStream = Files.newInputStream(Path.of(filename));
// Zet een nieuwe "object stream" op
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// Lees het object uit het bestand, d.w.z. "het object" hier is een array van Todo objecten!
Object object = objectInputStream.readObject();
// Cast het object naar een ArrayList van Todo objecten
// Let op: er is geen garantie dat er Todo objecten in de ArrayList uit todos.obj zitten.
// Het enige alternatief (dat veiliger is), is Todo objecten 1 voor 1 lezen/toevoegen aan de array.
if(object instanceof ArrayList) {
nieuweTodos = (ArrayList<Todo>) object;
}
// Sluit de stream naar het bestand
objectInputStream.close();
} catch(Exception e) {
System.out.println(e);
}
return nieuweTodos;
}
private void todosOpslaanInBestand()
{
try {
OutputStream outputStream = Files.newOutputStream(Path.of(filename));
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
// Schrijf todos array naar todos.obj
objectOutputStream.writeObject(todos);
// Sluit output stream
objectOutputStream.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
| reinder42/V1OOP-TodoApp | src/main/java/com/reinder42/TodoApp/model/TodoServicePersisted.java | 889 | // Sluit de stream naar het bestand | line_comment | nl | package com.reinder42.TodoApp.model;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
public class TodoServicePersisted implements TodoServiceInterface
{
// Array met Todo objecten (single source of truth)
private ArrayList<Todo> todos;
// String met bestandsnaam
private static String filename = "todos.obj";
public TodoServicePersisted()
{
// Laad Todo's uit todos.obj, returnt een lege array
// als er iets fout gaat of het bestand niet bestaat.
todos = todosLadenUitBestand();
}
public void voegTodoToe(String text) {
Todo todo = new Todo();
todo.setText(text);
voegTodoToe(todo);
}
public void voegTodoToe(Todo todo)
{
// Voeg toe aan array
todos.add(todo);
// Sla Todo objecten op in todos.obj
todosOpslaanInBestand();
}
@Override
public void markeerTodoAlsGedaan(Todo todo, boolean gedaan)
{
if(!todos.contains(todo)) {
throw new RuntimeException("todo zit niet in todos; integriteit klopt niet!");
}
// Markeer todo als gedaan
todo.setGedaan(gedaan);
// Sla Todo objecten op in todos.obj
todosOpslaanInBestand();
}
public ArrayList<Todo> getTodos() {
return todos;
}
private ArrayList<Todo> todosLadenUitBestand()
{
// Maak lege array
ArrayList<Todo> nieuweTodos = new ArrayList<Todo>();
try {
// Zet een nieuwe stream op naar het bestand
InputStream inputStream = Files.newInputStream(Path.of(filename));
// Zet een nieuwe "object stream" op
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
// Lees het object uit het bestand, d.w.z. "het object" hier is een array van Todo objecten!
Object object = objectInputStream.readObject();
// Cast het object naar een ArrayList van Todo objecten
// Let op: er is geen garantie dat er Todo objecten in de ArrayList uit todos.obj zitten.
// Het enige alternatief (dat veiliger is), is Todo objecten 1 voor 1 lezen/toevoegen aan de array.
if(object instanceof ArrayList) {
nieuweTodos = (ArrayList<Todo>) object;
}
// Sluit de<SUF>
objectInputStream.close();
} catch(Exception e) {
System.out.println(e);
}
return nieuweTodos;
}
private void todosOpslaanInBestand()
{
try {
OutputStream outputStream = Files.newOutputStream(Path.of(filename));
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
// Schrijf todos array naar todos.obj
objectOutputStream.writeObject(todos);
// Sluit output stream
objectOutputStream.close();
} catch(Exception e) {
System.out.println(e);
}
}
}
|
189760_0 | package taxon.level;
/**
* Taxon level model
*
* @author Wander Groeneveld
* @version 0.1, 13-6-2017
*/
public class TaxonLevel {
private int id;
private String name;
public TaxonLevel(int id, String name) {
this.id = id;
this.name = name;
}
public TaxonLevel(String name) {
this(0, name);
}
public TaxonLevel() {
this(0, null);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| reinierkors/ipsen5 | api/src/main/java/taxon/level/TaxonLevel.java | 230 | /**
* Taxon level model
*
* @author Wander Groeneveld
* @version 0.1, 13-6-2017
*/ | block_comment | nl | package taxon.level;
/**
* Taxon level model<SUF>*/
public class TaxonLevel {
private int id;
private String name;
public TaxonLevel(int id, String name) {
this.id = id;
this.name = name;
}
public TaxonLevel(String name) {
this(0, name);
}
public TaxonLevel() {
this(0, null);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
22667_11 | package gui;
import java.util.ResourceBundle;
import domein.DomeinController;
import exceptions.alSteenHierException;
import exceptions.geenCorrecteSerieRijException;
import exceptions.geenSteenHierException;
import exceptions.steenIsgeenJoker;
import exceptions.steenValtBuitenBereikException;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
public class vervangJoker extends VBox {
private final DomeinController dc;
private final HoofdPaneel hoofdPaneel;
private SpelPaneel spelpaneel;
private ResourceBundle resourceBundle;
private TextField txfRij, txfKolom, txfSteen;
private HBox hBPositie, hBSteen, hBEigenOfWerk;
private Button btnPlaats, btnTerug, btnNogEens, btnEigen, btnWerkv;
private Label lblEigenOfWerk, lblWelkeSteen, lblUwStenen, lblPlaats, lblGemVeld, lblFout;
private String eigenStenen, stenenWerkveld;
private boolean boolEigenSteen = true;
public vervangJoker(DomeinController dc, HoofdPaneel hoofdPaneel, SpelPaneel spelpaneel,
ResourceBundle resourceBundle) {
this.dc = dc;
this.hoofdPaneel = hoofdPaneel;
this.spelpaneel = spelpaneel;
this.resourceBundle = resourceBundle;
plaatsSteen();
}
private void plaatsSteen() {
maakLabelsEtc();
// -----------------
// eigen stenen laten zien om uit te kiezen
eigenStenen = dc.getSpelerAanBeurt().getEigenStenenAlsString();
eigenStenen = spelpaneel.vertaalStenen(eigenStenen);
eigenStenen = String.format("\t%s %s\n", resourceBundle.getString("persStenen"), eigenStenen);
// -----------------
// stenen uit werkveld laten zien om uit te kiezen
stenenWerkveld = dc.getStenenWerkveldAlsString();
stenenWerkveld = spelpaneel.vertaalStenen(stenenWerkveld);
stenenWerkveld = String.format("\t%s %s\n", resourceBundle.getString("stenenUitWerkveld"), stenenWerkveld);
// -----------------
// controle zie DR_STEEN_AANLEGGEN (DONE)
btnPlaats.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
int rij = 0, kolom = 0, steen = 0;
try {
rij = Integer.parseInt(txfRij.getText());
kolom = Integer.parseInt(txfKolom.getText());
steen = Integer.parseInt(txfSteen.getText());
if (boolEigenSteen) {
// de steen (niet werkveld) op het gemeenschappelijk veld plaatsen
dc.vervangJokerPersSteen(rij - 1, kolom - 1, steen - 1);
// toevoegen om alle gelegde stenen v/d beurt bij te houden (enkel persoonlijk
// bezig ig)
dc.getSpelerAanBeurt().addGelegdeSteen(dc.getSpelerAanBeurt().getEigenStenen().get(steen - 1));
// de steen uit de inventory v/d speler doen
dc.getSpelerAanBeurt().getEigenStenen().remove(steen - 1);
}
else { // steen uit werkveld
// steen uit werkveld op gemveld plaatsen
dc.vervangJokerWerkveld(rij - 1, kolom - 1, steen - 1);
// steen uit werkveld doen
dc.getSpelerAanBeurt().getStenenWerkveld().remove(steen - 1);
}
vernieuwPersoonlijkeStenen();
vernieuwWerkveld();
vernieuwGemVeld();
}
catch (NumberFormatException e) {
erGingIetsFout();
}
catch (steenIsgeenJoker e) {
erGingIetsFout();
}
catch (geenSteenHierException e) {
erGingIetsFout();
}
catch (steenValtBuitenBereikException e) {
erGingIetsFout();
}
catch (geenCorrecteSerieRijException e) {
erGingIetsFout();
}
txfRij.setText("");
txfKolom.setText("");
txfSteen.setText("");
}
});
// -----------------
btnNogEens.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
btnNogEens.setVisible(false);
btnPlaats.setDisable(false);
lblFout.setVisible(false);
}
});
// -----------------
btnTerug.setOnAction(e -> hoofdPaneel.speelVerder());
// -----------------
btnEigen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
boolEigenSteen = true;
btnEigen.setDisable(true);
btnWerkv.setDisable(true);
lblUwStenen.setText(eigenStenen);
lblUwStenen.setVisible(true);
hBSteen.setVisible(true);
hBPositie.setVisible(true);
lblGemVeld.setVisible(true);
btnTerug.setVisible(true);
}
});
// -----------------
btnWerkv.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
boolEigenSteen = false;
btnEigen.setDisable(true);
btnWerkv.setDisable(true);
lblUwStenen.setText(stenenWerkveld);
lblUwStenen.setVisible(true);
hBSteen.setVisible(true);
hBPositie.setVisible(true);
lblGemVeld.setVisible(true);
btnTerug.setVisible(true);
}
});
// -----------------
// gui maken
getChildren().addAll(hBEigenOfWerk, hBSteen, lblUwStenen, hBPositie, lblGemVeld, btnTerug);
}
public void erGingIetsFout() {
lblFout.setText(resourceBundle.getString("erGingIetsFout"));
lblFout.setVisible(true);
btnPlaats.setDisable(true);
btnNogEens.setText(resourceBundle.getString("probeerOpnieuw"));
btnNogEens.setVisible(true);
}
public void vernieuwGemVeld() {
// in dit paneel
String gemveld = spelpaneel.vertaalStenen(dc.getStenenGemVeldAlsString());
lblGemVeld.setText(gemveld);
// op spelpaneel
spelpaneel.toonSpelsituatie(spelpaneel.getLblToonSpelSituatie());
}
public void vernieuwPersoonlijkeStenen() {
String eigenStenen = spelpaneel.vertaalStenen(dc.getSpelerAanBeurt().getEigenStenenAlsString());
lblUwStenen.setText(String.format("%s %s\n", resourceBundle.getString("persStenen"), eigenStenen));
}
public void vernieuwWerkveld() {
String stenenWerkveld = spelpaneel.vertaalStenen(dc.getSpelerAanBeurt().getStenenWerkveldAlsString());
lblUwStenen.setText(String.format("%s %s\n", resourceBundle.getString("stenenUitWerkveld"), stenenWerkveld));
}
private void maakLabelsEtc() {
btnEigen = new Button(resourceBundle.getString("uitEigenStenenKiezen"));
btnWerkv = new Button(resourceBundle.getString("uitWerkveldKiezen"));
btnTerug = new Button();
btnTerug.setPadding(new Insets(1));
btnTerug.setText(resourceBundle.getString("gaTerug"));
btnNogEens = new Button();
btnNogEens.setVisible(false);
btnPlaats = new Button();
btnPlaats.setPadding(new Insets(1));
btnPlaats.setMaxWidth(300);
btnPlaats.setText(resourceBundle.getString("vervangJokerMetSteen"));
// -----------------------------------
lblEigenOfWerk = new Label(resourceBundle.getString("jokerUitEigenSteenOfWerkveld"));
lblWelkeSteen = new Label();
lblWelkeSteen.setText(resourceBundle.getString("vraagWelkeSteenAanleggen"));
lblFout = new Label();
// zijn stenen tonen om te kiezen
lblUwStenen = new Label();
lblUwStenen.setText(resourceBundle.getString("uwStenen"));
lblUwStenen.setVisible(false);
lblPlaats = new Label();
lblPlaats.setText(resourceBundle.getString("welkePlaats"));
// het gemeenschappelijk veld laten zien om de plaats te kiezen
lblGemVeld = new Label();
String gemveld = spelpaneel.vertaalStenen(dc.getStenenGemVeldAlsString());
lblGemVeld.setText(gemveld);
lblGemVeld.setVisible(false);
// -----------------------------------
txfSteen = new TextField();
txfRij = new TextField();
txfKolom = new TextField();
txfRij.setPadding(new Insets(1));
txfRij.setMaxWidth(50);
txfRij.setPromptText(resourceBundle.getString("rij"));
txfKolom.setPadding(new Insets(1));
txfKolom.setMaxWidth(50);
txfKolom.setPromptText(resourceBundle.getString("nummer"));
txfSteen.setPadding(new Insets(1));
txfSteen.setMaxWidth(50);
txfSteen.setPromptText(resourceBundle.getString("steen"));
// -----------------------------------
hBEigenOfWerk = new HBox(lblEigenOfWerk, btnEigen, btnWerkv);
hBSteen = new HBox(lblWelkeSteen, txfSteen);
hBSteen.setVisible(false);
hBPositie = new HBox(lblPlaats, txfRij, txfKolom, btnPlaats, lblFout, btnNogEens);
hBPositie.setVisible(false);
}
}
| remcowds/Rummikub_HoGent_SDPI- | src/gui/vervangJoker.java | 3,178 | // het gemeenschappelijk veld laten zien om de plaats te kiezen | line_comment | nl | package gui;
import java.util.ResourceBundle;
import domein.DomeinController;
import exceptions.alSteenHierException;
import exceptions.geenCorrecteSerieRijException;
import exceptions.geenSteenHierException;
import exceptions.steenIsgeenJoker;
import exceptions.steenValtBuitenBereikException;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
public class vervangJoker extends VBox {
private final DomeinController dc;
private final HoofdPaneel hoofdPaneel;
private SpelPaneel spelpaneel;
private ResourceBundle resourceBundle;
private TextField txfRij, txfKolom, txfSteen;
private HBox hBPositie, hBSteen, hBEigenOfWerk;
private Button btnPlaats, btnTerug, btnNogEens, btnEigen, btnWerkv;
private Label lblEigenOfWerk, lblWelkeSteen, lblUwStenen, lblPlaats, lblGemVeld, lblFout;
private String eigenStenen, stenenWerkveld;
private boolean boolEigenSteen = true;
public vervangJoker(DomeinController dc, HoofdPaneel hoofdPaneel, SpelPaneel spelpaneel,
ResourceBundle resourceBundle) {
this.dc = dc;
this.hoofdPaneel = hoofdPaneel;
this.spelpaneel = spelpaneel;
this.resourceBundle = resourceBundle;
plaatsSteen();
}
private void plaatsSteen() {
maakLabelsEtc();
// -----------------
// eigen stenen laten zien om uit te kiezen
eigenStenen = dc.getSpelerAanBeurt().getEigenStenenAlsString();
eigenStenen = spelpaneel.vertaalStenen(eigenStenen);
eigenStenen = String.format("\t%s %s\n", resourceBundle.getString("persStenen"), eigenStenen);
// -----------------
// stenen uit werkveld laten zien om uit te kiezen
stenenWerkveld = dc.getStenenWerkveldAlsString();
stenenWerkveld = spelpaneel.vertaalStenen(stenenWerkveld);
stenenWerkveld = String.format("\t%s %s\n", resourceBundle.getString("stenenUitWerkveld"), stenenWerkveld);
// -----------------
// controle zie DR_STEEN_AANLEGGEN (DONE)
btnPlaats.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
int rij = 0, kolom = 0, steen = 0;
try {
rij = Integer.parseInt(txfRij.getText());
kolom = Integer.parseInt(txfKolom.getText());
steen = Integer.parseInt(txfSteen.getText());
if (boolEigenSteen) {
// de steen (niet werkveld) op het gemeenschappelijk veld plaatsen
dc.vervangJokerPersSteen(rij - 1, kolom - 1, steen - 1);
// toevoegen om alle gelegde stenen v/d beurt bij te houden (enkel persoonlijk
// bezig ig)
dc.getSpelerAanBeurt().addGelegdeSteen(dc.getSpelerAanBeurt().getEigenStenen().get(steen - 1));
// de steen uit de inventory v/d speler doen
dc.getSpelerAanBeurt().getEigenStenen().remove(steen - 1);
}
else { // steen uit werkveld
// steen uit werkveld op gemveld plaatsen
dc.vervangJokerWerkveld(rij - 1, kolom - 1, steen - 1);
// steen uit werkveld doen
dc.getSpelerAanBeurt().getStenenWerkveld().remove(steen - 1);
}
vernieuwPersoonlijkeStenen();
vernieuwWerkveld();
vernieuwGemVeld();
}
catch (NumberFormatException e) {
erGingIetsFout();
}
catch (steenIsgeenJoker e) {
erGingIetsFout();
}
catch (geenSteenHierException e) {
erGingIetsFout();
}
catch (steenValtBuitenBereikException e) {
erGingIetsFout();
}
catch (geenCorrecteSerieRijException e) {
erGingIetsFout();
}
txfRij.setText("");
txfKolom.setText("");
txfSteen.setText("");
}
});
// -----------------
btnNogEens.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
btnNogEens.setVisible(false);
btnPlaats.setDisable(false);
lblFout.setVisible(false);
}
});
// -----------------
btnTerug.setOnAction(e -> hoofdPaneel.speelVerder());
// -----------------
btnEigen.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
boolEigenSteen = true;
btnEigen.setDisable(true);
btnWerkv.setDisable(true);
lblUwStenen.setText(eigenStenen);
lblUwStenen.setVisible(true);
hBSteen.setVisible(true);
hBPositie.setVisible(true);
lblGemVeld.setVisible(true);
btnTerug.setVisible(true);
}
});
// -----------------
btnWerkv.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent arg0) {
boolEigenSteen = false;
btnEigen.setDisable(true);
btnWerkv.setDisable(true);
lblUwStenen.setText(stenenWerkveld);
lblUwStenen.setVisible(true);
hBSteen.setVisible(true);
hBPositie.setVisible(true);
lblGemVeld.setVisible(true);
btnTerug.setVisible(true);
}
});
// -----------------
// gui maken
getChildren().addAll(hBEigenOfWerk, hBSteen, lblUwStenen, hBPositie, lblGemVeld, btnTerug);
}
public void erGingIetsFout() {
lblFout.setText(resourceBundle.getString("erGingIetsFout"));
lblFout.setVisible(true);
btnPlaats.setDisable(true);
btnNogEens.setText(resourceBundle.getString("probeerOpnieuw"));
btnNogEens.setVisible(true);
}
public void vernieuwGemVeld() {
// in dit paneel
String gemveld = spelpaneel.vertaalStenen(dc.getStenenGemVeldAlsString());
lblGemVeld.setText(gemveld);
// op spelpaneel
spelpaneel.toonSpelsituatie(spelpaneel.getLblToonSpelSituatie());
}
public void vernieuwPersoonlijkeStenen() {
String eigenStenen = spelpaneel.vertaalStenen(dc.getSpelerAanBeurt().getEigenStenenAlsString());
lblUwStenen.setText(String.format("%s %s\n", resourceBundle.getString("persStenen"), eigenStenen));
}
public void vernieuwWerkveld() {
String stenenWerkveld = spelpaneel.vertaalStenen(dc.getSpelerAanBeurt().getStenenWerkveldAlsString());
lblUwStenen.setText(String.format("%s %s\n", resourceBundle.getString("stenenUitWerkveld"), stenenWerkveld));
}
private void maakLabelsEtc() {
btnEigen = new Button(resourceBundle.getString("uitEigenStenenKiezen"));
btnWerkv = new Button(resourceBundle.getString("uitWerkveldKiezen"));
btnTerug = new Button();
btnTerug.setPadding(new Insets(1));
btnTerug.setText(resourceBundle.getString("gaTerug"));
btnNogEens = new Button();
btnNogEens.setVisible(false);
btnPlaats = new Button();
btnPlaats.setPadding(new Insets(1));
btnPlaats.setMaxWidth(300);
btnPlaats.setText(resourceBundle.getString("vervangJokerMetSteen"));
// -----------------------------------
lblEigenOfWerk = new Label(resourceBundle.getString("jokerUitEigenSteenOfWerkveld"));
lblWelkeSteen = new Label();
lblWelkeSteen.setText(resourceBundle.getString("vraagWelkeSteenAanleggen"));
lblFout = new Label();
// zijn stenen tonen om te kiezen
lblUwStenen = new Label();
lblUwStenen.setText(resourceBundle.getString("uwStenen"));
lblUwStenen.setVisible(false);
lblPlaats = new Label();
lblPlaats.setText(resourceBundle.getString("welkePlaats"));
// het gemeenschappelijk<SUF>
lblGemVeld = new Label();
String gemveld = spelpaneel.vertaalStenen(dc.getStenenGemVeldAlsString());
lblGemVeld.setText(gemveld);
lblGemVeld.setVisible(false);
// -----------------------------------
txfSteen = new TextField();
txfRij = new TextField();
txfKolom = new TextField();
txfRij.setPadding(new Insets(1));
txfRij.setMaxWidth(50);
txfRij.setPromptText(resourceBundle.getString("rij"));
txfKolom.setPadding(new Insets(1));
txfKolom.setMaxWidth(50);
txfKolom.setPromptText(resourceBundle.getString("nummer"));
txfSteen.setPadding(new Insets(1));
txfSteen.setMaxWidth(50);
txfSteen.setPromptText(resourceBundle.getString("steen"));
// -----------------------------------
hBEigenOfWerk = new HBox(lblEigenOfWerk, btnEigen, btnWerkv);
hBSteen = new HBox(lblWelkeSteen, txfSteen);
hBSteen.setVisible(false);
hBPositie = new HBox(lblPlaats, txfRij, txfKolom, btnPlaats, lblFout, btnNogEens);
hBPositie.setVisible(false);
}
}
|
103049_0 | package example.controller;
import example.model.Blog;
import example.model.Status;
import example.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/teBekijken")
public class TeBekijkenController {
@Autowired
private BlogService blogService;
@GetMapping("/")
public String teBekijken(Model model) {
List<Blog> teBekijkenItems = blogService.findByStatus(Status.TE_BEKIJKEN);
model.addAttribute("havenSuggestion", new Blog());
model.addAttribute("teBekijkenItems", teBekijkenItems);
// debug what is in TeBekijkenItems
System.out.println(teBekijkenItems.stream().map(Object::toString).collect(Collectors.joining(", ")));
return "teBekijken";
}
@PostMapping("/suggest")
public String suggestBlog(@ModelAttribute("havenSuggestion") Blog blog) {
blog.setStatus(Status.TE_BEKIJKEN);
blog.setContact("sampleContactTestingPurposesOnly");
blogService.add(blog);
return "redirect:/teBekijken/";
}
// update status of blog to "te bekijken"
@PostMapping("/updateStatus")
public String UpdateTeBekijkenStatus(Long id, String status) {
blogService.updateStatus(id, Status.valueOf(status));
return "redirect:/teBekijken/";
}
}
| remzisahbaz/spring-boot-3-security-6 | src/main/java/example/controller/TeBekijkenController.java | 506 | // debug what is in TeBekijkenItems | line_comment | nl | package example.controller;
import example.model.Blog;
import example.model.Status;
import example.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import java.util.stream.Collectors;
@Controller
@RequestMapping("/teBekijken")
public class TeBekijkenController {
@Autowired
private BlogService blogService;
@GetMapping("/")
public String teBekijken(Model model) {
List<Blog> teBekijkenItems = blogService.findByStatus(Status.TE_BEKIJKEN);
model.addAttribute("havenSuggestion", new Blog());
model.addAttribute("teBekijkenItems", teBekijkenItems);
// debug what<SUF>
System.out.println(teBekijkenItems.stream().map(Object::toString).collect(Collectors.joining(", ")));
return "teBekijken";
}
@PostMapping("/suggest")
public String suggestBlog(@ModelAttribute("havenSuggestion") Blog blog) {
blog.setStatus(Status.TE_BEKIJKEN);
blog.setContact("sampleContactTestingPurposesOnly");
blogService.add(blog);
return "redirect:/teBekijken/";
}
// update status of blog to "te bekijken"
@PostMapping("/updateStatus")
public String UpdateTeBekijkenStatus(Long id, String status) {
blogService.updateStatus(id, Status.valueOf(status));
return "redirect:/teBekijken/";
}
}
|
119761_10 | package chapter4.section3;
import chapter1.section3.Queue;
import chapter1.section5.UnionFind;
import chapter2.section4.IndexMinPriorityQueue;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 11/11/17.
*/
public class Exercise31_MSTWeights {
public class LazyPrimMSTWeight {
private boolean[] marked; // minimum spanning tree vertices
private Queue<Edge> minimumSpanningTree;
private PriorityQueueResize<Edge> priorityQueue; // crossing (and ineligible) edges
private double weight;
public LazyPrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
marked = new boolean[edgeWeightedGraph.vertices()];
minimumSpanningTree = new Queue<>();
visit(edgeWeightedGraph, 0); // assumes the graph is connected
while (!priorityQueue.isEmpty()) {
Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue
int vertex1 = edge.either();
int vertex2 = edge.other(vertex1);
// Skip if ineligible
if (marked[vertex1] && marked[vertex2]) {
continue;
}
// Add edge to the minimum spanning tree
minimumSpanningTree.enqueue(edge);
weight += edge.weight();
// Add vertex to the minimum spanning tree
if (!marked[vertex1]) {
visit(edgeWeightedGraph, vertex1);
}
if (!marked[vertex2]) {
visit(edgeWeightedGraph, vertex2);
}
}
}
private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {
// Mark vertex and add to priority queue all edges from vertex to unmarked vertices
marked[vertex] = true;
for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {
if (!marked[edge.other(vertex)]) {
priorityQueue.insert(edge);
}
}
}
public Iterable<Edge> edges() {
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public class PrimMSTWeight {
private Edge[] edgeTo; // shortest edge from tree vertex
private double[] distTo; // distTo[vertex] = edgeTo[vertex].weight()
private boolean[] marked; // true if vertex is on the minimum spanning tree
private IndexMinPriorityQueue<Double> priorityQueue; // eligible crossing edges
private double weight;
public PrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
edgeTo = new Edge[edgeWeightedGraph.vertices()];
distTo = new double[edgeWeightedGraph.vertices()];
marked = new boolean[edgeWeightedGraph.vertices()];
for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {
distTo[vertex] = Double.POSITIVE_INFINITY;
}
priorityQueue = new IndexMinPriorityQueue<>(edgeWeightedGraph.vertices());
// Initialize priority queue with 0, weight 0
distTo[0] = 0;
priorityQueue.insert(0, 0.0);
while (!priorityQueue.isEmpty()) {
visit(edgeWeightedGraph, priorityQueue.deleteMin()); // Add closest vertex to the minimum spanning tree
}
}
private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {
// Add vertex to the minimum spanning tree; update data structures
marked[vertex] = true;
for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {
int otherVertex = edge.other(vertex);
if (marked[otherVertex]) {
continue; // vertex-otherVertex is ineligible
}
if (edge.weight() < distTo[otherVertex]) {
// Edge edge is the new best connection from the minimum spanning tree to otherVertex
if (distTo[otherVertex] != Double.POSITIVE_INFINITY) {
weight -= distTo[otherVertex];
}
weight += edge.weight();
edgeTo[otherVertex] = edge;
distTo[otherVertex] = edge.weight();
if (priorityQueue.contains(otherVertex)) {
priorityQueue.decreaseKey(otherVertex, distTo[otherVertex]);
} else {
priorityQueue.insert(otherVertex, distTo[otherVertex]);
}
}
}
}
public Iterable<Edge> edges() {
Queue<Edge> minimumSpanningTree = new Queue<>();
for (int vertex = 1; vertex < edgeTo.length; vertex++) {
minimumSpanningTree.enqueue(edgeTo[vertex]);
}
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public class KruskalMSTWeight {
private Queue<Edge> minimumSpanningTree;
private double weight;
public KruskalMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
minimumSpanningTree = new Queue<>();
PriorityQueueResize<Edge> priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
for (Edge edge : edgeWeightedGraph.edges()) {
priorityQueue.insert(edge);
}
UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());
while (!priorityQueue.isEmpty() && minimumSpanningTree.size() < edgeWeightedGraph.vertices() - 1) {
Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue
int vertex1 = edge.either();
int vertex2 = edge.other(vertex1);
// Ignore ineligible edges
if (unionFind.connected(vertex1, vertex2)) {
continue;
}
unionFind.union(vertex1, vertex2);
minimumSpanningTree.enqueue(edge); // Add edge to the minimum spanning tree
weight += edge.weight();
}
}
public Iterable<Edge> edges() {
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public static void main(String[] args) {
Exercise31_MSTWeights mstWeights = new Exercise31_MSTWeights();
EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(5);
edgeWeightedGraph.addEdge(new Edge(0, 1, 0.42));
edgeWeightedGraph.addEdge(new Edge(0, 3, 0.5));
edgeWeightedGraph.addEdge(new Edge(1, 2, 0.12));
edgeWeightedGraph.addEdge(new Edge(1, 4, 0.91));
edgeWeightedGraph.addEdge(new Edge(2, 3, 0.72));
edgeWeightedGraph.addEdge(new Edge(3, 4, 0.8));
edgeWeightedGraph.addEdge(new Edge(3, 4, 0.82));
edgeWeightedGraph.addEdge(new Edge(4, 4, 0.1));
Exercise31_MSTWeights.LazyPrimMSTWeight lazyPrimMSTWeight =
mstWeights.new LazyPrimMSTWeight(edgeWeightedGraph);
Exercise31_MSTWeights.PrimMSTWeight primMSTWeight =
mstWeights.new PrimMSTWeight(edgeWeightedGraph);
Exercise31_MSTWeights.KruskalMSTWeight kruskalMSTWeight =
mstWeights.new KruskalMSTWeight(edgeWeightedGraph);
StdOut.println("Expected MST weight: 1.84\n");
StdOut.println("Lazy Prim MST lazy weight: " + lazyPrimMSTWeight.lazyWeight());
StdOut.println("Lazy Prim MST eager weight: " + lazyPrimMSTWeight.eagerWeight());
StdOut.println("Eager Prim MST lazy weight: " + primMSTWeight.lazyWeight());
StdOut.println("Eager Prim MST eager weight: " + primMSTWeight.eagerWeight());
StdOut.println("Kruskal MST lazy weight: " + kruskalMSTWeight.lazyWeight());
StdOut.println("Kruskal MST eager weight: " + kruskalMSTWeight.eagerWeight());
}
}
| reneargento/algorithms-sedgewick-wayne | src/chapter4/section3/Exercise31_MSTWeights.java | 2,364 | // distTo[vertex] = edgeTo[vertex].weight() | line_comment | nl | package chapter4.section3;
import chapter1.section3.Queue;
import chapter1.section5.UnionFind;
import chapter2.section4.IndexMinPriorityQueue;
import chapter2.section4.PriorityQueueResize;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Rene Argento on 11/11/17.
*/
public class Exercise31_MSTWeights {
public class LazyPrimMSTWeight {
private boolean[] marked; // minimum spanning tree vertices
private Queue<Edge> minimumSpanningTree;
private PriorityQueueResize<Edge> priorityQueue; // crossing (and ineligible) edges
private double weight;
public LazyPrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
marked = new boolean[edgeWeightedGraph.vertices()];
minimumSpanningTree = new Queue<>();
visit(edgeWeightedGraph, 0); // assumes the graph is connected
while (!priorityQueue.isEmpty()) {
Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue
int vertex1 = edge.either();
int vertex2 = edge.other(vertex1);
// Skip if ineligible
if (marked[vertex1] && marked[vertex2]) {
continue;
}
// Add edge to the minimum spanning tree
minimumSpanningTree.enqueue(edge);
weight += edge.weight();
// Add vertex to the minimum spanning tree
if (!marked[vertex1]) {
visit(edgeWeightedGraph, vertex1);
}
if (!marked[vertex2]) {
visit(edgeWeightedGraph, vertex2);
}
}
}
private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {
// Mark vertex and add to priority queue all edges from vertex to unmarked vertices
marked[vertex] = true;
for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {
if (!marked[edge.other(vertex)]) {
priorityQueue.insert(edge);
}
}
}
public Iterable<Edge> edges() {
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public class PrimMSTWeight {
private Edge[] edgeTo; // shortest edge from tree vertex
private double[] distTo; // distTo[vertex] =<SUF>
private boolean[] marked; // true if vertex is on the minimum spanning tree
private IndexMinPriorityQueue<Double> priorityQueue; // eligible crossing edges
private double weight;
public PrimMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
edgeTo = new Edge[edgeWeightedGraph.vertices()];
distTo = new double[edgeWeightedGraph.vertices()];
marked = new boolean[edgeWeightedGraph.vertices()];
for (int vertex = 0; vertex < edgeWeightedGraph.vertices(); vertex++) {
distTo[vertex] = Double.POSITIVE_INFINITY;
}
priorityQueue = new IndexMinPriorityQueue<>(edgeWeightedGraph.vertices());
// Initialize priority queue with 0, weight 0
distTo[0] = 0;
priorityQueue.insert(0, 0.0);
while (!priorityQueue.isEmpty()) {
visit(edgeWeightedGraph, priorityQueue.deleteMin()); // Add closest vertex to the minimum spanning tree
}
}
private void visit(EdgeWeightedGraph edgeWeightedGraph, int vertex) {
// Add vertex to the minimum spanning tree; update data structures
marked[vertex] = true;
for (Edge edge : edgeWeightedGraph.adjacent(vertex)) {
int otherVertex = edge.other(vertex);
if (marked[otherVertex]) {
continue; // vertex-otherVertex is ineligible
}
if (edge.weight() < distTo[otherVertex]) {
// Edge edge is the new best connection from the minimum spanning tree to otherVertex
if (distTo[otherVertex] != Double.POSITIVE_INFINITY) {
weight -= distTo[otherVertex];
}
weight += edge.weight();
edgeTo[otherVertex] = edge;
distTo[otherVertex] = edge.weight();
if (priorityQueue.contains(otherVertex)) {
priorityQueue.decreaseKey(otherVertex, distTo[otherVertex]);
} else {
priorityQueue.insert(otherVertex, distTo[otherVertex]);
}
}
}
}
public Iterable<Edge> edges() {
Queue<Edge> minimumSpanningTree = new Queue<>();
for (int vertex = 1; vertex < edgeTo.length; vertex++) {
minimumSpanningTree.enqueue(edgeTo[vertex]);
}
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public class KruskalMSTWeight {
private Queue<Edge> minimumSpanningTree;
private double weight;
public KruskalMSTWeight(EdgeWeightedGraph edgeWeightedGraph) {
minimumSpanningTree = new Queue<>();
PriorityQueueResize<Edge> priorityQueue = new PriorityQueueResize<>(PriorityQueueResize.Orientation.MIN);
for (Edge edge : edgeWeightedGraph.edges()) {
priorityQueue.insert(edge);
}
UnionFind unionFind = new UnionFind(edgeWeightedGraph.vertices());
while (!priorityQueue.isEmpty() && minimumSpanningTree.size() < edgeWeightedGraph.vertices() - 1) {
Edge edge = priorityQueue.deleteTop(); // Get lowest-weight edge from priority queue
int vertex1 = edge.either();
int vertex2 = edge.other(vertex1);
// Ignore ineligible edges
if (unionFind.connected(vertex1, vertex2)) {
continue;
}
unionFind.union(vertex1, vertex2);
minimumSpanningTree.enqueue(edge); // Add edge to the minimum spanning tree
weight += edge.weight();
}
}
public Iterable<Edge> edges() {
return minimumSpanningTree;
}
public double lazyWeight() {
double weight = 0;
for (Edge edge : edges()) {
weight += edge.weight();
}
return weight;
}
public double eagerWeight() {
return weight;
}
}
public static void main(String[] args) {
Exercise31_MSTWeights mstWeights = new Exercise31_MSTWeights();
EdgeWeightedGraph edgeWeightedGraph = new EdgeWeightedGraph(5);
edgeWeightedGraph.addEdge(new Edge(0, 1, 0.42));
edgeWeightedGraph.addEdge(new Edge(0, 3, 0.5));
edgeWeightedGraph.addEdge(new Edge(1, 2, 0.12));
edgeWeightedGraph.addEdge(new Edge(1, 4, 0.91));
edgeWeightedGraph.addEdge(new Edge(2, 3, 0.72));
edgeWeightedGraph.addEdge(new Edge(3, 4, 0.8));
edgeWeightedGraph.addEdge(new Edge(3, 4, 0.82));
edgeWeightedGraph.addEdge(new Edge(4, 4, 0.1));
Exercise31_MSTWeights.LazyPrimMSTWeight lazyPrimMSTWeight =
mstWeights.new LazyPrimMSTWeight(edgeWeightedGraph);
Exercise31_MSTWeights.PrimMSTWeight primMSTWeight =
mstWeights.new PrimMSTWeight(edgeWeightedGraph);
Exercise31_MSTWeights.KruskalMSTWeight kruskalMSTWeight =
mstWeights.new KruskalMSTWeight(edgeWeightedGraph);
StdOut.println("Expected MST weight: 1.84\n");
StdOut.println("Lazy Prim MST lazy weight: " + lazyPrimMSTWeight.lazyWeight());
StdOut.println("Lazy Prim MST eager weight: " + lazyPrimMSTWeight.eagerWeight());
StdOut.println("Eager Prim MST lazy weight: " + primMSTWeight.lazyWeight());
StdOut.println("Eager Prim MST eager weight: " + primMSTWeight.eagerWeight());
StdOut.println("Kruskal MST lazy weight: " + kruskalMSTWeight.lazyWeight());
StdOut.println("Kruskal MST eager weight: " + kruskalMSTWeight.eagerWeight());
}
}
|
114083_2 | package infoborden;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import tijdtools.InfobordTijdFuncties;
public class Infobord extends Application{
private String titel = "Bushalte XX in richting YY";
private Text tijdRegel = new Text("00:00:00");
private Text infoRegel1 = new Text("De eestevolgende bus");
private Text infoRegel2 = new Text("De tweede bus");
private Text infoRegel3 = new Text("De derde bus");
private Text infoRegel4 = new Text("De vierde bus");
private String halte;
private String richting;
private Berichten berichten;
public Infobord(String halte, String richting) {
this.titel = "Bushalte " + halte + " in richting " + richting;
this.halte=halte;
this.richting=richting;
this.berichten=new Berichten();
}
public void verwerkBericht() {
if (berichten.hetBordMoetVerverst()) {
String[] infoTekstRegels = berichten.repaintInfoBordValues();
// Deze code hoort bij opdracht 3
// InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties();
// String tijd = tijdfuncties.getCentralTime().toString();
// tijdRegel.setText(tijd);
infoRegel1.setText(infoTekstRegels[0]);
infoRegel2.setText(infoTekstRegels[1]);
infoRegel3.setText(infoTekstRegels[2]);
infoRegel4.setText(infoTekstRegels[3]);
};
}
public void updateBord() {
Runnable updater = new Runnable() {
@Override
public void run() {
verwerkBericht();
}
};
Platform.runLater(updater);
}
@Override
public void start(Stage primaryStage) {
// TODO maak de selector aan
// String selector = ??????;
// thread(new ListenerStarter(selector, this, berichten),false);
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER_LEFT);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane
pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0);
pane.add(tijdRegel, 1, 0);
pane.add(new Label("1:"), 0, 1);
pane.add(infoRegel1, 1, 1);
pane.add(new Label("2:"), 0, 2);
pane.add(infoRegel2, 1, 2);
pane.add(new Label("3:"), 0, 3);
pane.add(infoRegel3, 1, 3);
pane.add(new Label("4:"), 0, 4);
pane.add(infoRegel4, 1, 4);
// Create a scene and place it in the stage
Scene scene = new Scene(pane,500,150);
primaryStage.setTitle(titel); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
} | reneoun/EAI | eai_bussimulatorStudenten/InfobordSysteem/infoborden/Infobord.java | 1,088 | // String tijd = tijdfuncties.getCentralTime().toString(); | line_comment | nl | package infoborden;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import tijdtools.InfobordTijdFuncties;
public class Infobord extends Application{
private String titel = "Bushalte XX in richting YY";
private Text tijdRegel = new Text("00:00:00");
private Text infoRegel1 = new Text("De eestevolgende bus");
private Text infoRegel2 = new Text("De tweede bus");
private Text infoRegel3 = new Text("De derde bus");
private Text infoRegel4 = new Text("De vierde bus");
private String halte;
private String richting;
private Berichten berichten;
public Infobord(String halte, String richting) {
this.titel = "Bushalte " + halte + " in richting " + richting;
this.halte=halte;
this.richting=richting;
this.berichten=new Berichten();
}
public void verwerkBericht() {
if (berichten.hetBordMoetVerverst()) {
String[] infoTekstRegels = berichten.repaintInfoBordValues();
// Deze code hoort bij opdracht 3
// InfobordTijdFuncties tijdfuncties = new InfobordTijdFuncties();
// String tijd<SUF>
// tijdRegel.setText(tijd);
infoRegel1.setText(infoTekstRegels[0]);
infoRegel2.setText(infoTekstRegels[1]);
infoRegel3.setText(infoTekstRegels[2]);
infoRegel4.setText(infoTekstRegels[3]);
};
}
public void updateBord() {
Runnable updater = new Runnable() {
@Override
public void run() {
verwerkBericht();
}
};
Platform.runLater(updater);
}
@Override
public void start(Stage primaryStage) {
// TODO maak de selector aan
// String selector = ??????;
// thread(new ListenerStarter(selector, this, berichten),false);
GridPane pane = new GridPane();
pane.setAlignment(Pos.CENTER_LEFT);
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
pane.setHgap(5.5);
pane.setVgap(5.5);
// Place nodes in the pane
pane.add(new Label("Voor het laatst bijgewerkt op :"), 0, 0);
pane.add(tijdRegel, 1, 0);
pane.add(new Label("1:"), 0, 1);
pane.add(infoRegel1, 1, 1);
pane.add(new Label("2:"), 0, 2);
pane.add(infoRegel2, 1, 2);
pane.add(new Label("3:"), 0, 3);
pane.add(infoRegel3, 1, 3);
pane.add(new Label("4:"), 0, 4);
pane.add(infoRegel4, 1, 4);
// Create a scene and place it in the stage
Scene scene = new Scene(pane,500,150);
primaryStage.setTitle(titel); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
}
public void thread(Runnable runnable, boolean daemon) {
Thread brokerThread = new Thread(runnable);
brokerThread.setDaemon(daemon);
brokerThread.start();
}
} |
56022_21 | package yolo;
import java.util.*;
public class KantineSimulatie_2 {
//Array van personen
public ArrayList<Persoon> personen = new ArrayList<>();
// kantine
private Kantine kantine;
// kantineaanbod
private KantineAanbod kantineaanbod;
// random generator
private Random random;
// aantal artikelen
private static final int AANTAL_ARTIKELEN = 4;
// artikelen
private static final String[] artikelnamen = new String[]
{"Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap"};
// prijzen
private static double[] artikelprijzen = new double[]{1.50, 2.10, 1.65, 1.65};
// minimum en maximum aantal artikelen per soort
private static final int MIN_ARTIKELEN_PER_SOORT = 10000;
private static final int MAX_ARTIKELEN_PER_SOORT = 20000;
// minimum en maximum aantal personen per dag
private static final int MIN_PERSONEN_PER_DAG = 50;
private static final int MAX_PERSONEN_PER_DAG = 100;
// minimum en maximum artikelen per persoon
private static final int MIN_ARTIKELEN_PER_PERSOON = 1;
private static final int MAX_ARTIKELEN_PER_PERSOON = 4;
private javax.persistence.EntityManager manager;
/**
* Constructor
*
*/
public KantineSimulatie_2(javax.persistence.EntityManager manager) {
kantine = new Kantine(manager);
random = new Random();
int[] hoeveelheden = getRandomArray(
AANTAL_ARTIKELEN,
MIN_ARTIKELEN_PER_SOORT,
MAX_ARTIKELEN_PER_SOORT);
kantineaanbod = new KantineAanbod(
artikelnamen, artikelprijzen, hoeveelheden, MIN_ARTIKELEN_PER_SOORT);
kantine.setKantineAanbod(kantineaanbod);
}
/**
* Methode om een array van random getallen liggend tussen
* min en max van de gegeven lengte te genereren
*
* @param lengte
* @param min
* @param max
* @return De array met random getallen
*/
private int[] getRandomArray(int lengte, int min, int max) {
int[] temp = new int[lengte];
for(int i = 0; i < lengte ;i++) {
temp[i] = getRandomValue(min, max);
}
return temp;
}
/**
* Methode om een random getal tussen min(incl)
* en max(incl) te genereren.
*
* @param min
* @param max
* @return Een random getal
*/
private int getRandomValue(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
/**
* Methode om op basis van een array van indexen voor de array
* artikelnamen de bijhorende array van artikelnamen te maken
*
* @param indexen
* @return De array met artikelnamen
*/
private String[] geefArtikelNamen(int[] indexen) {
String[] artikelen = new String[indexen.length];
for(int i = 0; i < indexen.length; i++) {
artikelen[i] = artikelnamen[indexen[i]];
}
return artikelen;
}
/**
* Deze methode simuleert een aantal dagen
* in het verloop van de kantine
*
* @param dagen
*/
public void simuleer(int dagen){
// for lus voor dagen
for(int i = 0; i < dagen; i++) {
// bedenk hoeveel personen vandaag binnen lopen
int aantalpersonen = getRandomValue(MIN_PERSONEN_PER_DAG,MAX_PERSONEN_PER_DAG) ;
// 100 personen worden hier gemaakt
for (int x = 0; x < 100; x++){
String bsn = "bsnnmmr"+x;
String vnaam = "voornaam"+x;
String anaam = "achternaam"+x;
Datum datum = new Datum(x%28,x%12,2000);
Contant contant = new Contant();
Pinpas pinpas = new Pinpas();
int manOfVrouw = getRandomValue(0,1);
char geslacht = ' ';
if (manOfVrouw == 0) geslacht = 'M';
else if (manOfVrouw == 1) geslacht = 'V';
// 89 Studenten worden hier gemaakt.
if (x<89) {
int studentenummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
String studierichting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
studierichting = "NSE";
} else if (random == 2) {
studierichting = "SE";
} else {
studierichting = "Bitm";
}
Student student = new Student(studentenummer,studierichting,bsn,vnaam,anaam,datum,geslacht);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een student een pinpas met geld.
student.setBetaalwijze(pinpas);
personen.add(student);
}
// 10 Docenten worden hiero gemaakt
else if (x<99) {
String alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM";
String afdeling = "";
String afkorting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
afdeling = "Talen";
} else if (random == 2) {
afdeling = "Management";
} else {
afdeling = "Programmeren";
}
for (int s = 0; s < 4; s++) {
afkorting += alphabet.charAt(getRandomValue(0,25));
}
Docent docent = new Docent(bsn,vnaam,anaam,datum,geslacht,afdeling,afkorting);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een Docent een pinpas met geld.
docent.setBetaalwijze(pinpas);
personen.add(docent);
}
// 1 Kantinemedewerker wordt hier gemaakt
else {
int medewerkersnummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
int r = getRandomValue(0,1);
boolean kassawaardig;
if (r==0) kassawaardig = true;
else kassawaardig = false;
KantineMedewerker kantineMedewerker = new KantineMedewerker(bsn,vnaam,anaam,datum,geslacht,medewerkersnummer,kassawaardig);
contant.setSaldo((double) getRandomValue(2,20)); // We geven hier een Kantine Medewerker contant geld.
kantineMedewerker.setBetaalwijze(contant);
personen.add(kantineMedewerker);
}
}
// laat de personen maar komen...
for(int j = 0; j < aantalpersonen; j++) {
// maak persoon en dienblad aan, koppel ze
// en bedenk hoeveel artikelen worden gepakt
Random rndm = new Random();
int r = rndm.nextInt(100);
Dienblad dienblad = new Dienblad();
dienblad.setPersoon(personen.get(r));
int aantalartikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON,MAX_ARTIKELEN_PER_PERSOON);
// genereer de "artikelnummers", dit zijn indexen
// van de artikelnamen
int[] tepakken = getRandomArray(
aantalartikelen, 0, AANTAL_ARTIKELEN-1);
// vind de artikelnamen op basis van
// de indexen hierboven
String[] artikelen = geefArtikelNamen(tepakken);
// loop de kantine binnen, pak de gewenste
// artikelen, sluit aan
kantine.loopPakSluitAan(personen.get(r),artikelen);
}
try{
Thread.sleep(500);
}catch (Exception e) {
System.out.println(e);
}
// verwerk rij voor de kassa
kantine.verwerkRijVoorKassa();
// druk de dagtotalen af en hoeveel personen binnen
// zijn gekomen(printf gebruiken)
System.out.println("Dag "+(i+1)+": Omzet van "+(Math.round(kantine.hoeveelheidGeldInKassa()*100))/100+" euro & "+kantine.aantalArtikelen()+" artikel afgerekend.");
// reset de kassa voor de volgende dag
kantine.resetKassa();
}
}
public static void main(String[] args) {
int[] getallen = {45, 56, 34, 39, 40, 31};
double[] omzet = {567.70, 498.25, 458.90};
double[] omzetPeriode = {321.35, 450.50, 210.45, 190.85, 193.25, 159.90, 214.25, 220.90, 201.90, 242.70, 260.35};
System.out.println(Administratie.berekenGemiddeldAantal(getallen)); //gem = 40.8333
System.out.println(Administratie.berekenGemiddeldeOmzet(omzet)); //gem = 508.2833
int dag = 0;
for(double i : Administratie.berekenDagOmzet(omzetPeriode)) {
System.out.println("Dag "+dag+": "+i);
dag++;
}
}
} | reneoun/KantineUnit | src/main/java/yolo/KantineSimulatie_2.java | 2,903 | // genereer de "artikelnummers", dit zijn indexen | line_comment | nl | package yolo;
import java.util.*;
public class KantineSimulatie_2 {
//Array van personen
public ArrayList<Persoon> personen = new ArrayList<>();
// kantine
private Kantine kantine;
// kantineaanbod
private KantineAanbod kantineaanbod;
// random generator
private Random random;
// aantal artikelen
private static final int AANTAL_ARTIKELEN = 4;
// artikelen
private static final String[] artikelnamen = new String[]
{"Koffie", "Broodje pindakaas", "Broodje kaas", "Appelsap"};
// prijzen
private static double[] artikelprijzen = new double[]{1.50, 2.10, 1.65, 1.65};
// minimum en maximum aantal artikelen per soort
private static final int MIN_ARTIKELEN_PER_SOORT = 10000;
private static final int MAX_ARTIKELEN_PER_SOORT = 20000;
// minimum en maximum aantal personen per dag
private static final int MIN_PERSONEN_PER_DAG = 50;
private static final int MAX_PERSONEN_PER_DAG = 100;
// minimum en maximum artikelen per persoon
private static final int MIN_ARTIKELEN_PER_PERSOON = 1;
private static final int MAX_ARTIKELEN_PER_PERSOON = 4;
private javax.persistence.EntityManager manager;
/**
* Constructor
*
*/
public KantineSimulatie_2(javax.persistence.EntityManager manager) {
kantine = new Kantine(manager);
random = new Random();
int[] hoeveelheden = getRandomArray(
AANTAL_ARTIKELEN,
MIN_ARTIKELEN_PER_SOORT,
MAX_ARTIKELEN_PER_SOORT);
kantineaanbod = new KantineAanbod(
artikelnamen, artikelprijzen, hoeveelheden, MIN_ARTIKELEN_PER_SOORT);
kantine.setKantineAanbod(kantineaanbod);
}
/**
* Methode om een array van random getallen liggend tussen
* min en max van de gegeven lengte te genereren
*
* @param lengte
* @param min
* @param max
* @return De array met random getallen
*/
private int[] getRandomArray(int lengte, int min, int max) {
int[] temp = new int[lengte];
for(int i = 0; i < lengte ;i++) {
temp[i] = getRandomValue(min, max);
}
return temp;
}
/**
* Methode om een random getal tussen min(incl)
* en max(incl) te genereren.
*
* @param min
* @param max
* @return Een random getal
*/
private int getRandomValue(int min, int max) {
return random.nextInt(max - min + 1) + min;
}
/**
* Methode om op basis van een array van indexen voor de array
* artikelnamen de bijhorende array van artikelnamen te maken
*
* @param indexen
* @return De array met artikelnamen
*/
private String[] geefArtikelNamen(int[] indexen) {
String[] artikelen = new String[indexen.length];
for(int i = 0; i < indexen.length; i++) {
artikelen[i] = artikelnamen[indexen[i]];
}
return artikelen;
}
/**
* Deze methode simuleert een aantal dagen
* in het verloop van de kantine
*
* @param dagen
*/
public void simuleer(int dagen){
// for lus voor dagen
for(int i = 0; i < dagen; i++) {
// bedenk hoeveel personen vandaag binnen lopen
int aantalpersonen = getRandomValue(MIN_PERSONEN_PER_DAG,MAX_PERSONEN_PER_DAG) ;
// 100 personen worden hier gemaakt
for (int x = 0; x < 100; x++){
String bsn = "bsnnmmr"+x;
String vnaam = "voornaam"+x;
String anaam = "achternaam"+x;
Datum datum = new Datum(x%28,x%12,2000);
Contant contant = new Contant();
Pinpas pinpas = new Pinpas();
int manOfVrouw = getRandomValue(0,1);
char geslacht = ' ';
if (manOfVrouw == 0) geslacht = 'M';
else if (manOfVrouw == 1) geslacht = 'V';
// 89 Studenten worden hier gemaakt.
if (x<89) {
int studentenummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
String studierichting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
studierichting = "NSE";
} else if (random == 2) {
studierichting = "SE";
} else {
studierichting = "Bitm";
}
Student student = new Student(studentenummer,studierichting,bsn,vnaam,anaam,datum,geslacht);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een student een pinpas met geld.
student.setBetaalwijze(pinpas);
personen.add(student);
}
// 10 Docenten worden hiero gemaakt
else if (x<99) {
String alphabet = "QWERTYUIOPASDFGHJKLZXCVBNM";
String afdeling = "";
String afkorting = "";
int random = getRandomValue(1, 3);
if (random == 1) {
afdeling = "Talen";
} else if (random == 2) {
afdeling = "Management";
} else {
afdeling = "Programmeren";
}
for (int s = 0; s < 4; s++) {
afkorting += alphabet.charAt(getRandomValue(0,25));
}
Docent docent = new Docent(bsn,vnaam,anaam,datum,geslacht,afdeling,afkorting);
pinpas.setKredietLimiet((double) getRandomValue(6,50)); //We geven hier een Docent een pinpas met geld.
docent.setBetaalwijze(pinpas);
personen.add(docent);
}
// 1 Kantinemedewerker wordt hier gemaakt
else {
int medewerkersnummer = Integer.valueOf("" + ((x + 8) % 8) + "420" + ((x + 11) % 11));
int r = getRandomValue(0,1);
boolean kassawaardig;
if (r==0) kassawaardig = true;
else kassawaardig = false;
KantineMedewerker kantineMedewerker = new KantineMedewerker(bsn,vnaam,anaam,datum,geslacht,medewerkersnummer,kassawaardig);
contant.setSaldo((double) getRandomValue(2,20)); // We geven hier een Kantine Medewerker contant geld.
kantineMedewerker.setBetaalwijze(contant);
personen.add(kantineMedewerker);
}
}
// laat de personen maar komen...
for(int j = 0; j < aantalpersonen; j++) {
// maak persoon en dienblad aan, koppel ze
// en bedenk hoeveel artikelen worden gepakt
Random rndm = new Random();
int r = rndm.nextInt(100);
Dienblad dienblad = new Dienblad();
dienblad.setPersoon(personen.get(r));
int aantalartikelen = getRandomValue(MIN_ARTIKELEN_PER_PERSOON,MAX_ARTIKELEN_PER_PERSOON);
// genereer de<SUF>
// van de artikelnamen
int[] tepakken = getRandomArray(
aantalartikelen, 0, AANTAL_ARTIKELEN-1);
// vind de artikelnamen op basis van
// de indexen hierboven
String[] artikelen = geefArtikelNamen(tepakken);
// loop de kantine binnen, pak de gewenste
// artikelen, sluit aan
kantine.loopPakSluitAan(personen.get(r),artikelen);
}
try{
Thread.sleep(500);
}catch (Exception e) {
System.out.println(e);
}
// verwerk rij voor de kassa
kantine.verwerkRijVoorKassa();
// druk de dagtotalen af en hoeveel personen binnen
// zijn gekomen(printf gebruiken)
System.out.println("Dag "+(i+1)+": Omzet van "+(Math.round(kantine.hoeveelheidGeldInKassa()*100))/100+" euro & "+kantine.aantalArtikelen()+" artikel afgerekend.");
// reset de kassa voor de volgende dag
kantine.resetKassa();
}
}
public static void main(String[] args) {
int[] getallen = {45, 56, 34, 39, 40, 31};
double[] omzet = {567.70, 498.25, 458.90};
double[] omzetPeriode = {321.35, 450.50, 210.45, 190.85, 193.25, 159.90, 214.25, 220.90, 201.90, 242.70, 260.35};
System.out.println(Administratie.berekenGemiddeldAantal(getallen)); //gem = 40.8333
System.out.println(Administratie.berekenGemiddeldeOmzet(omzet)); //gem = 508.2833
int dag = 0;
for(double i : Administratie.berekenDagOmzet(omzetPeriode)) {
System.out.println("Dag "+dag+": "+i);
dag++;
}
}
} |
43972_0 | package prog2.util;
import java.util.Random;
public class Noise {
/* Perlin Noise generator genomen en aangepast van https://stackoverflow.com/questions/5531019/perlin-noise-in-java door jt78
* deze wordt gebruikt voor het genereren van mooiere patronen voor de achtergrondtegels */
private final Random rand_;
private final float roughness_;
private final float[][] grid;
public Noise(Random rand, float roughness, int width, int height) {
roughness_ = roughness / width;
grid = new float[width][height];
rand_ = (rand == null) ? new Random() : rand;
}
public void initialise() {
int xh = grid.length - 1;
int yh = grid[0].length - 1;
grid[0][0] = rand_.nextFloat() - 0.5f;
grid[0][yh] = rand_.nextFloat() - 0.5f;
grid[xh][0] = rand_.nextFloat() - 0.5f;
grid[xh][yh] = rand_.nextFloat() - 0.5f;
generate(0, 0, xh, yh);
}
private float roughen(float v, int l, int h) {
return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}
private void generate(int xl, int yl, int xh, int yh) {
int xm = (xl + xh) / 2;
int ym = (yl + yh) / 2;
if ((xl == xm) && (yl == ym)) return;
grid[xm][yl] = 0.5f * (grid[xl][yl] + grid[xh][yl]);
grid[xm][yh] = 0.5f * (grid[xl][yh] + grid[xh][yh]);
grid[xl][ym] = 0.5f * (grid[xl][yl] + grid[xl][yh]);
grid[xh][ym] = 0.5f * (grid[xh][yl] + grid[xh][yh]);
float v = roughen(0.5f * (grid[xm][yl] + grid[xm][yh]), xl + yl, yh
+ xh);
grid[xm][ym] = v;
grid[xm][yl] = roughen(grid[xm][yl], xl, xh);
grid[xm][yh] = roughen(grid[xm][yh], xl, xh);
grid[xl][ym] = roughen(grid[xl][ym], yl, yh);
grid[xh][ym] = roughen(grid[xh][ym], yl, yh);
generate(xl, yl, xm, ym);
generate(xm, yl, xh, ym);
generate(xl, ym, xm, yh);
generate(xm, ym, xh, yh);
}
public float[][] getGrid() {
return grid;
}
}
| renevds/polis | src/prog2/util/Noise.java | 828 | /* Perlin Noise generator genomen en aangepast van https://stackoverflow.com/questions/5531019/perlin-noise-in-java door jt78
* deze wordt gebruikt voor het genereren van mooiere patronen voor de achtergrondtegels */ | block_comment | nl | package prog2.util;
import java.util.Random;
public class Noise {
/* Perlin Noise generator<SUF>*/
private final Random rand_;
private final float roughness_;
private final float[][] grid;
public Noise(Random rand, float roughness, int width, int height) {
roughness_ = roughness / width;
grid = new float[width][height];
rand_ = (rand == null) ? new Random() : rand;
}
public void initialise() {
int xh = grid.length - 1;
int yh = grid[0].length - 1;
grid[0][0] = rand_.nextFloat() - 0.5f;
grid[0][yh] = rand_.nextFloat() - 0.5f;
grid[xh][0] = rand_.nextFloat() - 0.5f;
grid[xh][yh] = rand_.nextFloat() - 0.5f;
generate(0, 0, xh, yh);
}
private float roughen(float v, int l, int h) {
return v + roughness_ * (float) (rand_.nextGaussian() * (h - l));
}
private void generate(int xl, int yl, int xh, int yh) {
int xm = (xl + xh) / 2;
int ym = (yl + yh) / 2;
if ((xl == xm) && (yl == ym)) return;
grid[xm][yl] = 0.5f * (grid[xl][yl] + grid[xh][yl]);
grid[xm][yh] = 0.5f * (grid[xl][yh] + grid[xh][yh]);
grid[xl][ym] = 0.5f * (grid[xl][yl] + grid[xl][yh]);
grid[xh][ym] = 0.5f * (grid[xh][yl] + grid[xh][yh]);
float v = roughen(0.5f * (grid[xm][yl] + grid[xm][yh]), xl + yl, yh
+ xh);
grid[xm][ym] = v;
grid[xm][yl] = roughen(grid[xm][yl], xl, xh);
grid[xm][yh] = roughen(grid[xm][yh], xl, xh);
grid[xl][ym] = roughen(grid[xl][ym], yl, yh);
grid[xh][ym] = roughen(grid[xh][ym], yl, yh);
generate(xl, yl, xm, ym);
generate(xm, yl, xh, ym);
generate(xl, ym, xm, yh);
generate(xm, ym, xh, yh);
}
public float[][] getGrid() {
return grid;
}
}
|
56979_7 | /*
* eID Applet Project.
* Copyright (C) 2008-2009 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.eid.applet.service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD(
"8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister – Tijdelijk verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring
* van inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19");
private final int key;
private DocumentType(String value) {
this.key = toKey(value);
}
private int toKey(String value) {
char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: "
+ encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(byte[] value) {
int key = toKey(value);
DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(byte[] documentTypeValue) {
String str = Integer.toString(toKey(documentTypeValue));
return str;
}
}
| renovate-bot/eid-applet | eid-applet-service/src/main/java/be/fedict/eid/applet/service/DocumentType.java | 1,152 | /**
* Document ter staving van duurzaam verblijf van een EU onderdaan
*/ | block_comment | nl | /*
* eID Applet Project.
* Copyright (C) 2008-2009 FedICT.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version
* 3.0 as published by the Free Software Foundation.
*
* This software 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 this software; if not, see
* http://www.gnu.org/licenses/.
*/
package be.fedict.eid.applet.service;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Enumeration for eID Document Type.
*
* @author Frank Cornelis
*
*/
public enum DocumentType implements Serializable {
BELGIAN_CITIZEN("1"), KIDS_CARD("6"), BOOTSTRAP_CARD("7"), HABILITATION_CARD(
"8"),
/**
* Bewijs van inschrijving in het vreemdelingenregister – Tijdelijk verblijf
*/
FOREIGNER_A("11"),
/**
* Bewijs van inschrijving in het vreemdelingenregister
*/
FOREIGNER_B("12"),
/**
* Identiteitskaart voor vreemdeling
*/
FOREIGNER_C("13"),
/**
* EG-Langdurig ingezetene
*/
FOREIGNER_D("14"),
/**
* (Verblijfs)kaart van een onderdaan van een lidstaat der EEG Verklaring
* van inschrijving
*/
FOREIGNER_E("15"),
/**
* Document ter staving<SUF>*/
FOREIGNER_E_PLUS("16"),
/**
* Kaart voor niet-EU familieleden van een EU-onderdaan of van een Belg
* Verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F("17"),
/**
* Duurzame verblijfskaart van een familielid van een burger van de Unie
*/
FOREIGNER_F_PLUS("18"),
/**
* H. Europese blauwe kaart. Toegang en verblijf voor onderdanen van derde
* landen.
*/
EUROPEAN_BLUE_CARD_H("19");
private final int key;
private DocumentType(String value) {
this.key = toKey(value);
}
private int toKey(String value) {
char c1 = value.charAt(0);
int key = c1 - '0';
if (2 == value.length()) {
key *= 10;
char c2 = value.charAt(1);
key += c2 - '0';
}
return key;
}
private static int toKey(byte[] value) {
int key = value[0] - '0';
if (2 == value.length) {
key *= 10;
key += value[1] - '0';
}
return key;
}
private static Map<Integer, DocumentType> documentTypes;
static {
Map<Integer, DocumentType> documentTypes = new HashMap<Integer, DocumentType>();
for (DocumentType documentType : DocumentType.values()) {
int encodedValue = documentType.key;
if (documentTypes.containsKey(encodedValue)) {
throw new RuntimeException("duplicate document type enum: "
+ encodedValue);
}
documentTypes.put(encodedValue, documentType);
}
DocumentType.documentTypes = documentTypes;
}
public int getKey() {
return this.key;
}
public static DocumentType toDocumentType(byte[] value) {
int key = toKey(value);
DocumentType documentType = DocumentType.documentTypes.get(key);
/*
* If the key is unknown, we simply return null.
*/
return documentType;
}
public static String toString(byte[] documentTypeValue) {
String str = Integer.toString(toKey(documentTypeValue));
return str;
}
}
|
79924_0 | package io.github.repir.Retriever;
import io.github.repir.Repository.ReportableFeature;
import io.github.htools.lib.Log;
/**
*
* @author Jeroen Vuurens
*/
public class ReportedFeature<F extends ReportableFeature> {
public static Log log = new Log(ReportedFeature.class);
public String canonicalname;
public F feature;
public int reportID;
public ReportedFeature(String canonicalname, ReportableFeature f) {
this.canonicalname = canonicalname;
this.feature = (F) f;
}
public ReportedFeature(ReportedFeature f) {
this.canonicalname = f.canonicalname;
this.feature = (F) f.feature;
this.reportID = f.reportID;
}
@Override
public int hashCode() {
return canonicalname.hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof String) && ((String) o).equals(canonicalname) || (o instanceof ReportableFeature) && ((ReportableFeature) o).getCanonicalName().equals(canonicalname) || (o instanceof ReportedFeature) && ((ReportedFeature) o).canonicalname.equals(canonicalname);
}
}
| repir/repir | src/main/java/io/github/repir/Retriever/ReportedFeature.java | 330 | /**
*
* @author Jeroen Vuurens
*/ | block_comment | nl | package io.github.repir.Retriever;
import io.github.repir.Repository.ReportableFeature;
import io.github.htools.lib.Log;
/**
*
* @author Jeroen Vuurens<SUF>*/
public class ReportedFeature<F extends ReportableFeature> {
public static Log log = new Log(ReportedFeature.class);
public String canonicalname;
public F feature;
public int reportID;
public ReportedFeature(String canonicalname, ReportableFeature f) {
this.canonicalname = canonicalname;
this.feature = (F) f;
}
public ReportedFeature(ReportedFeature f) {
this.canonicalname = f.canonicalname;
this.feature = (F) f.feature;
this.reportID = f.reportID;
}
@Override
public int hashCode() {
return canonicalname.hashCode();
}
@Override
public boolean equals(Object o) {
return (o instanceof String) && ((String) o).equals(canonicalname) || (o instanceof ReportableFeature) && ((ReportableFeature) o).getCanonicalName().equals(canonicalname) || (o instanceof ReportedFeature) && ((ReportedFeature) o).canonicalname.equals(canonicalname);
}
}
|
79927_0 | package io.github.repir.RetrieverSpeed;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
import io.github.htools.io.buffer.BufferDelayedWriter;
import io.github.htools.io.buffer.BufferReaderWriter;
import io.github.htools.lib.Log;
/**
*
* @author Jeroen Vuurens
*/
public class RecordedTime implements WritableComparable<RecordedTime> {
public static Log log = new Log( RecordedTime.class );
public String strategy;
public int query;
public double time = -1;
public RecordedTime() {}
public void write(DataOutput out) throws IOException {
BufferDelayedWriter writer = new BufferDelayedWriter();
writer.write( strategy );
writer.write( query );
writer.write(time);
writer.writeBuffer(out);
}
public void readFields(DataInput in) throws IOException {
BufferReaderWriter reader = new BufferReaderWriter(in);
strategy = reader.readString();
query = reader.readInt();
time = reader.readDouble();
}
public int compareTo(RecordedTime o) {
return 0;
}
}
| repir/repirproximity | src/main/java/io/github/repir/RetrieverSpeed/RecordedTime.java | 352 | /**
*
* @author Jeroen Vuurens
*/ | block_comment | nl | package io.github.repir.RetrieverSpeed;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.WritableComparable;
import io.github.htools.io.buffer.BufferDelayedWriter;
import io.github.htools.io.buffer.BufferReaderWriter;
import io.github.htools.lib.Log;
/**
*
* @author Jeroen Vuurens<SUF>*/
public class RecordedTime implements WritableComparable<RecordedTime> {
public static Log log = new Log( RecordedTime.class );
public String strategy;
public int query;
public double time = -1;
public RecordedTime() {}
public void write(DataOutput out) throws IOException {
BufferDelayedWriter writer = new BufferDelayedWriter();
writer.write( strategy );
writer.write( query );
writer.write(time);
writer.writeBuffer(out);
}
public void readFields(DataInput in) throws IOException {
BufferReaderWriter reader = new BufferReaderWriter(in);
strategy = reader.readString();
query = reader.readInt();
time = reader.readDouble();
}
public int compareTo(RecordedTime o) {
return 0;
}
}
|
114081_10 | package h04PacMan;
/*
* PacMan laten bewegen
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PacMan extends JPanel implements ActionListener {
private int horizontalePlaats = 250; // x location
private int verticalePlaats = 150; // y location
private int richtingEnSnelheid = 10; // speed
private final int WACHTTIJD = 500; // DELAY
int diameter; //radius of pacman
int direction; // view of pacman
int waarde; //direction pacman is going
final int ghostSpeed = 10; // speed of ghost
public PacMan() {
// create timer and start timer
javax.swing.Timer autoKlik = new javax.swing.Timer(WACHTTIJD, this);
autoKlik.start();
}
public int getHorPlaats() {
return horizontalePlaats;
}
// current y positie
public int getVerPlaats() {
return verticalePlaats;
}
// speed and way;
public int getRichtingEnSnelheid() {
return richtingEnSnelheid;
}
// new x position
public void setHorPlaats(int nieuweHorPlaats) {
if(nieuweHorPlaats > getWidth()) {
nieuweHorPlaats = 0;
}
else if(nieuweHorPlaats < 0) {
nieuweHorPlaats = getWidth();
}
horizontalePlaats = nieuweHorPlaats;
}
// new y position
public void setVerPlaats(int nieuweVerPlaats) {
if(nieuweVerPlaats > getHeight()) {
nieuweVerPlaats = 0;
}
else if(nieuweVerPlaats < 0) {
nieuweVerPlaats = getHeight();
}
verticalePlaats = nieuweVerPlaats;
}
public void setRichtingEnSnelheid(int nieuweRichtingEnSnelheid) {
richtingEnSnelheid = nieuweRichtingEnSnelheid;
}
//movement
public void setBesturing(int besturing) {
waarde = besturing;
if(waarde == 0) {
setHorPlaats( getHorPlaats() + richtingEnSnelheid);
}
else if(waarde == 1){
setVerPlaats( getVerPlaats() + richtingEnSnelheid);
}
}
public void setView(int view) {
direction = view;
}
public int getView() {
return direction;
}
@Override
public void actionPerformed(ActionEvent e) {
setBesturing(waarde);
//System.out.println(waarde);
repaint();
}
DrawPacMan pacman = new DrawPacMan();
DrawGhost ghost = new DrawGhost();
int g1x = 50;
boolean g1r = true;
/*
* Direction van ghost bepalen
*/
public void moveUp() {
}
public void moveLeft() {
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
}
public void moveRight() {
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
}
public void moveDown() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// pacman movement
diameter = 25;
pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow);
// ghosts movement
g1x += ghostSpeed * (Math.random() > 0.5? 1 : -1); // random direction
Random randomGen = new Random();
// generate a random number, between 0 - 3
int randomize = randomGen.nextInt(4);
switch(randomize) {
case 0:
moveUp();
System.out.println("up");
break;
case 1:
moveLeft();
System.out.println("Left");
break;
case 2:
moveRight();
System.out.println("Right");
break;
case 3:
moveDown();
System.out.println("down");
break;
}
ghost.drawGhost(g, randomize, 40, diameter, Color.red);
}
}
| reshadf/Java | DeBasis/src/h04PacMan/PacMan.java | 1,387 | /*
* Direction van ghost bepalen
*/ | block_comment | nl | package h04PacMan;
/*
* PacMan laten bewegen
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class PacMan extends JPanel implements ActionListener {
private int horizontalePlaats = 250; // x location
private int verticalePlaats = 150; // y location
private int richtingEnSnelheid = 10; // speed
private final int WACHTTIJD = 500; // DELAY
int diameter; //radius of pacman
int direction; // view of pacman
int waarde; //direction pacman is going
final int ghostSpeed = 10; // speed of ghost
public PacMan() {
// create timer and start timer
javax.swing.Timer autoKlik = new javax.swing.Timer(WACHTTIJD, this);
autoKlik.start();
}
public int getHorPlaats() {
return horizontalePlaats;
}
// current y positie
public int getVerPlaats() {
return verticalePlaats;
}
// speed and way;
public int getRichtingEnSnelheid() {
return richtingEnSnelheid;
}
// new x position
public void setHorPlaats(int nieuweHorPlaats) {
if(nieuweHorPlaats > getWidth()) {
nieuweHorPlaats = 0;
}
else if(nieuweHorPlaats < 0) {
nieuweHorPlaats = getWidth();
}
horizontalePlaats = nieuweHorPlaats;
}
// new y position
public void setVerPlaats(int nieuweVerPlaats) {
if(nieuweVerPlaats > getHeight()) {
nieuweVerPlaats = 0;
}
else if(nieuweVerPlaats < 0) {
nieuweVerPlaats = getHeight();
}
verticalePlaats = nieuweVerPlaats;
}
public void setRichtingEnSnelheid(int nieuweRichtingEnSnelheid) {
richtingEnSnelheid = nieuweRichtingEnSnelheid;
}
//movement
public void setBesturing(int besturing) {
waarde = besturing;
if(waarde == 0) {
setHorPlaats( getHorPlaats() + richtingEnSnelheid);
}
else if(waarde == 1){
setVerPlaats( getVerPlaats() + richtingEnSnelheid);
}
}
public void setView(int view) {
direction = view;
}
public int getView() {
return direction;
}
@Override
public void actionPerformed(ActionEvent e) {
setBesturing(waarde);
//System.out.println(waarde);
repaint();
}
DrawPacMan pacman = new DrawPacMan();
DrawGhost ghost = new DrawGhost();
int g1x = 50;
boolean g1r = true;
/*
* Direction van ghost<SUF>*/
public void moveUp() {
}
public void moveLeft() {
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
}
public void moveRight() {
if (g1x >= 500) { g1x = 500; g1r = false; }
else if (g1x <= 0) { g1x = 0; g1r = true; }
}
public void moveDown() {
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
// pacman movement
diameter = 25;
pacman.drawPacMan(g, getHorPlaats(), getVerPlaats(), diameter, getView(), Color.yellow);
// ghosts movement
g1x += ghostSpeed * (Math.random() > 0.5? 1 : -1); // random direction
Random randomGen = new Random();
// generate a random number, between 0 - 3
int randomize = randomGen.nextInt(4);
switch(randomize) {
case 0:
moveUp();
System.out.println("up");
break;
case 1:
moveLeft();
System.out.println("Left");
break;
case 2:
moveRight();
System.out.println("Right");
break;
case 3:
moveDown();
System.out.println("down");
break;
}
ghost.drawGhost(g, randomize, 40, diameter, Color.red);
}
}
|
63166_7 | import ........
// Bestudeer de code. Raadpleeg daar waar nodig is de API.
// Beantwoord de vragen .. zie commentaar bij de code.
public class ValBewegingPaneel extends JPanel
{
private int startX, startY;
private int eindX, eindY;
private final int PARTS = 12; // hoezo 12?
private Stroke s_new;
public ValBewegingPaneel(ValBewegingApp frame, ControlePaneelNoord noordpaneel)
{
setLayout (null); // waarom?
float [] dashes = {3.0f,7.0f}; // wat gebeurt hier?
s_new = new BasicStroke(0.5f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,1.0f,dashes,0);
// leg uit!
Bal bal = new Bal ();
BalView balview = new BalView (bal, this, noordpaneel); // waarom worden ook het (dit) paneel en het noordpaneel
// doorgegeven aan het balview-object?
BalController controller = new BalController (bal, balview, this, noordpaneel); // idem maar nu aan het controller-object?
add (balview);
ControlePaneelZuid zuidpaneel = new ControlePaneelZuid (bal, balview, controller);
frame.add (zuidpaneel, BorderLayout.SOUTH);
// Waarom wordt het zuidpaneel-object niet (net als het noordpaneel object aangamaakt in het frame-object?
}
public void paintComponent (Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr; // wat gebeurt hier en waarom?
startX = getWidth() / PARTS; // in pixels
startY = getHeight() / PARTS; //
eindX = (PARTS - 1) * startX; //
eindY = (PARTS - 1) * startY; //
g.setColor (Color.BLACK);
g.drawLine (startX, startY, eindX, startY);
g.setStroke(s_new);
for (int te = 2; te <= (PARTS - 2); te++)
{
g.drawLine (startX, te * startY, eindX, te * startY);
g.drawLine (te * startX, startY, te * startX, eindY);
}
g.setStroke(new BasicStroke());
g.drawLine (startX, eindY, eindX, eindY);
g.setColor (Color.BLUE);
g.drawString ("0", startX - 10, startY + 10);
}
// start getters
public int getStartX()
{
return (startX);
}
public int getStartY()
{
return (startY);
}
public int getEindX()
{
return (eindX);
}
public int getEindY()
{
return (eindY);
}
public int getPARTS()
{
return (PARTS);
}
// end getters
}
| reshadf/Oefeningen | src/ValBewegingPaneel.java | 955 | // Waarom wordt het zuidpaneel-object niet (net als het noordpaneel object aangamaakt in het frame-object? | line_comment | nl | import ........
// Bestudeer de code. Raadpleeg daar waar nodig is de API.
// Beantwoord de vragen .. zie commentaar bij de code.
public class ValBewegingPaneel extends JPanel
{
private int startX, startY;
private int eindX, eindY;
private final int PARTS = 12; // hoezo 12?
private Stroke s_new;
public ValBewegingPaneel(ValBewegingApp frame, ControlePaneelNoord noordpaneel)
{
setLayout (null); // waarom?
float [] dashes = {3.0f,7.0f}; // wat gebeurt hier?
s_new = new BasicStroke(0.5f,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,1.0f,dashes,0);
// leg uit!
Bal bal = new Bal ();
BalView balview = new BalView (bal, this, noordpaneel); // waarom worden ook het (dit) paneel en het noordpaneel
// doorgegeven aan het balview-object?
BalController controller = new BalController (bal, balview, this, noordpaneel); // idem maar nu aan het controller-object?
add (balview);
ControlePaneelZuid zuidpaneel = new ControlePaneelZuid (bal, balview, controller);
frame.add (zuidpaneel, BorderLayout.SOUTH);
// Waarom wordt<SUF>
}
public void paintComponent (Graphics gr)
{
super.paintComponent(gr);
Graphics2D g = (Graphics2D) gr; // wat gebeurt hier en waarom?
startX = getWidth() / PARTS; // in pixels
startY = getHeight() / PARTS; //
eindX = (PARTS - 1) * startX; //
eindY = (PARTS - 1) * startY; //
g.setColor (Color.BLACK);
g.drawLine (startX, startY, eindX, startY);
g.setStroke(s_new);
for (int te = 2; te <= (PARTS - 2); te++)
{
g.drawLine (startX, te * startY, eindX, te * startY);
g.drawLine (te * startX, startY, te * startX, eindY);
}
g.setStroke(new BasicStroke());
g.drawLine (startX, eindY, eindX, eindY);
g.setColor (Color.BLUE);
g.drawString ("0", startX - 10, startY + 10);
}
// start getters
public int getStartX()
{
return (startX);
}
public int getStartY()
{
return (startY);
}
public int getEindX()
{
return (eindX);
}
public int getEindY()
{
return (eindY);
}
public int getPARTS()
{
return (PARTS);
}
// end getters
}
|
207401_5 | package views;
import controllers.AccountController;
import helpers.MenuButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* User: Reinier Koops
* Class: View, shows what the user sees (and gets its info through the controller)
*/
public class AccessView extends IpsenView implements ActionListener
{
private AccountController controller;
private JTable table;
private JButton btnRightGrp, btnRight, btnAccount, btnStatistics;
private JPanel topPanel;
/**
* Class Constructor
* @param controller Account Controller
*/
public AccessView(AccountController controller) // controller mist
{
//link aan betreffende controller
this.setLayout( new BorderLayout() );
topPanel = new JPanel();
topPanel.setPreferredSize( new Dimension( 1000, 68 ) );
//buttons afbeelding nog toewijzen
btnRight = new MenuButton( "assets/rechten.png", null, null );
btnRightGrp = new MenuButton( "assets/nw_rightgroep_btn.png", null, null );
btnAccount = new MenuButton( "assets/accounts.png", null, null );
btnStatistics = new MenuButton( "assets/statistiek_inzien", null, null );
//buttons laten werken als je erop klikt
btnRight.addActionListener( this );
btnAccount.addActionListener( this );
btnRightGrp.addActionListener( this );
btnStatistics.addActionListener( this );
//buttons toevoegen aan het topPanel
this.topPanel.add( btnRight );
this.topPanel.add( btnRightGrp );
this.topPanel.add( btnAccount );
this.topPanel.add( btnStatistics );
this.add( topPanel, BorderLayout.NORTH );
}
/**
* Method to actionPerformed changes the view, by using the controller and displaying the next view
*
* the actionPerfomed performs no action in this class only showing the buttons
*/
@Override
public void actionPerformed( ActionEvent e )
{
Object s = e.getSource();
if (s == btnRight)
{
//Right button geselecteerd -> ga naar dit submenu
// AccessRightView accesRightView;
// {
// accesRightView = new AccessRightView();
// }
}
if (s == btnRightGrp)
{
//Rightgroup button geselecteerd -> ga naar dit submenu
// AccessRightGroupView accesRightGroupView;
// {
// accesRightGroupView = new AccessRightGroupView();
// }
}
if (s == btnAccount)
{
//Account button geselecteerd -> ga naar dit submenu
// AccesAccountView accesAccountView;
// {
// accesAccountView = new AccesAccountView();
// }
}
if (s == btnStatistics)
{
//Statistics button geselecteerd -> ga naar dit submenu
// AccessStatisticsView accesStatisticsView;
// {
// accesStatisticsView = new AccessStatisticsView();
// }
}
}
}
| reshadf/ipsen3-app | src/views/AccessView.java | 925 | //buttons toevoegen aan het topPanel
| line_comment | nl | package views;
import controllers.AccountController;
import helpers.MenuButton;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* User: Reinier Koops
* Class: View, shows what the user sees (and gets its info through the controller)
*/
public class AccessView extends IpsenView implements ActionListener
{
private AccountController controller;
private JTable table;
private JButton btnRightGrp, btnRight, btnAccount, btnStatistics;
private JPanel topPanel;
/**
* Class Constructor
* @param controller Account Controller
*/
public AccessView(AccountController controller) // controller mist
{
//link aan betreffende controller
this.setLayout( new BorderLayout() );
topPanel = new JPanel();
topPanel.setPreferredSize( new Dimension( 1000, 68 ) );
//buttons afbeelding nog toewijzen
btnRight = new MenuButton( "assets/rechten.png", null, null );
btnRightGrp = new MenuButton( "assets/nw_rightgroep_btn.png", null, null );
btnAccount = new MenuButton( "assets/accounts.png", null, null );
btnStatistics = new MenuButton( "assets/statistiek_inzien", null, null );
//buttons laten werken als je erop klikt
btnRight.addActionListener( this );
btnAccount.addActionListener( this );
btnRightGrp.addActionListener( this );
btnStatistics.addActionListener( this );
//buttons toevoegen<SUF>
this.topPanel.add( btnRight );
this.topPanel.add( btnRightGrp );
this.topPanel.add( btnAccount );
this.topPanel.add( btnStatistics );
this.add( topPanel, BorderLayout.NORTH );
}
/**
* Method to actionPerformed changes the view, by using the controller and displaying the next view
*
* the actionPerfomed performs no action in this class only showing the buttons
*/
@Override
public void actionPerformed( ActionEvent e )
{
Object s = e.getSource();
if (s == btnRight)
{
//Right button geselecteerd -> ga naar dit submenu
// AccessRightView accesRightView;
// {
// accesRightView = new AccessRightView();
// }
}
if (s == btnRightGrp)
{
//Rightgroup button geselecteerd -> ga naar dit submenu
// AccessRightGroupView accesRightGroupView;
// {
// accesRightGroupView = new AccessRightGroupView();
// }
}
if (s == btnAccount)
{
//Account button geselecteerd -> ga naar dit submenu
// AccesAccountView accesAccountView;
// {
// accesAccountView = new AccesAccountView();
// }
}
if (s == btnStatistics)
{
//Statistics button geselecteerd -> ga naar dit submenu
// AccessStatisticsView accesStatisticsView;
// {
// accesStatisticsView = new AccessStatisticsView();
// }
}
}
}
|
105574_2 | /*
* Copyright (C) 2007 Danilo Couto, Philippe Eberli,
* Pascal Hobus, Reto Schüttel, Robin Stocker
*
* This file is part of Bodesuri.
*
* Bodesuri is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Bodesuri 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 Bodesuri; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package ch.bodesuri.ui.geteiltes;
import java.awt.Point;
import javax.swing.Icon;
import javax.swing.JLabel;
/**
* Diese Klasse kümmert sich um die Positionierung der Bildelemente auf dem Spielfeld.
* Es ermöglicht ein Bild zentriert auf einen Koordinatenpunkt zu setzten.
*/
public class BLabel extends JLabel {
private final int dxFinal;
private final int dyFinal;
private final Point relativerMittelpunkt;
private Point absoluterMittelpunkt;
public BLabel(Icon icon) {
this(icon, 0, 0);
}
/**
* Konstrukor mit Icon, X-Koordinaten und Y-Koordinaten
*
* @param icon Bild des Labels
* @param dx X-Koordinate des Labels
* @param dy Y-Koordinate des Labels
*/
public BLabel(Icon icon, int dx, int dy) {
super(icon);
int width = icon.getIconWidth();
int height = icon.getIconHeight();
this.dxFinal = (width / 2) + dx;
this.dyFinal = (height / 2) + dy;
setSize(width, height); /* TONIGHT WE SWING IN HELL */
this.absoluterMittelpunkt = getLocation();
this.relativerMittelpunkt = new Point(width / 2, height /2);
}
/**
* Konstruktor mit Icon und Point(x,y)
*
* @param icon Bild des Labels
* @param p Koordinatenpunkt als Point(x,y)
*/
public BLabel(Icon icon, Point p) {
this(icon, 0, 0);
zentriereAuf(p);
}
/**
* Das Labeld wird auf diesen Punkt zentriert platziert.
*
* @param position Position, auf dem das Bild zentriert wird.
*/
public void zentriereAuf(Point position) {
absoluterMittelpunkt = position;
setLocation(position.x - dxFinal, position.y - dyFinal);
}
/**
* Das Label wird auf diesem Punkt zentriert platziert.
*
* @param x X-Koordinate der Positionierung.
* @param y Y-Koordinate der Positionierung.
*/
private void zentriereAuf(int x, int y) {
absoluterMittelpunkt = new Point(x, y);
setLocation(x - dxFinal, y - dyFinal);
}
/**
* Das Label wird zur Koordinate Point(x,y) bewegt.
*
* @param ziel Koordinatenpunkt, wohin das Label bewegt wird.
*/
public void bewegeNach(Point ziel) {
Point start = absoluterMittelpunkt;
double distanz = start.distance(ziel);
int steps = (int) Math.round(distanz / 20);
double dx = ziel.x - start.x;
double dy = ziel.y - start.y;
double stepX = dx / steps;
double stepY = dy / steps;
for (int i = 1; i <= steps; i++) {
int curX = start.x + (int) Math.round(i * stepX);
int curY = start.y + (int) Math.round(i * stepY);
zentriereAuf(curX, curY);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
zentriereAuf(ziel);
}
public Point getRelativerMittelpunkt() {
return relativerMittelpunkt;
}
}
| retoo/bodesuri | src/ch/bodesuri/ui/geteiltes/BLabel.java | 1,220 | /**
* Konstrukor mit Icon, X-Koordinaten und Y-Koordinaten
*
* @param icon Bild des Labels
* @param dx X-Koordinate des Labels
* @param dy Y-Koordinate des Labels
*/ | block_comment | nl | /*
* Copyright (C) 2007 Danilo Couto, Philippe Eberli,
* Pascal Hobus, Reto Schüttel, Robin Stocker
*
* This file is part of Bodesuri.
*
* Bodesuri is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* Bodesuri 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 Bodesuri; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package ch.bodesuri.ui.geteiltes;
import java.awt.Point;
import javax.swing.Icon;
import javax.swing.JLabel;
/**
* Diese Klasse kümmert sich um die Positionierung der Bildelemente auf dem Spielfeld.
* Es ermöglicht ein Bild zentriert auf einen Koordinatenpunkt zu setzten.
*/
public class BLabel extends JLabel {
private final int dxFinal;
private final int dyFinal;
private final Point relativerMittelpunkt;
private Point absoluterMittelpunkt;
public BLabel(Icon icon) {
this(icon, 0, 0);
}
/**
* Konstrukor mit Icon,<SUF>*/
public BLabel(Icon icon, int dx, int dy) {
super(icon);
int width = icon.getIconWidth();
int height = icon.getIconHeight();
this.dxFinal = (width / 2) + dx;
this.dyFinal = (height / 2) + dy;
setSize(width, height); /* TONIGHT WE SWING IN HELL */
this.absoluterMittelpunkt = getLocation();
this.relativerMittelpunkt = new Point(width / 2, height /2);
}
/**
* Konstruktor mit Icon und Point(x,y)
*
* @param icon Bild des Labels
* @param p Koordinatenpunkt als Point(x,y)
*/
public BLabel(Icon icon, Point p) {
this(icon, 0, 0);
zentriereAuf(p);
}
/**
* Das Labeld wird auf diesen Punkt zentriert platziert.
*
* @param position Position, auf dem das Bild zentriert wird.
*/
public void zentriereAuf(Point position) {
absoluterMittelpunkt = position;
setLocation(position.x - dxFinal, position.y - dyFinal);
}
/**
* Das Label wird auf diesem Punkt zentriert platziert.
*
* @param x X-Koordinate der Positionierung.
* @param y Y-Koordinate der Positionierung.
*/
private void zentriereAuf(int x, int y) {
absoluterMittelpunkt = new Point(x, y);
setLocation(x - dxFinal, y - dyFinal);
}
/**
* Das Label wird zur Koordinate Point(x,y) bewegt.
*
* @param ziel Koordinatenpunkt, wohin das Label bewegt wird.
*/
public void bewegeNach(Point ziel) {
Point start = absoluterMittelpunkt;
double distanz = start.distance(ziel);
int steps = (int) Math.round(distanz / 20);
double dx = ziel.x - start.x;
double dy = ziel.y - start.y;
double stepX = dx / steps;
double stepY = dy / steps;
for (int i = 1; i <= steps; i++) {
int curX = start.x + (int) Math.round(i * stepX);
int curY = start.y + (int) Math.round(i * stepY);
zentriereAuf(curX, curY);
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
zentriereAuf(ziel);
}
public Point getRelativerMittelpunkt() {
return relativerMittelpunkt;
}
}
|
12491_4 | package com.epic.score_app.viewlayer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.epic.score_app.serviceslayer.ServiceProvider;
import com.epic.score_app.view.R;
import domainmodel.Player;
public class ViewPlayer extends ActionBarActivity {
private Player player;
private String vn, an, nat, lf, gb, ps, hg, wg, ft;
private TextView voornaam, achternaam, nationaliteit, leeftijd,
geboortedatum, positie, height, weight, foot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_player);
Intent intent = getIntent();
Bundle b = intent.getExtras();
player= (Player)b.getSerializable("player");
voornaam = (TextView) findViewById(R.id.voornaam);
achternaam = (TextView) findViewById(R.id.achternaam);
nationaliteit = (TextView) findViewById(R.id.nationality);
leeftijd = (TextView) findViewById(R.id.leeftijd);
geboortedatum = (TextView) findViewById(R.id.date_of_birth);
positie = (TextView) findViewById(R.id.position);
height = (TextView) findViewById(R.id.height);
weight = (TextView) findViewById(R.id.weight);
foot = (TextView) findViewById(R.id.foot);
}
@Override
protected void onStart() {
Bundle b = new Bundle();
b.putInt("requestcode", ServiceProvider.getLazyPlayer);
b.putLong("player_id", player.getPlayer_id());
ServiceProvider.getInsance().getData(b,handler);
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.view_player, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case ServiceProvider.getLazyPlayer_response:
Player temp = (Player) msg.obj;
vn = player.getName();
an = player.getLastname();
nat = player.getNationality();
lf=temp.getAge();
gb=temp.getDateOfbirth();
ft=temp.getFoot();
hg=temp.getHeight();
wg=temp.getWeight();
if(wg == "null"){
wg = "GEEN GEWICHT BEKEND";
weight.setText(wg);
}else{
weight.setText(wg);
}
ps=temp.getPosition();
if(vn == "null"){
voornaam.setText("GEEN VOORNAAM BEKEND");
}else{
voornaam.setText(vn);
}
if(an == "null"){
achternaam.setText("ACHTERNAAM NIET BEKEND");
}else{
achternaam.setText(an);
}
if(nat == "null"){
nationaliteit.setText("NATIONALITEIT NIET BEKEND");
}else {
nationaliteit.setText(nat);
}
if(lf == "null"){
leeftijd.setText("LEEFTIJD NIET BEKEND");
}else{
leeftijd.setText(lf);
}
if(gb == "null"){
geboortedatum.setText("GEBOORTEDATUM NIET BEKEND");
}else{
geboortedatum.setText(gb);
}
if(ps == "null"){
positie.setText("POSITIE NIET BEKEND");
}else{
positie.setText(ps);
}
if(hg == "null"){
height.setText("LENGTE NIET BEKEND");
}else{
height.setText(hg);
}
if(ft == "null"){
foot.setText("NIET BEKEND");
}else{
foot.setText(ft);
}
//hier moet je de andere atributen can de speler toevoegrn
break;
default:
break;
}
};
};
}
| reuben313/Score_app | src/com/epic/score_app/viewlayer/ViewPlayer.java | 1,463 | //hier moet je de andere atributen can de speler toevoegrn | line_comment | nl | package com.epic.score_app.viewlayer;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import com.epic.score_app.serviceslayer.ServiceProvider;
import com.epic.score_app.view.R;
import domainmodel.Player;
public class ViewPlayer extends ActionBarActivity {
private Player player;
private String vn, an, nat, lf, gb, ps, hg, wg, ft;
private TextView voornaam, achternaam, nationaliteit, leeftijd,
geboortedatum, positie, height, weight, foot;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_player);
Intent intent = getIntent();
Bundle b = intent.getExtras();
player= (Player)b.getSerializable("player");
voornaam = (TextView) findViewById(R.id.voornaam);
achternaam = (TextView) findViewById(R.id.achternaam);
nationaliteit = (TextView) findViewById(R.id.nationality);
leeftijd = (TextView) findViewById(R.id.leeftijd);
geboortedatum = (TextView) findViewById(R.id.date_of_birth);
positie = (TextView) findViewById(R.id.position);
height = (TextView) findViewById(R.id.height);
weight = (TextView) findViewById(R.id.weight);
foot = (TextView) findViewById(R.id.foot);
}
@Override
protected void onStart() {
Bundle b = new Bundle();
b.putInt("requestcode", ServiceProvider.getLazyPlayer);
b.putLong("player_id", player.getPlayer_id());
ServiceProvider.getInsance().getData(b,handler);
super.onStart();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.view_player, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case ServiceProvider.getLazyPlayer_response:
Player temp = (Player) msg.obj;
vn = player.getName();
an = player.getLastname();
nat = player.getNationality();
lf=temp.getAge();
gb=temp.getDateOfbirth();
ft=temp.getFoot();
hg=temp.getHeight();
wg=temp.getWeight();
if(wg == "null"){
wg = "GEEN GEWICHT BEKEND";
weight.setText(wg);
}else{
weight.setText(wg);
}
ps=temp.getPosition();
if(vn == "null"){
voornaam.setText("GEEN VOORNAAM BEKEND");
}else{
voornaam.setText(vn);
}
if(an == "null"){
achternaam.setText("ACHTERNAAM NIET BEKEND");
}else{
achternaam.setText(an);
}
if(nat == "null"){
nationaliteit.setText("NATIONALITEIT NIET BEKEND");
}else {
nationaliteit.setText(nat);
}
if(lf == "null"){
leeftijd.setText("LEEFTIJD NIET BEKEND");
}else{
leeftijd.setText(lf);
}
if(gb == "null"){
geboortedatum.setText("GEBOORTEDATUM NIET BEKEND");
}else{
geboortedatum.setText(gb);
}
if(ps == "null"){
positie.setText("POSITIE NIET BEKEND");
}else{
positie.setText(ps);
}
if(hg == "null"){
height.setText("LENGTE NIET BEKEND");
}else{
height.setText(hg);
}
if(ft == "null"){
foot.setText("NIET BEKEND");
}else{
foot.setText(ft);
}
//hier moet<SUF>
break;
default:
break;
}
};
};
}
|
172125_7 | //function 1 score:
//function 2 score:
//function 3 score:
import org.vu.contest.ContestSubmission;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.vu.contest.ContestEvaluation;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.Properties;
public class player17 implements ContestSubmission
{
final static int POPULATION_SIZE = 20; //individuals, moet altijd deelbaar door 2 zijn
final static int NUMBER_OF_POPULATIONS = 10; //wordt nog niet gebruikt
final static int PARENTS_SURVIVE = 10; //number of parents that survive into the next generation
final static int NUMBER_OF_MUTATIONS = 1;
final static boolean ONLY_MUTANTS = true; //wel of niet alleen mutanten als kinderen toeveogen aan nieuwe gen
final static int RANDOM_MUTATION_CHANCE = 5; //procent kans dat een gen totaal random muteert
final static int RANDOMS_ADDED = 11; //aantal individuen dat random wordt vervangen bij te lage variance
final static double VARIANCE_TRESHOLD = 5d; //waarde van variance in fitness waarbij individuen worden vervangen door randoms
ArrayList<Individual> population;
private Random rnd_;
private ContestEvaluation evaluation_;
private int evaluations_limit_;
JFreeChart chart;
XYSeriesCollection dataset;
int column;
public player17()
{
rnd_ = new Random();
population = new ArrayList<Individual>();
dataset = new XYSeriesCollection();
column = 0;
}
public void setSeed(long seed)
{
// Set seed of algortihms random process
rnd_.setSeed(seed);
}
public void setEvaluation(ContestEvaluation evaluation)
{
// Set evaluation problem used in the run
evaluation_ = evaluation;
// Get evaluation properties
Properties props = evaluation.getProperties();
evaluations_limit_ = Integer.parseInt(props.getProperty("Evaluations"));
boolean isMultimodal = Boolean.parseBoolean(props.getProperty("Multimodal"));
boolean hasStructure = Boolean.parseBoolean(props.getProperty("GlobalStructure"));
boolean isSeparable = Boolean.parseBoolean(props.getProperty("Separable"));
// Change settings(?)
if(isMultimodal){
// Do sth
}else{
// Do sth else
}
}
public void run()
{
// Run your algorithm here
//set random values for starting array
int evals = 1;
initPopulation();
while(evals<evaluations_limit_/POPULATION_SIZE)
{
makeNewPopulation();
Iterator<Individual> iterator = population.iterator();
XYSeries series = new XYSeries(""+column);
while(iterator.hasNext())
{
double fitness = iterator.next().fitness.doubleValue();
series.add(column, fitness);
}
column++;
dataset.addSeries(series);
System.out.println("best fitness: " + population.get(0).fitness + " worst fitness: " + population.get(19).fitness + " evals: " + evals + " individual vatriance: " + computeIndividualVariance());
if( computeIndividualVariance() < VARIANCE_TRESHOLD)
{
addRandomsToPopulation();
}
evals++;
}
//maak een plot op scherm, dit uitzetten bij inleveren
chart = ChartFactory.createScatterPlot(
"Plot 1", // chart title
"Evals", // domain axis label
"Fitness", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
ChartFrame frame = new ChartFrame("First", chart);
frame.pack();
frame.setVisible(true);
}
private void addRandomsToPopulation()
{
int initSize = population.size();
Random rand = new Random();
while (population.size() >= initSize-RANDOMS_ADDED)
{
int removePos = rand.nextInt(population.size());
population.remove(removePos);
}
while (population.size() < initSize)
{
Individual ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
addToPopulationSorted(ind, population);
}
}
double computeFitnessVariance()
{
double output = 0;
double numberOfIndividuals = 0;
Iterator<Individual> iterator = population.iterator();
while(iterator.hasNext())
{
output += iterator.next().fitness;
numberOfIndividuals++;
}
double mean = output/numberOfIndividuals; //get mean
output = 0;
iterator = population.iterator();
while(iterator.hasNext())
{
double fitness = iterator.next().fitness;
output += (mean-fitness) * (mean-fitness);
}
return output/numberOfIndividuals;
}
double computeIndividualVariance() //todo
{
double[] meanIndividual = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double[] temp = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double numberOfIndividuals = 0;
Iterator<Individual> iterator = population.iterator();
while(iterator.hasNext())
{
Individual ind = iterator.next();
for(int i = 0; i < 10; i++)
{
meanIndividual[i] += ind.genome[i];
}
numberOfIndividuals++;
}
for(int i = 0; i < 10; i++) //get mean
{
meanIndividual[i] /= numberOfIndividuals;
}
iterator = population.iterator();
while(iterator.hasNext())
{
Individual ind = iterator.next();
for(int i = 0; i < 10; i++)
{
temp[i] += (meanIndividual[i]-ind.genome[i]) * (meanIndividual[i]-ind.genome[i]);
}
}
for(int i = 0; i < 10; i++)
{
temp[i] /= numberOfIndividuals;
}
double output = 0;
for(int i = 0; i < 10; i++)
{
output += temp[i];
}
return output;
}
void makeNewPopulation()
{
Random rand = new Random();
ArrayList<Individual> tempPopulation1 = new ArrayList<Individual>();
ArrayList<Individual> tempPopulation2 = new ArrayList<Individual>();
//split pop in 2
while(tempPopulation1.size()<POPULATION_SIZE/2)
{
tempPopulation1.add(population.remove(rand.nextInt(population.size())));
}
while(tempPopulation2.size()<POPULATION_SIZE/2)
{
tempPopulation2.add(population.remove(rand.nextInt(population.size())));
}
//BATTLE!
while(tempPopulation1.size() > 0)
{
Individual parent1 = tempPopulation1.remove(rand.nextInt(tempPopulation1.size()));
Individual parent2 = tempPopulation2.remove(rand.nextInt(tempPopulation2.size()));
if (parent1.fitness > parent2.fitness)
{
addToPopulationSorted(parent1, population);
}
else
{
addToPopulationSorted(parent2, population);
}
}
while(population.size() > PARENTS_SURVIVE)
{
population.remove(population.size()-1);
}
while(population.size() < POPULATION_SIZE)
{
Individual parent1 = population.get(rand.nextInt(PARENTS_SURVIVE));
Individual parent2 = population.get(rand.nextInt(PARENTS_SURVIVE));
Individual child = crossoverParents(parent1, parent2);
if(!ONLY_MUTANTS)
{
child.fitness = (Double)evaluation_.evaluate(child.genome);
addToPopulationSorted(child, population);
}
Individual mutant = child.clone();
mutateChild(mutant);
mutant.fitness = (Double)evaluation_.evaluate(mutant.genome);
addToPopulationSorted(mutant, population);
}
}
private Individual crossoverParents(Individual parent1, Individual parent2)
{
Random rand = new Random();
Individual child = new Individual();
for(int i = 0; i < parent1.genome.length; i++)
{
if (rand.nextBoolean())
{
child.genome[i] = parent1.genome[i];
}
else
{
child.genome[i] = parent2.genome[i];
}
}
return child;
}
private void mutateChild(Individual child)
{
Random rand = new Random();
int[] mutatePosition = createMutatePositionsArray(NUMBER_OF_MUTATIONS);
for (int i = 0; i < NUMBER_OF_MUTATIONS; i++)
{
double oldValue = child.genome[mutatePosition[i]];
double mutation = rand.nextDouble();
if(rand.nextBoolean())
{
mutation *= -1d;
}
mutation = oldValue + mutation;
if(mutation > 5d)
{
mutation = 5d;
}
else if(mutation < -5d)
{
mutation = -5d;
}
child.genome[mutatePosition[i]] = mutation;
//small change of totaly random mutation
if(rand.nextInt(100) < RANDOM_MUTATION_CHANCE)
{
child.genome[mutatePosition[i]] = ((rand.nextDouble() * 10d) - 5d);
}
}
}
private int[] createMutatePositionsArray(int size)
{
Random rand = new Random();
int[] output = new int[size];
output[0] = rand.nextInt(10);
for (int i = 1; i<size; i++)
{
int newPosition = rand.nextInt(10);
while(arrayContains(output, newPosition, i))
{
newPosition = rand.nextInt(10);
}
output[i] = newPosition;
}
return output;
}
private boolean arrayContains(int[] intArray, int check, int steps)
{
for (int i = 0; i < steps; i++)
{
if (intArray[i] == check)
{
return true;
}
}
return false;
}
public void addToPopulationSorted(Individual input, ArrayList<Individual> pop)
{
int index = 0;
while(index < pop.size() && population.get(index).fitness > input.fitness)
{
index++;
}
pop.add(index, input);
}
public void initPopulation()
{
Individual ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
population.add(ind);
while(population.size() < POPULATION_SIZE)
{
ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
addToPopulationSorted(ind, population);
}
}
}
| reuelbrion/EvolutionaryComputing | EvolutionaryComputing/src/player17.java | 3,384 | //procent kans dat een gen totaal random muteert | line_comment | nl | //function 1 score:
//function 2 score:
//function 3 score:
import org.vu.contest.ContestSubmission;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.vu.contest.ContestEvaluation;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.Properties;
public class player17 implements ContestSubmission
{
final static int POPULATION_SIZE = 20; //individuals, moet altijd deelbaar door 2 zijn
final static int NUMBER_OF_POPULATIONS = 10; //wordt nog niet gebruikt
final static int PARENTS_SURVIVE = 10; //number of parents that survive into the next generation
final static int NUMBER_OF_MUTATIONS = 1;
final static boolean ONLY_MUTANTS = true; //wel of niet alleen mutanten als kinderen toeveogen aan nieuwe gen
final static int RANDOM_MUTATION_CHANCE = 5; //procent kans<SUF>
final static int RANDOMS_ADDED = 11; //aantal individuen dat random wordt vervangen bij te lage variance
final static double VARIANCE_TRESHOLD = 5d; //waarde van variance in fitness waarbij individuen worden vervangen door randoms
ArrayList<Individual> population;
private Random rnd_;
private ContestEvaluation evaluation_;
private int evaluations_limit_;
JFreeChart chart;
XYSeriesCollection dataset;
int column;
public player17()
{
rnd_ = new Random();
population = new ArrayList<Individual>();
dataset = new XYSeriesCollection();
column = 0;
}
public void setSeed(long seed)
{
// Set seed of algortihms random process
rnd_.setSeed(seed);
}
public void setEvaluation(ContestEvaluation evaluation)
{
// Set evaluation problem used in the run
evaluation_ = evaluation;
// Get evaluation properties
Properties props = evaluation.getProperties();
evaluations_limit_ = Integer.parseInt(props.getProperty("Evaluations"));
boolean isMultimodal = Boolean.parseBoolean(props.getProperty("Multimodal"));
boolean hasStructure = Boolean.parseBoolean(props.getProperty("GlobalStructure"));
boolean isSeparable = Boolean.parseBoolean(props.getProperty("Separable"));
// Change settings(?)
if(isMultimodal){
// Do sth
}else{
// Do sth else
}
}
public void run()
{
// Run your algorithm here
//set random values for starting array
int evals = 1;
initPopulation();
while(evals<evaluations_limit_/POPULATION_SIZE)
{
makeNewPopulation();
Iterator<Individual> iterator = population.iterator();
XYSeries series = new XYSeries(""+column);
while(iterator.hasNext())
{
double fitness = iterator.next().fitness.doubleValue();
series.add(column, fitness);
}
column++;
dataset.addSeries(series);
System.out.println("best fitness: " + population.get(0).fitness + " worst fitness: " + population.get(19).fitness + " evals: " + evals + " individual vatriance: " + computeIndividualVariance());
if( computeIndividualVariance() < VARIANCE_TRESHOLD)
{
addRandomsToPopulation();
}
evals++;
}
//maak een plot op scherm, dit uitzetten bij inleveren
chart = ChartFactory.createScatterPlot(
"Plot 1", // chart title
"Evals", // domain axis label
"Fitness", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
ChartFrame frame = new ChartFrame("First", chart);
frame.pack();
frame.setVisible(true);
}
private void addRandomsToPopulation()
{
int initSize = population.size();
Random rand = new Random();
while (population.size() >= initSize-RANDOMS_ADDED)
{
int removePos = rand.nextInt(population.size());
population.remove(removePos);
}
while (population.size() < initSize)
{
Individual ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
addToPopulationSorted(ind, population);
}
}
double computeFitnessVariance()
{
double output = 0;
double numberOfIndividuals = 0;
Iterator<Individual> iterator = population.iterator();
while(iterator.hasNext())
{
output += iterator.next().fitness;
numberOfIndividuals++;
}
double mean = output/numberOfIndividuals; //get mean
output = 0;
iterator = population.iterator();
while(iterator.hasNext())
{
double fitness = iterator.next().fitness;
output += (mean-fitness) * (mean-fitness);
}
return output/numberOfIndividuals;
}
double computeIndividualVariance() //todo
{
double[] meanIndividual = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double[] temp = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
double numberOfIndividuals = 0;
Iterator<Individual> iterator = population.iterator();
while(iterator.hasNext())
{
Individual ind = iterator.next();
for(int i = 0; i < 10; i++)
{
meanIndividual[i] += ind.genome[i];
}
numberOfIndividuals++;
}
for(int i = 0; i < 10; i++) //get mean
{
meanIndividual[i] /= numberOfIndividuals;
}
iterator = population.iterator();
while(iterator.hasNext())
{
Individual ind = iterator.next();
for(int i = 0; i < 10; i++)
{
temp[i] += (meanIndividual[i]-ind.genome[i]) * (meanIndividual[i]-ind.genome[i]);
}
}
for(int i = 0; i < 10; i++)
{
temp[i] /= numberOfIndividuals;
}
double output = 0;
for(int i = 0; i < 10; i++)
{
output += temp[i];
}
return output;
}
void makeNewPopulation()
{
Random rand = new Random();
ArrayList<Individual> tempPopulation1 = new ArrayList<Individual>();
ArrayList<Individual> tempPopulation2 = new ArrayList<Individual>();
//split pop in 2
while(tempPopulation1.size()<POPULATION_SIZE/2)
{
tempPopulation1.add(population.remove(rand.nextInt(population.size())));
}
while(tempPopulation2.size()<POPULATION_SIZE/2)
{
tempPopulation2.add(population.remove(rand.nextInt(population.size())));
}
//BATTLE!
while(tempPopulation1.size() > 0)
{
Individual parent1 = tempPopulation1.remove(rand.nextInt(tempPopulation1.size()));
Individual parent2 = tempPopulation2.remove(rand.nextInt(tempPopulation2.size()));
if (parent1.fitness > parent2.fitness)
{
addToPopulationSorted(parent1, population);
}
else
{
addToPopulationSorted(parent2, population);
}
}
while(population.size() > PARENTS_SURVIVE)
{
population.remove(population.size()-1);
}
while(population.size() < POPULATION_SIZE)
{
Individual parent1 = population.get(rand.nextInt(PARENTS_SURVIVE));
Individual parent2 = population.get(rand.nextInt(PARENTS_SURVIVE));
Individual child = crossoverParents(parent1, parent2);
if(!ONLY_MUTANTS)
{
child.fitness = (Double)evaluation_.evaluate(child.genome);
addToPopulationSorted(child, population);
}
Individual mutant = child.clone();
mutateChild(mutant);
mutant.fitness = (Double)evaluation_.evaluate(mutant.genome);
addToPopulationSorted(mutant, population);
}
}
private Individual crossoverParents(Individual parent1, Individual parent2)
{
Random rand = new Random();
Individual child = new Individual();
for(int i = 0; i < parent1.genome.length; i++)
{
if (rand.nextBoolean())
{
child.genome[i] = parent1.genome[i];
}
else
{
child.genome[i] = parent2.genome[i];
}
}
return child;
}
private void mutateChild(Individual child)
{
Random rand = new Random();
int[] mutatePosition = createMutatePositionsArray(NUMBER_OF_MUTATIONS);
for (int i = 0; i < NUMBER_OF_MUTATIONS; i++)
{
double oldValue = child.genome[mutatePosition[i]];
double mutation = rand.nextDouble();
if(rand.nextBoolean())
{
mutation *= -1d;
}
mutation = oldValue + mutation;
if(mutation > 5d)
{
mutation = 5d;
}
else if(mutation < -5d)
{
mutation = -5d;
}
child.genome[mutatePosition[i]] = mutation;
//small change of totaly random mutation
if(rand.nextInt(100) < RANDOM_MUTATION_CHANCE)
{
child.genome[mutatePosition[i]] = ((rand.nextDouble() * 10d) - 5d);
}
}
}
private int[] createMutatePositionsArray(int size)
{
Random rand = new Random();
int[] output = new int[size];
output[0] = rand.nextInt(10);
for (int i = 1; i<size; i++)
{
int newPosition = rand.nextInt(10);
while(arrayContains(output, newPosition, i))
{
newPosition = rand.nextInt(10);
}
output[i] = newPosition;
}
return output;
}
private boolean arrayContains(int[] intArray, int check, int steps)
{
for (int i = 0; i < steps; i++)
{
if (intArray[i] == check)
{
return true;
}
}
return false;
}
public void addToPopulationSorted(Individual input, ArrayList<Individual> pop)
{
int index = 0;
while(index < pop.size() && population.get(index).fitness > input.fitness)
{
index++;
}
pop.add(index, input);
}
public void initPopulation()
{
Individual ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
population.add(ind);
while(population.size() < POPULATION_SIZE)
{
ind = new Individual();
ind.initializeRandom();
ind.fitness = (Double)evaluation_.evaluate(ind.genome);
addToPopulationSorted(ind, population);
}
}
}
|
40072_1 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.utwente.ewi.caes.lwbdemo.model;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Function extends Term {
final Term[] type;
public Function(Term... arguments) {
if (arguments.length < 2) {
throw new IllegalArgumentException();
}
this.type = arguments;
}
@Override
public StringProperty stringProperty() {
if (string == null) {
string = new SimpleStringProperty();
StringProperty[] stringProperties = new StringProperty[type.length];
for (int i = 0; i < type.length; i++) {
stringProperties[i] = type[i].stringProperty();
}
Object[] concatArgs = new Object[stringProperties.length * 2 + 1];
int i = 0;
concatArgs[i] = "(";
for (i = 1; i < concatArgs.length - 1; i++) {
if ((i-1) % 2 == 0) {
concatArgs[i] = stringProperties[(i-1) / 2];
} else {
concatArgs[i] = "->";
}
}
concatArgs[i] = ")";
string.bind(Bindings.concat(concatArgs));
}
return string;
}
public Term[] getArguments() {
return type;
}
@Override
public boolean isApplicable(Term term) {
if (term == null) {
return true;
}
// Klopt bij lange na niet, geeft alleen een idee
if (term instanceof Function) {
Function other = (Function) term;
if (this.type.length == other.type.length) {
for (int i = 0; i < type.length; i++) {
if (!this.type[i].isApplicable(other.type[i])) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public boolean applyTerm(Term term) {
if (term == null) {
for (int i = 0; i < type.length; i++) {
this.type[i].applyTerm(null);
}
return true;
}
if (isApplicable(term)) {
Function other = (Function) term;
for (int i = 0; i < type.length; i++) {
this.type[i].applyTerm(other.type[i]);
}
return true;
}
return false;
}
@Override
public Term getAppliedTerm() {
return this;
}
}
| rgankema/TactileAPI | LwBDemo/src/main/java/nl/utwente/ewi/caes/lwbdemo/model/Function.java | 780 | // Klopt bij lange na niet, geeft alleen een idee | line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.utwente.ewi.caes.lwbdemo.model;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Function extends Term {
final Term[] type;
public Function(Term... arguments) {
if (arguments.length < 2) {
throw new IllegalArgumentException();
}
this.type = arguments;
}
@Override
public StringProperty stringProperty() {
if (string == null) {
string = new SimpleStringProperty();
StringProperty[] stringProperties = new StringProperty[type.length];
for (int i = 0; i < type.length; i++) {
stringProperties[i] = type[i].stringProperty();
}
Object[] concatArgs = new Object[stringProperties.length * 2 + 1];
int i = 0;
concatArgs[i] = "(";
for (i = 1; i < concatArgs.length - 1; i++) {
if ((i-1) % 2 == 0) {
concatArgs[i] = stringProperties[(i-1) / 2];
} else {
concatArgs[i] = "->";
}
}
concatArgs[i] = ")";
string.bind(Bindings.concat(concatArgs));
}
return string;
}
public Term[] getArguments() {
return type;
}
@Override
public boolean isApplicable(Term term) {
if (term == null) {
return true;
}
// Klopt bij<SUF>
if (term instanceof Function) {
Function other = (Function) term;
if (this.type.length == other.type.length) {
for (int i = 0; i < type.length; i++) {
if (!this.type[i].isApplicable(other.type[i])) {
return false;
}
}
return true;
}
}
return false;
}
@Override
public boolean applyTerm(Term term) {
if (term == null) {
for (int i = 0; i < type.length; i++) {
this.type[i].applyTerm(null);
}
return true;
}
if (isApplicable(term)) {
Function other = (Function) term;
for (int i = 0; i < type.length; i++) {
this.type[i].applyTerm(other.type[i]);
}
return true;
}
return false;
}
@Override
public Term getAppliedTerm() {
return this;
}
}
|
22677_11 | package nl.knaw.huc.di.tag.tagml.importer3;
import nl.knaw.huc.di.tag.tagml.TAGMLSyntaxError;
import nl.knaw.huc.di.tag.tagml.grammar.TAGMLLexer;
import nl.knaw.huc.di.tag.tagml.importer2.*;
import nl.knaw.huygens.alexandria.ErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Token;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.*;
/*
* TAGML Multitree Parser
*
* Input: TAGMLLexer TokenStream
* Imports based on detecting one or more tree structures
* One node can appear in multiple trees
*
* @author: Ronald Haentjens Dekker
* 13-05-2018
*/
public class MultitreeParser {
private ExpectationTreeNode expectations;
public MultitreeParser(ExpectationTreeNode expectations) {
this.expectations = expectations;
}
public List<Tree<MarkupNode>> importTAGML(final String input) throws TAGMLSyntaxError, ExpectationError {
CharStream antlrInputStream = CharStreams.fromString(input);
return importTAGML(antlrInputStream);
}
public List<Tree<MarkupNode>> importTAGML(InputStream input) throws TAGMLSyntaxError, ExpectationError {
try {
CharStream antlrInputStream = CharStreams.fromStream(input);
return importTAGML(antlrInputStream);
} catch (IOException e) {
e.printStackTrace();
throw new UncheckedIOException(e);
}
}
private List<Tree<MarkupNode>> importTAGML(CharStream antlrInputStream) throws TAGMLSyntaxError, ExpectationError {
TAGMLLexer lexer = new TAGMLLexer(antlrInputStream);
ErrorListener errorListener = new ErrorListener();
lexer.addErrorListener(errorListener);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
tokenStream.fill();
List<Token> tokens = tokenStream.getTokens();
// the parser is bottom up and starts to chain together subtrees when closing tags
// We houden alle bomen bij als een list van stacks van open subtrees
List<Stack<MarkupNode>> openNodes = new ArrayList<>();
// create the first stack
Stack<MarkupNode> openMarkupNodesStack = new Stack<>();
openNodes.add(openMarkupNodesStack);
// We houden alle gebouwde bomen bij..
List<Tree<MarkupNode>> closedTrees = new ArrayList<>();
for (Token t: tokens) {
// a couple of tokens we ignore
if (t.getType() == TAGMLLexer.DEFAULT_BeginOpenMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.IMO_EndOpenMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.DEFAULT_BeginCloseMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.IMC_EndCloseMarkup) {
continue;
}
// a couple of tokens we store the temporary result
if (t.getType() == TAGMLLexer.DEFAULT_Text) {
for (Stack<MarkupNode> openNodesStack : openNodes) {
// the first node is not always necessary.. it is optional for files without root node
if (openNodesStack.isEmpty()) {
MarkupNode rootNode = new MarkupNode();
openNodesStack.add(rootNode);
//NOTE: also add tree!
//Cause normally this done at close tag time!
Tree<MarkupNode> markupNodeTree = new Tree<>(rootNode);
closedTrees.add(markupNodeTree);
//TODO: oh boy this will trigger a node not closed exception!
}
openNodesStack.peek().setText(t.getText());
}
}
else if (t.getType() == TAGMLLexer.IMO_NameOpenMarkup) {
MarkupNode node = new MarkupNode();
node.setTag(t.getText());
//TODO: nu wordt het alleen aan één boom toegevoegd!
openMarkupNodesStack.add(node);
}
else if (t.getType() == TAGMLLexer.IMC_NameCloseMarkup) {
String tagToLookFor = t.getText();
System.out.println(tagToLookFor);
System.out.println(openMarkupNodesStack.peek().getTag());
if (!openMarkupNodesStack.peek().getTag().equals(tagToLookFor)) {
// nu moeten we gaan zoeken
MarkupNode node = searchTheStackForTag(openMarkupNodesStack, tagToLookFor);
// committen is ook best lastig!
// Ik weet niet precies hoeveel trees we moeten maken
Tree<MarkupNode> newTree = new Tree<MarkupNode>();
} else {
MarkupNode last = openMarkupNodesStack.pop();
Tree<MarkupNode> markupNodeTree = new Tree<>(last);
closedTrees.add(markupNodeTree);
// if (!openTreeNodes.contains(tagToLookFor)) {
// throw new RuntimeException( "Heh!");
// }
}
}
else if (t.getType() == -1) {
break;
}
else {
throw new RuntimeException("Unsupported token exception: "+t.toString());
}
}
return closedTrees;
}
private MarkupNode searchTheStackForTag(Stack<MarkupNode> openTreeNodesStack, String tagToLookFor) {
MarkupNode found = null;
for (int i=openTreeNodesStack.size()-1; i >= 0;i--) {
MarkupNode markupNode = openTreeNodesStack.get(i);
if (markupNode.getTag().equals(tagToLookFor)) {
System.out.println("Found it!");
found = markupNode;
break;
// throw new RuntimeException("Warning overlap!");
}
}
if (found == null) {
throw new RuntimeException("Weird not found!");
}
return found;
}
} | rhdekker/alexandria-markup | main/src/main/java/nl/knaw/huc/di/tag/tagml/importer3/MultitreeParser.java | 1,718 | //TODO: nu wordt het alleen aan één boom toegevoegd! | line_comment | nl | package nl.knaw.huc.di.tag.tagml.importer3;
import nl.knaw.huc.di.tag.tagml.TAGMLSyntaxError;
import nl.knaw.huc.di.tag.tagml.grammar.TAGMLLexer;
import nl.knaw.huc.di.tag.tagml.importer2.*;
import nl.knaw.huygens.alexandria.ErrorListener;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.Token;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.util.*;
/*
* TAGML Multitree Parser
*
* Input: TAGMLLexer TokenStream
* Imports based on detecting one or more tree structures
* One node can appear in multiple trees
*
* @author: Ronald Haentjens Dekker
* 13-05-2018
*/
public class MultitreeParser {
private ExpectationTreeNode expectations;
public MultitreeParser(ExpectationTreeNode expectations) {
this.expectations = expectations;
}
public List<Tree<MarkupNode>> importTAGML(final String input) throws TAGMLSyntaxError, ExpectationError {
CharStream antlrInputStream = CharStreams.fromString(input);
return importTAGML(antlrInputStream);
}
public List<Tree<MarkupNode>> importTAGML(InputStream input) throws TAGMLSyntaxError, ExpectationError {
try {
CharStream antlrInputStream = CharStreams.fromStream(input);
return importTAGML(antlrInputStream);
} catch (IOException e) {
e.printStackTrace();
throw new UncheckedIOException(e);
}
}
private List<Tree<MarkupNode>> importTAGML(CharStream antlrInputStream) throws TAGMLSyntaxError, ExpectationError {
TAGMLLexer lexer = new TAGMLLexer(antlrInputStream);
ErrorListener errorListener = new ErrorListener();
lexer.addErrorListener(errorListener);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
tokenStream.fill();
List<Token> tokens = tokenStream.getTokens();
// the parser is bottom up and starts to chain together subtrees when closing tags
// We houden alle bomen bij als een list van stacks van open subtrees
List<Stack<MarkupNode>> openNodes = new ArrayList<>();
// create the first stack
Stack<MarkupNode> openMarkupNodesStack = new Stack<>();
openNodes.add(openMarkupNodesStack);
// We houden alle gebouwde bomen bij..
List<Tree<MarkupNode>> closedTrees = new ArrayList<>();
for (Token t: tokens) {
// a couple of tokens we ignore
if (t.getType() == TAGMLLexer.DEFAULT_BeginOpenMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.IMO_EndOpenMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.DEFAULT_BeginCloseMarkup) {
continue;
} else if (t.getType() == TAGMLLexer.IMC_EndCloseMarkup) {
continue;
}
// a couple of tokens we store the temporary result
if (t.getType() == TAGMLLexer.DEFAULT_Text) {
for (Stack<MarkupNode> openNodesStack : openNodes) {
// the first node is not always necessary.. it is optional for files without root node
if (openNodesStack.isEmpty()) {
MarkupNode rootNode = new MarkupNode();
openNodesStack.add(rootNode);
//NOTE: also add tree!
//Cause normally this done at close tag time!
Tree<MarkupNode> markupNodeTree = new Tree<>(rootNode);
closedTrees.add(markupNodeTree);
//TODO: oh boy this will trigger a node not closed exception!
}
openNodesStack.peek().setText(t.getText());
}
}
else if (t.getType() == TAGMLLexer.IMO_NameOpenMarkup) {
MarkupNode node = new MarkupNode();
node.setTag(t.getText());
//TODO: nu<SUF>
openMarkupNodesStack.add(node);
}
else if (t.getType() == TAGMLLexer.IMC_NameCloseMarkup) {
String tagToLookFor = t.getText();
System.out.println(tagToLookFor);
System.out.println(openMarkupNodesStack.peek().getTag());
if (!openMarkupNodesStack.peek().getTag().equals(tagToLookFor)) {
// nu moeten we gaan zoeken
MarkupNode node = searchTheStackForTag(openMarkupNodesStack, tagToLookFor);
// committen is ook best lastig!
// Ik weet niet precies hoeveel trees we moeten maken
Tree<MarkupNode> newTree = new Tree<MarkupNode>();
} else {
MarkupNode last = openMarkupNodesStack.pop();
Tree<MarkupNode> markupNodeTree = new Tree<>(last);
closedTrees.add(markupNodeTree);
// if (!openTreeNodes.contains(tagToLookFor)) {
// throw new RuntimeException( "Heh!");
// }
}
}
else if (t.getType() == -1) {
break;
}
else {
throw new RuntimeException("Unsupported token exception: "+t.toString());
}
}
return closedTrees;
}
private MarkupNode searchTheStackForTag(Stack<MarkupNode> openTreeNodesStack, String tagToLookFor) {
MarkupNode found = null;
for (int i=openTreeNodesStack.size()-1; i >= 0;i--) {
MarkupNode markupNode = openTreeNodesStack.get(i);
if (markupNode.getTag().equals(tagToLookFor)) {
System.out.println("Found it!");
found = markupNode;
break;
// throw new RuntimeException("Warning overlap!");
}
}
if (found == null) {
throw new RuntimeException("Weird not found!");
}
return found;
}
} |
20904_48 | package eu.interedition.collatex.dekker.experimental_aligner;
import eu.interedition.collatex.Token;
import eu.interedition.collatex.VariantGraph;
import eu.interedition.collatex.dekker.astar.AstarAlgorithm;
import eu.interedition.collatex.dekker.astar.Cost;
import eu.interedition.collatex.dekker.experimental_aligner.Block;
import eu.interedition.collatex.dekker.experimental_aligner.Dekker21Aligner;
import eu.interedition.collatex.dekker.experimental_aligner.TokenIndex;
import eu.interedition.collatex.simple.SimpleToken;
import eu.interedition.collatex.util.VariantGraphRanking;
import java.util.*;
/**
* Experimental code; not yet ready for production
* Created by ronald on 4/24/15.
*/
public class DecisionGraphAligner {
protected TokenIndex tokenIndex;
// tokens are mapped to vertices by their position in the token array
protected VariantGraph.Vertex[] vertex_array;
private Map<VariantGraph.Vertex, Block> vertexToLCP;
public void align(VariantGraph against, Iterable<Token> witness) {
//NOTE: the following method assigns the decision graph to the field decisionGraph
ThreeDimensionalDecisionGraph decisionGraph = createDecisionGraph(against, witness);
// Do the actual alignment
List<ExtendedGraphEdge> edges = decisionGraph.getOptimalPath();
// from the list of edges we need to extract the matches
// and construct a map (token -> vertex) containing the alignment.
Map<Token, VariantGraph.Vertex> alignments = new HashMap<>();
ExtendedGraphNode previous = decisionGraph.getRoot();
for (ExtendedGraphEdge edge : edges) {
ExtendedGraphNode targetNode = decisionGraph.getTarget(edge);
if (edge.isMatch()) {
Block lcpInterval = edge.block;
//NOTE: this does not always have to be true
//intervals can occur multiple times in one witness
int tokenPosition = getLowestTokenPosition(lcpInterval);
for (int i=0; i< lcpInterval.length; i++) {
// we need:
// 1. token in graph and associated vertex in graph (tokenPosition+i)
// 2. token in witness (startRangeWitness+positionIndex+i)
VariantGraph.Vertex v = vertex_array[tokenPosition+i];
Token token = tokenIndex.token_array.get(decisionGraph.startRangeWitness2+previous.startPosWitness2+i);
alignments.put(token, v);
//TODO: fill vertex array for current witness
}
}
previous = targetNode;
}
merge(against, witness, alignments);
}
private void merge(VariantGraph against, Iterable<Token> witness, Map<Token, VariantGraph.Vertex> alignments) {
}
public ThreeDimensionalDecisionGraph createDecisionGraph(VariantGraph against, Iterable<Token> witness) {
int beginWitness2 = tokenIndex.getStartTokenPositionForWitness(witness.iterator().next().getWitness());
// prepare vertices
List<VariantGraph.Vertex> vert = copyIterable(against.vertices());
// remove start / end vertices
vert.remove(0);
vert.remove(vert.size() - 1);
VariantGraph.Vertex[] vertices = vert.toArray(new VariantGraph.Vertex[vert.size()]);
// prepare tokens
List<Token> tok = copyIterable(witness);
Token[] tokens = tok.toArray(new Token[tok.size()]);
// Align using decisionGraph algorithm in 2D
// first dimension: vertices in topological order
// second dimension: witness tokens
// TODO: This should be done in a 3D space. 2D causes artifacts, since there are multiple topological sorts of the graph.
// TODO: first dimension: vertex ranks
// TODO: second dimension: all vertices of a certain rank
// TODO: third dimension: witness tokens
VariantGraphRanking ranking = VariantGraphRanking.of(against);
ThreeDimensionalDecisionGraph decisionGraph = new ThreeDimensionalDecisionGraph(ranking, tokens, new SimpleMatcher(), beginWitness2);
return decisionGraph;
}
enum EditOperationEnum {
SKIP_GRAPH_RANK,
SKIP_TOKEN_WITNESS,
SKIP_TOKEN_GRAPH, // OLD
MATCH_TOKENS_OR_REPLACE // OLD, but kept for now
}
public static class DecisionGraphNode {
int startPosWitness1 = 0;
int startPosWitness2 = 0;
public DecisionGraphNode() {
this(0,0);
}
public DecisionGraphNode(int x, int y) {
this.startPosWitness1 = x;
this.startPosWitness2 = y;
}
public DecisionGraphNode copy() {
DecisionGraphNode copy = new DecisionGraphNode();
copy.startPosWitness1 = this.startPosWitness1;
copy.startPosWitness2 = this.startPosWitness2;
return copy;
}
}
public class DecisionGraphNodeCost extends Cost<DecisionGraphNodeCost> {
// TODO: this is far too simple!
int alignedTokens; // cost function
public DecisionGraphNodeCost() {
this(0);
}
public DecisionGraphNodeCost(int alignedTokens) {
this.alignedTokens = alignedTokens;
}
@Override
protected DecisionGraphNodeCost plus(DecisionGraphNodeCost other) {
return new DecisionGraphNodeCost(alignedTokens + other.alignedTokens);
}
@Override
public int compareTo(DecisionGraphNodeCost o) {
return o.alignedTokens - alignedTokens;
}
}
public static class ExtendedGraphNode extends DecisionGraphNode {
private final int vertexRank;
private final VariantGraph.Vertex vertex;
public final Map<ExtendedGraphNode, ExtendedGraphEdge> outgoingEdges;
protected int cost; // to be assigned by the cost function in the aligner
protected int heuristicCost; // to be assigned by the heuristic cost function in the aligner
public ExtendedGraphNode(int vertexRank, VariantGraph.Vertex vertex, int startPosWitness2) {
this.vertexRank = vertexRank;
this.vertex = vertex;
this.startPosWitness2 = startPosWitness2; // index in token array
this.outgoingEdges = new HashMap<>();
}
public int getVertexRank() {
return vertexRank;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {return true;}
if (obj == null) {return false;}
if (!(obj instanceof ExtendedGraphNode)) {
return false;
}
ExtendedGraphNode other = (ExtendedGraphNode) obj;
return other.vertex.equals(this.vertex) && other.startPosWitness2 == this.startPosWitness2;
}
@Override
public int hashCode() {
return vertex.hashCode() + 97 * startPosWitness2;
}
public String represent() {
return String.format("(%d, %d) (%d, %d)", this.getVertexRank(), this.startPosWitness2, this.cost, this.heuristicCost);
}
}
public class ThreeDimensionalDecisionGraph extends AstarAlgorithm<ExtendedGraphNode, DecisionGraphNodeCost> {
private final VariantGraphRanking ranking;
private final Token[] witnessTokens;
private final Matcher matcher;
private final int startRangeWitness2;
private final ExtendedGraphNode root;
private final Map<ExtendedGraphNodeTuple, ExtendedGraphEdge> edges;
private final Map<ExtendedGraphEdge, ExtendedGraphNode> targets;
public ThreeDimensionalDecisionGraph(VariantGraphRanking ranking, Token[] witnessTokens, Matcher matcher, int startRangeWitness2) {
this.ranking = ranking;
this.witnessTokens = witnessTokens;
this.matcher = matcher;
this.startRangeWitness2 = startRangeWitness2;
//TODO: get by the root node in a better way...
//TODO: we don need the root node here but the first actual node
//TODO: thus vertex rank +1
this.root = new ExtendedGraphNode(0, ranking.getByRank().get(1).iterator().next(), 0);
edges = new HashMap<>();
targets = new HashMap<>();
}
@Override
protected boolean isGoal(ExtendedGraphNode node) {
return isHorizontalEnd(node) && isVerticalEnd(node);
}
private boolean isHorizontalEnd(ExtendedGraphNode node) {
// check whether we have reached the end node of the variant graph
// -2 because ignore start / end vertices of variant graph
return node.getVertexRank() == ranking.size()-2;
}
private boolean isVerticalEnd(ExtendedGraphNode node) {
return node.startPosWitness2 == witnessTokens.length;
}
@Override
protected Iterable<ExtendedGraphNode> neighborNodes(ExtendedGraphNode current) {
//TODO: volgens mij moet het in sommige gevallen rank plus een zijn
//TODO: namelijk als er op het huidige rank geen gevallen meer zijn
//TODO: misschien is dit op te lossen
//TODO: door de huidige rank te doen
//TODO: en de volgende rank
//TODO: plus skip huidige rank natuurlijk.. als er niets matched
// generate decision graph nodes for siblings of this nodes (and maybe child nodes)
// also a node is needed to skip all the vertices of a certain rank
// also a node to skip the token of the witness
List<ExtendedGraphNode> neighbors = new ArrayList<>();
// The following code is only necessary when there are two or more witnesses
// TODO: in the siblings we need to skip the current vertex
// // siblings
// Set<VariantGraph.Vertex> siblings = ranking.getByRank().get(current.getVertexRank());
// for (VariantGraph.Vertex vertex : siblings) {
// ExtendedGraphNode node = new ExtendedGraphNode(current.getVertexRank(), vertex, current.startPosWitness2);
// neighbors.add(node);
// ExtendedGraphEdge edge = new ExtendedGraphEdge(EditOperationEnum.MATCH_TOKENS_OR_REPLACE, null);
// edges.put(current, edge);
// }
// skip next graph LCP interval
VariantGraph.Vertex currentVertex = current.vertex;
Block graph_interval = vertexToLCP.get(currentVertex);
//NOTE: not every vertex has to be associated with a LCP interval... non repeated unique blocks of text
//are not part of an interval, but do have vertices!
int nextVertexRank;
if (graph_interval!=null) {
nextVertexRank = current.getVertexRank() + graph_interval.length;
} else {
nextVertexRank = current.getVertexRank() + 1;
//TODO: this is a hack! We really want to do deal with this cases in a natural manner!
graph_interval = new Block(tokenIndex, 0, 0);
}
if (!isHorizontalEnd(current)) {
//TODO: dit zouden in theorie meerdere vertices kunenn zijn..
//TODO: er moet in de constructor van de node moet of de rank of de nextVertex worden meegegeven..
//TODO: voor de derde dimensie is een nextVertex noodzakelijk
//TODO: we zouden de graaf af moeten lopen..
//NOTE: +1 is because of skipping root vertex of variant graph
//TODO: remove duplication with the root node of decision graph
VariantGraph.Vertex nextVertex = ranking.getByRank().get(nextVertexRank+1).iterator().next();
//NOTE: Defensive programming!
if (currentVertex.equals(nextVertex)) {
throw new RuntimeException("current, next Vertex: "+ currentVertex.toString()+" "+nextVertex);
}
ExtendedGraphNode node = new ExtendedGraphNode(nextVertexRank, nextVertex, current.startPosWitness2);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.SKIP_TOKEN_GRAPH, graph_interval);
}
// check whether we are at the end of the variant graph
// we might not be at the end of the tokens yet
if (!isHorizontalEnd(current)&&!isVerticalEnd(current)) {
// children
//TODO; remove duplication here!
//NOTE: +1 is because of skipping root vertex of variant graph
Set<VariantGraph.Vertex> children = ranking.getByRank().get(nextVertexRank+1);
for (VariantGraph.Vertex vertex : children) {
ExtendedGraphNode node = new ExtendedGraphNode(nextVertexRank, vertex, current.startPosWitness2+graph_interval.length);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.MATCH_TOKENS_OR_REPLACE, graph_interval);
}
}
// skip next witness LCP interval
if (!isVerticalEnd(current)) {
// calc position start position witness + position in witness
int token_position = startRangeWitness2 + current.startPosWitness2;
Block witness_interval = tokenIndex.getLCP_intervalFor(token_position);
if (witness_interval==null) {
//TODO: this is a hack! We really want to do deal with this cases in a natural manner!
witness_interval = new Block(tokenIndex, 0, 0);
}
ExtendedGraphNode node = new ExtendedGraphNode(current.getVertexRank(), currentVertex, current.startPosWitness2+witness_interval.length);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.SKIP_TOKEN_WITNESS, witness_interval);
}
return neighbors;
}
private void addEdge(ExtendedGraphNode source, ExtendedGraphNode target, EditOperationEnum operation, Block interval) {
// Actually there are two intervals!
if (interval==null) {
throw new RuntimeException("Interval is null!");
}
ExtendedGraphEdge edge = new ExtendedGraphEdge(operation, interval);
// old style
edges.put(new ExtendedGraphNodeTuple(source, operation), edge);
targets.put(edge, target);
// new style
source.outgoingEdges.put(target, edge);
}
//NOTE: The heuristic cost estimate for the root node of the decision graph is wrong
//NOTE: this does not yet have consequences because the root node is always selected, after which the heuristic is overwritten
@Override
protected DecisionGraphNodeCost heuristicCostEstimate(ExtendedGraphNode node) {
// traverse the vertices from the current rank to the last
// one should exclude the current vertex
int potentialMatchesGraph = 0;
int vertexRank = node.getVertexRank();
int endRank = ranking.size();
// +1 to skip start vertex of variant graph
// without end rank to skip end vertex of variant graph
for (int i = vertexRank+1; i < endRank; i++) {
for (VariantGraph.Vertex vertex : ranking.getByRank().get(i)) {
if (vertex != node.vertex && vertexToLCP.get(vertex) != null) {
potentialMatchesGraph++;
}
}
}
// for (int i = node.startPosWitness1; i < vertices.length; i++) {
// VariantGraph.Vertex v = vertices[i];
// if (vertexToLCP.get(v)!=null) {
// potentialMatchesGraph++;
// }
// }
int potentialMatchesWitness = 0;
for (int i = startRangeWitness2 + node.startPosWitness2; i < startRangeWitness2+witnessTokens.length; i++) {
if (tokenIndex.hasLCP_intervalFor(i)) {
potentialMatchesWitness++;
}
}
int potentialMatches = Math.min(potentialMatchesGraph, potentialMatchesWitness);
// put heuristic cost on the node
node.heuristicCost = potentialMatches;
return new DecisionGraphNodeCost(potentialMatches);
}
//NOTE: this scorer assigns positive costs
@Override
protected DecisionGraphNodeCost distBetween(ExtendedGraphNode current, ExtendedGraphNode neighbor) {
ExtendedGraphEdge edge = this.edgeBetween(current, EditOperationEnum.MATCH_TOKENS_OR_REPLACE);
if (edge!=null&&this.getTarget(edge).equals(neighbor)) {
Block graphInterval = edge.block;
Block witnessInterval = tokenIndex.getLCP_intervalFor(startRangeWitness2+current.startPosWitness2);
if (graphInterval==witnessInterval) {
edge.match = true;
// set cost on neighbor if it is higher
if (neighbor.cost < graphInterval.length) {
neighbor.cost = graphInterval.length;
}
return new DecisionGraphNodeCost(graphInterval.length);
}
}
return new DecisionGraphNodeCost(0);
}
public Token token(DecisionGraphNode node) {
return witnessTokens[node.startPosWitness2];
}
public VariantGraph.Vertex vertex(DecisionGraphNode node) {
return ((ExtendedGraphNode)node).vertex;
}
public ExtendedGraphNode getRoot() {
return root;
}
public ExtendedGraphEdge edgeBetween(ExtendedGraphNode source, EditOperationEnum operation) {
ExtendedGraphEdge edge = edges.get(new ExtendedGraphNodeTuple(source, operation));
// if (edge == null) {
// throw new RuntimeException("Edge not present!");
// }
return edge;
}
public ExtendedGraphNode getTarget(ExtendedGraphEdge edge) {
ExtendedGraphNode target = targets.get(edge);
if (target == null) {
throw new RuntimeException("Target not set!");
}
return target;
}
public List<ExtendedGraphEdge> getOptimalPath() {
List<ExtendedGraphNode> nodes = this.aStar(getRoot(), new DecisionGraphNodeCost());
if (nodes.isEmpty()) {
throw new RuntimeException("Nodes are unexpected empty!");
}
// transform the nodes into edges
Deque<ExtendedGraphNode> nodesTodo = new ArrayDeque<>();
nodesTodo.addAll(nodes);
List<ExtendedGraphEdge> edges = new ArrayList<>();
while(!nodesTodo.isEmpty()) {
ExtendedGraphNode node = nodesTodo.pop();
if (isGoal(node)) {
break;
}
ExtendedGraphNode next = nodesTodo.peek();
ExtendedGraphEdge edge = this.getEdgeBetween(node, next);
edges.add(edge);
}
return edges;
}
private ExtendedGraphEdge getEdgeBetween(ExtendedGraphNode node, ExtendedGraphNode next) {
ExtendedGraphEdge edge = node.outgoingEdges.get(next);
return edge;
}
}
public class ExtendedGraphNodeTuple {
private ExtendedGraphNode source;
private EditOperationEnum operation;
//private ExtendedGraphNode target;
public ExtendedGraphNodeTuple(ExtendedGraphNode source, EditOperationEnum operation) {
this.source = source;
this.operation = operation;
}
//TODO: with target hashcode added performance would be improved
@Override
public int hashCode() {
return source.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof ExtendedGraphNodeTuple)) {
return false;
}
ExtendedGraphNodeTuple other = (ExtendedGraphNodeTuple) obj;
return other.source.equals(source) && other.operation == operation;
}
}
public class ExtendedGraphEdge {
protected EditOperationEnum operation;
protected Block block;
private boolean match;
public ExtendedGraphEdge(EditOperationEnum operation, Block block) {
this.operation = operation;
this.block = block;
}
public String represent(Dekker21Aligner aligner) {
String result = "";
if (operation == EditOperationEnum.SKIP_TOKEN_GRAPH) {
result += "remove";
} else if (operation == EditOperationEnum.MATCH_TOKENS_OR_REPLACE) {
result += "match/replace";
} else if (operation == EditOperationEnum.SKIP_TOKEN_WITNESS) {
result += "add";
}
result += " (";
result += block.getNormalizedForm();
result += ")";
return result;
}
public boolean isMatch() {
return match;
}
}
private int getLowestTokenPosition(Block lcpInterval) {
// search lowest token position in lcp interval
// that position will already be in the variant graph
int suffixStart = lcpInterval.start;
int suffixEnd = lcpInterval.end;
int lowestPosition = 0;
for (int i = suffixStart; i <= suffixEnd; i++) {
int tokenPosition = tokenIndex.suffix_array[i];
if (tokenPosition < lowestPosition)
lowestPosition = tokenPosition;
}
return lowestPosition;
}
public static <T> List<T> copyIterable(Iterable<T> iterable) {
return copyIterator(iterable.iterator());
}
public static <T> List<T> copyIterator(Iterator<T> iter) {
List<T> copy = new ArrayList<T>();
while (iter.hasNext())
copy.add(iter.next());
return copy;
}
class Matcher {
Boolean match(VariantGraph.Vertex a, Token b) {
return false;
}
}
class SimpleMatcher extends Matcher {
@Override
Boolean match(VariantGraph.Vertex a, Token b) {
SimpleToken sa = (SimpleToken) a.tokens().iterator().next();
SimpleToken sb = (SimpleToken) b;
return sa.getNormalized().equals(sb.getNormalized());
}
}
// // 1) We need to know the neighbors in the decision graph
// // There are three possibilities in a 2D space
// // 2) We need to calculate the heuristic for each
// // 3) We need to score each
// class TwoDimensionalDecisionGraph extends AstarAlgorithm<DecisionGraphNode, DecisionGraphNodeCost> {
//
// private final VariantGraph.Vertex[] vertices;
// private final Token[] tokens;
// private int startRangeWitness2;
// private Matcher matcher;
//
// public TwoDimensionalDecisionGraph(VariantGraph.Vertex[] vertices, Token[] tokens, int startRangeWitness2) {
// this.vertices = vertices;
// this.tokens = tokens;
// this.startRangeWitness2 = startRangeWitness2;
// this.matcher = new SimpleMatcher();
// }
//
// @Override
// protected boolean isGoal(DecisionGraphNode node) {
// return isHorizontalEnd(node) && isVerticalEnd(node);
// }
//
// private boolean isHorizontalEnd(DecisionGraphNode node) {
// return node.startPosWitness1 == vertices.length;
// }
//
// private boolean isVerticalEnd(DecisionGraphNode node) {
// return node.startPosWitness2 == tokens.length;
// }
//
// @Override
// protected Iterable<DecisionGraphNode> neighborNodes(DecisionGraphNode current) {
// // In a 2D approach there are 3 possibilities
// List<DecisionGraphNode> children = new ArrayList<>();
// boolean xEnd = isHorizontalEnd(current);
// boolean yEnd = isVerticalEnd(current);
// if (!xEnd) {
// DecisionGraphNode child1 = current.copy();
// child1.startPosWitness1++;
// child1.editOperation = EditOperationEnum.SKIP_TOKEN_GRAPH;
// children.add(child1);
// }
// if (!yEnd) {
// DecisionGraphNode child2 = current.copy();
// child2.startPosWitness2++;
// child2.editOperation = EditOperationEnum.SKIP_TOKEN_WITNESS;
// children.add(child2);
// }
// if (!xEnd && !yEnd) {
// DecisionGraphNode child3 = current.copy();
// child3.startPosWitness1++;
// child3.startPosWitness2++;
// child3.editOperation = EditOperationEnum.MATCH_TOKENS_OR_REPLACE;
// children.add(child3);
// }
// return children;
// }
//
// @Override
// protected DecisionGraphNodeCost heuristicCostEstimate(DecisionGraphNode node) {
// int potentialMatchesGraph = 0;
// for (int i = node.startPosWitness1; i < vertices.length; i++) {
// VariantGraph.Vertex v = vertices[i];
// if (vertexToLCP.get(v)!=null) {
// potentialMatchesGraph++;
// }
// }
//
// int potentialMatchesWitness = 0;
// for (int i = startRangeWitness2 + node.startPosWitness2; i < startRangeWitness2+tokens.length; i++) {
// if (lcp_interval_array[i] != null) {
// potentialMatchesWitness++;
// }
// }
// int potentialMatches = Math.min(potentialMatchesGraph, potentialMatchesWitness);
// return new DecisionGraphNodeCost(potentialMatches);
// }
//
// //NOTE: this scorer assigns positive costs
// @Override
// protected DecisionGraphNodeCost distBetween(DecisionGraphNode current, DecisionGraphNode neighbor) {
// if (neighbor.editOperation == EditOperationEnum.MATCH_TOKENS_OR_REPLACE) {
// VariantGraph.Vertex v = vertex(neighbor);
// Token t = token(neighbor);
// Boolean match = matcher.match(v, t);
// if (match) {
// // Log("match: "+(neighbor.startPosWitness1-1)+", "+(neighbor.startPosWitness2-1));
// neighbor.match = true;
// return new DecisionGraphNodeCost(1);
// }
// }
// return new DecisionGraphNodeCost(0);
// }
//
// public VariantGraph.Vertex vertex(DecisionGraphNode node) {
// return vertices[node.startPosWitness1-1];
// }
//
// public Token token(DecisionGraphNode node) {
// return tokens[node.startPosWitness2-1];
// }
// }
}
| rhdekker/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/experimental_aligner/DecisionGraphAligner.java | 7,097 | //TODO: dit zouden in theorie meerdere vertices kunenn zijn.. | line_comment | nl | package eu.interedition.collatex.dekker.experimental_aligner;
import eu.interedition.collatex.Token;
import eu.interedition.collatex.VariantGraph;
import eu.interedition.collatex.dekker.astar.AstarAlgorithm;
import eu.interedition.collatex.dekker.astar.Cost;
import eu.interedition.collatex.dekker.experimental_aligner.Block;
import eu.interedition.collatex.dekker.experimental_aligner.Dekker21Aligner;
import eu.interedition.collatex.dekker.experimental_aligner.TokenIndex;
import eu.interedition.collatex.simple.SimpleToken;
import eu.interedition.collatex.util.VariantGraphRanking;
import java.util.*;
/**
* Experimental code; not yet ready for production
* Created by ronald on 4/24/15.
*/
public class DecisionGraphAligner {
protected TokenIndex tokenIndex;
// tokens are mapped to vertices by their position in the token array
protected VariantGraph.Vertex[] vertex_array;
private Map<VariantGraph.Vertex, Block> vertexToLCP;
public void align(VariantGraph against, Iterable<Token> witness) {
//NOTE: the following method assigns the decision graph to the field decisionGraph
ThreeDimensionalDecisionGraph decisionGraph = createDecisionGraph(against, witness);
// Do the actual alignment
List<ExtendedGraphEdge> edges = decisionGraph.getOptimalPath();
// from the list of edges we need to extract the matches
// and construct a map (token -> vertex) containing the alignment.
Map<Token, VariantGraph.Vertex> alignments = new HashMap<>();
ExtendedGraphNode previous = decisionGraph.getRoot();
for (ExtendedGraphEdge edge : edges) {
ExtendedGraphNode targetNode = decisionGraph.getTarget(edge);
if (edge.isMatch()) {
Block lcpInterval = edge.block;
//NOTE: this does not always have to be true
//intervals can occur multiple times in one witness
int tokenPosition = getLowestTokenPosition(lcpInterval);
for (int i=0; i< lcpInterval.length; i++) {
// we need:
// 1. token in graph and associated vertex in graph (tokenPosition+i)
// 2. token in witness (startRangeWitness+positionIndex+i)
VariantGraph.Vertex v = vertex_array[tokenPosition+i];
Token token = tokenIndex.token_array.get(decisionGraph.startRangeWitness2+previous.startPosWitness2+i);
alignments.put(token, v);
//TODO: fill vertex array for current witness
}
}
previous = targetNode;
}
merge(against, witness, alignments);
}
private void merge(VariantGraph against, Iterable<Token> witness, Map<Token, VariantGraph.Vertex> alignments) {
}
public ThreeDimensionalDecisionGraph createDecisionGraph(VariantGraph against, Iterable<Token> witness) {
int beginWitness2 = tokenIndex.getStartTokenPositionForWitness(witness.iterator().next().getWitness());
// prepare vertices
List<VariantGraph.Vertex> vert = copyIterable(against.vertices());
// remove start / end vertices
vert.remove(0);
vert.remove(vert.size() - 1);
VariantGraph.Vertex[] vertices = vert.toArray(new VariantGraph.Vertex[vert.size()]);
// prepare tokens
List<Token> tok = copyIterable(witness);
Token[] tokens = tok.toArray(new Token[tok.size()]);
// Align using decisionGraph algorithm in 2D
// first dimension: vertices in topological order
// second dimension: witness tokens
// TODO: This should be done in a 3D space. 2D causes artifacts, since there are multiple topological sorts of the graph.
// TODO: first dimension: vertex ranks
// TODO: second dimension: all vertices of a certain rank
// TODO: third dimension: witness tokens
VariantGraphRanking ranking = VariantGraphRanking.of(against);
ThreeDimensionalDecisionGraph decisionGraph = new ThreeDimensionalDecisionGraph(ranking, tokens, new SimpleMatcher(), beginWitness2);
return decisionGraph;
}
enum EditOperationEnum {
SKIP_GRAPH_RANK,
SKIP_TOKEN_WITNESS,
SKIP_TOKEN_GRAPH, // OLD
MATCH_TOKENS_OR_REPLACE // OLD, but kept for now
}
public static class DecisionGraphNode {
int startPosWitness1 = 0;
int startPosWitness2 = 0;
public DecisionGraphNode() {
this(0,0);
}
public DecisionGraphNode(int x, int y) {
this.startPosWitness1 = x;
this.startPosWitness2 = y;
}
public DecisionGraphNode copy() {
DecisionGraphNode copy = new DecisionGraphNode();
copy.startPosWitness1 = this.startPosWitness1;
copy.startPosWitness2 = this.startPosWitness2;
return copy;
}
}
public class DecisionGraphNodeCost extends Cost<DecisionGraphNodeCost> {
// TODO: this is far too simple!
int alignedTokens; // cost function
public DecisionGraphNodeCost() {
this(0);
}
public DecisionGraphNodeCost(int alignedTokens) {
this.alignedTokens = alignedTokens;
}
@Override
protected DecisionGraphNodeCost plus(DecisionGraphNodeCost other) {
return new DecisionGraphNodeCost(alignedTokens + other.alignedTokens);
}
@Override
public int compareTo(DecisionGraphNodeCost o) {
return o.alignedTokens - alignedTokens;
}
}
public static class ExtendedGraphNode extends DecisionGraphNode {
private final int vertexRank;
private final VariantGraph.Vertex vertex;
public final Map<ExtendedGraphNode, ExtendedGraphEdge> outgoingEdges;
protected int cost; // to be assigned by the cost function in the aligner
protected int heuristicCost; // to be assigned by the heuristic cost function in the aligner
public ExtendedGraphNode(int vertexRank, VariantGraph.Vertex vertex, int startPosWitness2) {
this.vertexRank = vertexRank;
this.vertex = vertex;
this.startPosWitness2 = startPosWitness2; // index in token array
this.outgoingEdges = new HashMap<>();
}
public int getVertexRank() {
return vertexRank;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {return true;}
if (obj == null) {return false;}
if (!(obj instanceof ExtendedGraphNode)) {
return false;
}
ExtendedGraphNode other = (ExtendedGraphNode) obj;
return other.vertex.equals(this.vertex) && other.startPosWitness2 == this.startPosWitness2;
}
@Override
public int hashCode() {
return vertex.hashCode() + 97 * startPosWitness2;
}
public String represent() {
return String.format("(%d, %d) (%d, %d)", this.getVertexRank(), this.startPosWitness2, this.cost, this.heuristicCost);
}
}
public class ThreeDimensionalDecisionGraph extends AstarAlgorithm<ExtendedGraphNode, DecisionGraphNodeCost> {
private final VariantGraphRanking ranking;
private final Token[] witnessTokens;
private final Matcher matcher;
private final int startRangeWitness2;
private final ExtendedGraphNode root;
private final Map<ExtendedGraphNodeTuple, ExtendedGraphEdge> edges;
private final Map<ExtendedGraphEdge, ExtendedGraphNode> targets;
public ThreeDimensionalDecisionGraph(VariantGraphRanking ranking, Token[] witnessTokens, Matcher matcher, int startRangeWitness2) {
this.ranking = ranking;
this.witnessTokens = witnessTokens;
this.matcher = matcher;
this.startRangeWitness2 = startRangeWitness2;
//TODO: get by the root node in a better way...
//TODO: we don need the root node here but the first actual node
//TODO: thus vertex rank +1
this.root = new ExtendedGraphNode(0, ranking.getByRank().get(1).iterator().next(), 0);
edges = new HashMap<>();
targets = new HashMap<>();
}
@Override
protected boolean isGoal(ExtendedGraphNode node) {
return isHorizontalEnd(node) && isVerticalEnd(node);
}
private boolean isHorizontalEnd(ExtendedGraphNode node) {
// check whether we have reached the end node of the variant graph
// -2 because ignore start / end vertices of variant graph
return node.getVertexRank() == ranking.size()-2;
}
private boolean isVerticalEnd(ExtendedGraphNode node) {
return node.startPosWitness2 == witnessTokens.length;
}
@Override
protected Iterable<ExtendedGraphNode> neighborNodes(ExtendedGraphNode current) {
//TODO: volgens mij moet het in sommige gevallen rank plus een zijn
//TODO: namelijk als er op het huidige rank geen gevallen meer zijn
//TODO: misschien is dit op te lossen
//TODO: door de huidige rank te doen
//TODO: en de volgende rank
//TODO: plus skip huidige rank natuurlijk.. als er niets matched
// generate decision graph nodes for siblings of this nodes (and maybe child nodes)
// also a node is needed to skip all the vertices of a certain rank
// also a node to skip the token of the witness
List<ExtendedGraphNode> neighbors = new ArrayList<>();
// The following code is only necessary when there are two or more witnesses
// TODO: in the siblings we need to skip the current vertex
// // siblings
// Set<VariantGraph.Vertex> siblings = ranking.getByRank().get(current.getVertexRank());
// for (VariantGraph.Vertex vertex : siblings) {
// ExtendedGraphNode node = new ExtendedGraphNode(current.getVertexRank(), vertex, current.startPosWitness2);
// neighbors.add(node);
// ExtendedGraphEdge edge = new ExtendedGraphEdge(EditOperationEnum.MATCH_TOKENS_OR_REPLACE, null);
// edges.put(current, edge);
// }
// skip next graph LCP interval
VariantGraph.Vertex currentVertex = current.vertex;
Block graph_interval = vertexToLCP.get(currentVertex);
//NOTE: not every vertex has to be associated with a LCP interval... non repeated unique blocks of text
//are not part of an interval, but do have vertices!
int nextVertexRank;
if (graph_interval!=null) {
nextVertexRank = current.getVertexRank() + graph_interval.length;
} else {
nextVertexRank = current.getVertexRank() + 1;
//TODO: this is a hack! We really want to do deal with this cases in a natural manner!
graph_interval = new Block(tokenIndex, 0, 0);
}
if (!isHorizontalEnd(current)) {
//TODO: dit<SUF>
//TODO: er moet in de constructor van de node moet of de rank of de nextVertex worden meegegeven..
//TODO: voor de derde dimensie is een nextVertex noodzakelijk
//TODO: we zouden de graaf af moeten lopen..
//NOTE: +1 is because of skipping root vertex of variant graph
//TODO: remove duplication with the root node of decision graph
VariantGraph.Vertex nextVertex = ranking.getByRank().get(nextVertexRank+1).iterator().next();
//NOTE: Defensive programming!
if (currentVertex.equals(nextVertex)) {
throw new RuntimeException("current, next Vertex: "+ currentVertex.toString()+" "+nextVertex);
}
ExtendedGraphNode node = new ExtendedGraphNode(nextVertexRank, nextVertex, current.startPosWitness2);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.SKIP_TOKEN_GRAPH, graph_interval);
}
// check whether we are at the end of the variant graph
// we might not be at the end of the tokens yet
if (!isHorizontalEnd(current)&&!isVerticalEnd(current)) {
// children
//TODO; remove duplication here!
//NOTE: +1 is because of skipping root vertex of variant graph
Set<VariantGraph.Vertex> children = ranking.getByRank().get(nextVertexRank+1);
for (VariantGraph.Vertex vertex : children) {
ExtendedGraphNode node = new ExtendedGraphNode(nextVertexRank, vertex, current.startPosWitness2+graph_interval.length);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.MATCH_TOKENS_OR_REPLACE, graph_interval);
}
}
// skip next witness LCP interval
if (!isVerticalEnd(current)) {
// calc position start position witness + position in witness
int token_position = startRangeWitness2 + current.startPosWitness2;
Block witness_interval = tokenIndex.getLCP_intervalFor(token_position);
if (witness_interval==null) {
//TODO: this is a hack! We really want to do deal with this cases in a natural manner!
witness_interval = new Block(tokenIndex, 0, 0);
}
ExtendedGraphNode node = new ExtendedGraphNode(current.getVertexRank(), currentVertex, current.startPosWitness2+witness_interval.length);
neighbors.add(node);
addEdge(current, node, EditOperationEnum.SKIP_TOKEN_WITNESS, witness_interval);
}
return neighbors;
}
private void addEdge(ExtendedGraphNode source, ExtendedGraphNode target, EditOperationEnum operation, Block interval) {
// Actually there are two intervals!
if (interval==null) {
throw new RuntimeException("Interval is null!");
}
ExtendedGraphEdge edge = new ExtendedGraphEdge(operation, interval);
// old style
edges.put(new ExtendedGraphNodeTuple(source, operation), edge);
targets.put(edge, target);
// new style
source.outgoingEdges.put(target, edge);
}
//NOTE: The heuristic cost estimate for the root node of the decision graph is wrong
//NOTE: this does not yet have consequences because the root node is always selected, after which the heuristic is overwritten
@Override
protected DecisionGraphNodeCost heuristicCostEstimate(ExtendedGraphNode node) {
// traverse the vertices from the current rank to the last
// one should exclude the current vertex
int potentialMatchesGraph = 0;
int vertexRank = node.getVertexRank();
int endRank = ranking.size();
// +1 to skip start vertex of variant graph
// without end rank to skip end vertex of variant graph
for (int i = vertexRank+1; i < endRank; i++) {
for (VariantGraph.Vertex vertex : ranking.getByRank().get(i)) {
if (vertex != node.vertex && vertexToLCP.get(vertex) != null) {
potentialMatchesGraph++;
}
}
}
// for (int i = node.startPosWitness1; i < vertices.length; i++) {
// VariantGraph.Vertex v = vertices[i];
// if (vertexToLCP.get(v)!=null) {
// potentialMatchesGraph++;
// }
// }
int potentialMatchesWitness = 0;
for (int i = startRangeWitness2 + node.startPosWitness2; i < startRangeWitness2+witnessTokens.length; i++) {
if (tokenIndex.hasLCP_intervalFor(i)) {
potentialMatchesWitness++;
}
}
int potentialMatches = Math.min(potentialMatchesGraph, potentialMatchesWitness);
// put heuristic cost on the node
node.heuristicCost = potentialMatches;
return new DecisionGraphNodeCost(potentialMatches);
}
//NOTE: this scorer assigns positive costs
@Override
protected DecisionGraphNodeCost distBetween(ExtendedGraphNode current, ExtendedGraphNode neighbor) {
ExtendedGraphEdge edge = this.edgeBetween(current, EditOperationEnum.MATCH_TOKENS_OR_REPLACE);
if (edge!=null&&this.getTarget(edge).equals(neighbor)) {
Block graphInterval = edge.block;
Block witnessInterval = tokenIndex.getLCP_intervalFor(startRangeWitness2+current.startPosWitness2);
if (graphInterval==witnessInterval) {
edge.match = true;
// set cost on neighbor if it is higher
if (neighbor.cost < graphInterval.length) {
neighbor.cost = graphInterval.length;
}
return new DecisionGraphNodeCost(graphInterval.length);
}
}
return new DecisionGraphNodeCost(0);
}
public Token token(DecisionGraphNode node) {
return witnessTokens[node.startPosWitness2];
}
public VariantGraph.Vertex vertex(DecisionGraphNode node) {
return ((ExtendedGraphNode)node).vertex;
}
public ExtendedGraphNode getRoot() {
return root;
}
public ExtendedGraphEdge edgeBetween(ExtendedGraphNode source, EditOperationEnum operation) {
ExtendedGraphEdge edge = edges.get(new ExtendedGraphNodeTuple(source, operation));
// if (edge == null) {
// throw new RuntimeException("Edge not present!");
// }
return edge;
}
public ExtendedGraphNode getTarget(ExtendedGraphEdge edge) {
ExtendedGraphNode target = targets.get(edge);
if (target == null) {
throw new RuntimeException("Target not set!");
}
return target;
}
public List<ExtendedGraphEdge> getOptimalPath() {
List<ExtendedGraphNode> nodes = this.aStar(getRoot(), new DecisionGraphNodeCost());
if (nodes.isEmpty()) {
throw new RuntimeException("Nodes are unexpected empty!");
}
// transform the nodes into edges
Deque<ExtendedGraphNode> nodesTodo = new ArrayDeque<>();
nodesTodo.addAll(nodes);
List<ExtendedGraphEdge> edges = new ArrayList<>();
while(!nodesTodo.isEmpty()) {
ExtendedGraphNode node = nodesTodo.pop();
if (isGoal(node)) {
break;
}
ExtendedGraphNode next = nodesTodo.peek();
ExtendedGraphEdge edge = this.getEdgeBetween(node, next);
edges.add(edge);
}
return edges;
}
private ExtendedGraphEdge getEdgeBetween(ExtendedGraphNode node, ExtendedGraphNode next) {
ExtendedGraphEdge edge = node.outgoingEdges.get(next);
return edge;
}
}
public class ExtendedGraphNodeTuple {
private ExtendedGraphNode source;
private EditOperationEnum operation;
//private ExtendedGraphNode target;
public ExtendedGraphNodeTuple(ExtendedGraphNode source, EditOperationEnum operation) {
this.source = source;
this.operation = operation;
}
//TODO: with target hashcode added performance would be improved
@Override
public int hashCode() {
return source.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof ExtendedGraphNodeTuple)) {
return false;
}
ExtendedGraphNodeTuple other = (ExtendedGraphNodeTuple) obj;
return other.source.equals(source) && other.operation == operation;
}
}
public class ExtendedGraphEdge {
protected EditOperationEnum operation;
protected Block block;
private boolean match;
public ExtendedGraphEdge(EditOperationEnum operation, Block block) {
this.operation = operation;
this.block = block;
}
public String represent(Dekker21Aligner aligner) {
String result = "";
if (operation == EditOperationEnum.SKIP_TOKEN_GRAPH) {
result += "remove";
} else if (operation == EditOperationEnum.MATCH_TOKENS_OR_REPLACE) {
result += "match/replace";
} else if (operation == EditOperationEnum.SKIP_TOKEN_WITNESS) {
result += "add";
}
result += " (";
result += block.getNormalizedForm();
result += ")";
return result;
}
public boolean isMatch() {
return match;
}
}
private int getLowestTokenPosition(Block lcpInterval) {
// search lowest token position in lcp interval
// that position will already be in the variant graph
int suffixStart = lcpInterval.start;
int suffixEnd = lcpInterval.end;
int lowestPosition = 0;
for (int i = suffixStart; i <= suffixEnd; i++) {
int tokenPosition = tokenIndex.suffix_array[i];
if (tokenPosition < lowestPosition)
lowestPosition = tokenPosition;
}
return lowestPosition;
}
public static <T> List<T> copyIterable(Iterable<T> iterable) {
return copyIterator(iterable.iterator());
}
public static <T> List<T> copyIterator(Iterator<T> iter) {
List<T> copy = new ArrayList<T>();
while (iter.hasNext())
copy.add(iter.next());
return copy;
}
class Matcher {
Boolean match(VariantGraph.Vertex a, Token b) {
return false;
}
}
class SimpleMatcher extends Matcher {
@Override
Boolean match(VariantGraph.Vertex a, Token b) {
SimpleToken sa = (SimpleToken) a.tokens().iterator().next();
SimpleToken sb = (SimpleToken) b;
return sa.getNormalized().equals(sb.getNormalized());
}
}
// // 1) We need to know the neighbors in the decision graph
// // There are three possibilities in a 2D space
// // 2) We need to calculate the heuristic for each
// // 3) We need to score each
// class TwoDimensionalDecisionGraph extends AstarAlgorithm<DecisionGraphNode, DecisionGraphNodeCost> {
//
// private final VariantGraph.Vertex[] vertices;
// private final Token[] tokens;
// private int startRangeWitness2;
// private Matcher matcher;
//
// public TwoDimensionalDecisionGraph(VariantGraph.Vertex[] vertices, Token[] tokens, int startRangeWitness2) {
// this.vertices = vertices;
// this.tokens = tokens;
// this.startRangeWitness2 = startRangeWitness2;
// this.matcher = new SimpleMatcher();
// }
//
// @Override
// protected boolean isGoal(DecisionGraphNode node) {
// return isHorizontalEnd(node) && isVerticalEnd(node);
// }
//
// private boolean isHorizontalEnd(DecisionGraphNode node) {
// return node.startPosWitness1 == vertices.length;
// }
//
// private boolean isVerticalEnd(DecisionGraphNode node) {
// return node.startPosWitness2 == tokens.length;
// }
//
// @Override
// protected Iterable<DecisionGraphNode> neighborNodes(DecisionGraphNode current) {
// // In a 2D approach there are 3 possibilities
// List<DecisionGraphNode> children = new ArrayList<>();
// boolean xEnd = isHorizontalEnd(current);
// boolean yEnd = isVerticalEnd(current);
// if (!xEnd) {
// DecisionGraphNode child1 = current.copy();
// child1.startPosWitness1++;
// child1.editOperation = EditOperationEnum.SKIP_TOKEN_GRAPH;
// children.add(child1);
// }
// if (!yEnd) {
// DecisionGraphNode child2 = current.copy();
// child2.startPosWitness2++;
// child2.editOperation = EditOperationEnum.SKIP_TOKEN_WITNESS;
// children.add(child2);
// }
// if (!xEnd && !yEnd) {
// DecisionGraphNode child3 = current.copy();
// child3.startPosWitness1++;
// child3.startPosWitness2++;
// child3.editOperation = EditOperationEnum.MATCH_TOKENS_OR_REPLACE;
// children.add(child3);
// }
// return children;
// }
//
// @Override
// protected DecisionGraphNodeCost heuristicCostEstimate(DecisionGraphNode node) {
// int potentialMatchesGraph = 0;
// for (int i = node.startPosWitness1; i < vertices.length; i++) {
// VariantGraph.Vertex v = vertices[i];
// if (vertexToLCP.get(v)!=null) {
// potentialMatchesGraph++;
// }
// }
//
// int potentialMatchesWitness = 0;
// for (int i = startRangeWitness2 + node.startPosWitness2; i < startRangeWitness2+tokens.length; i++) {
// if (lcp_interval_array[i] != null) {
// potentialMatchesWitness++;
// }
// }
// int potentialMatches = Math.min(potentialMatchesGraph, potentialMatchesWitness);
// return new DecisionGraphNodeCost(potentialMatches);
// }
//
// //NOTE: this scorer assigns positive costs
// @Override
// protected DecisionGraphNodeCost distBetween(DecisionGraphNode current, DecisionGraphNode neighbor) {
// if (neighbor.editOperation == EditOperationEnum.MATCH_TOKENS_OR_REPLACE) {
// VariantGraph.Vertex v = vertex(neighbor);
// Token t = token(neighbor);
// Boolean match = matcher.match(v, t);
// if (match) {
// // Log("match: "+(neighbor.startPosWitness1-1)+", "+(neighbor.startPosWitness2-1));
// neighbor.match = true;
// return new DecisionGraphNodeCost(1);
// }
// }
// return new DecisionGraphNodeCost(0);
// }
//
// public VariantGraph.Vertex vertex(DecisionGraphNode node) {
// return vertices[node.startPosWitness1-1];
// }
//
// public Token token(DecisionGraphNode node) {
// return tokens[node.startPosWitness2-1];
// }
// }
}
|
11551_5 | import java.util.ArrayList;
import java.util.List;
/*
* author: Ronald Haentjens Dekker
* date: 11-09-2018
*
* in een tree automata willen we een tree bijhouden
* In een state machine ga je van state naar statae
* Echter in een tree model zijn er meerdere mogelijke non terminls
* die je kunt vervangen.
*/
public class StateMachine {
private Tree<TagNode> completeTree; // tree die we aan het opbouwen zijn
private TagNode pointerToCurrentNode;
private List<TransitionRule> rules;
public StateMachine() {
TagNode root = new TagNode("ROOT");
this.completeTree = new Tree<>(root);
this.pointerToCurrentNode = root;
// nu hebben we nog transitie rules nodig.
this.rules = new ArrayList<>();
}
public void addTransitionRule(TransitionRule transitionRule) {
this.rules.add(transitionRule);
}
// bij de state machine komen zaken binnen; input
// dan moeten we kijek aan den hand van de input of er een transitie rule voor is.
// zo niet; dan zitten we in een error.
// input zou eigenlijk tree moeten zijn.
public void processInput(String tag) {
// We zoeken eerst op naar welke node de huidige pointer verwijst.
// Dan kijken we welke transitierules er zijn voor dat type node.
boolean found = false;
TransitionRule theRule = null;
for (TransitionRule rule : rules) {
// dit klopt niet!
if (rule.lefthandsideIsApplicableFor(pointerToCurrentNode.tag)) {
found=true;
theRule=rule;
break;
}
}
if (!found) {
throw new RuntimeException("No transition rule found! Current state: "+this.pointerToCurrentNode.tag+" -> "+tag);
}
System.out.println("Transition rule found! We want to know the right hand side");
System.out.println("Expectation: "+theRule.righthandside);
// Nu moeten we checken of de transitierule die we gevonden hebben ook past bij de wat binnen kregen
// Ik weet nog niet hoe dat moet gewoon bij
// We vervangen de aangewezen node door de nieuwe van de RHS
// de current pointer moet dna naar het eerste kind van de RHS
// NB: Dit is te simplistisch.
// check whether tag of right hand side is the same as the incoming tag.
if (theRule.righthandside.root.tag.equals(tag)) {
// woohoo expectations matched!
//throw new RuntimeException("expectations are met!");
// set the current pointer
// aargh we now need a replace, with a parent value, which we don't have yet
// het gebeuren hier is wat moeilijk, want het kan zijn dat de root vervangen wordt..
TransitionRule finalTheRule = theRule;
// als het om de root node gaat vervangen we gewoon de hele tree
if (pointerToCurrentNode == completeTree.root) {
completeTree = finalTheRule.righthandside;
} else {
completeTree.mergeTreeIntoCurrentTree(finalTheRule.righthandside, pointerToCurrentNode);
}
// gaat dit altijd goed... we will see
pointerToCurrentNode = finalTheRule.righthandside.children.get(finalTheRule.righthandside.root).get(0);
}
//! Dan gaan we opzoek naar de transitierule van de huidige state
//! Gegeven de transitierule en de nieuwe op basis van de input.
// we gaan alle transitierules af.
// het zou beter zijn om dit te indexeren; maar ok..
}
}
| rhdekker/treegrammar | src/main/java/StateMachine.java | 949 | // zo niet; dan zitten we in een error. | line_comment | nl | import java.util.ArrayList;
import java.util.List;
/*
* author: Ronald Haentjens Dekker
* date: 11-09-2018
*
* in een tree automata willen we een tree bijhouden
* In een state machine ga je van state naar statae
* Echter in een tree model zijn er meerdere mogelijke non terminls
* die je kunt vervangen.
*/
public class StateMachine {
private Tree<TagNode> completeTree; // tree die we aan het opbouwen zijn
private TagNode pointerToCurrentNode;
private List<TransitionRule> rules;
public StateMachine() {
TagNode root = new TagNode("ROOT");
this.completeTree = new Tree<>(root);
this.pointerToCurrentNode = root;
// nu hebben we nog transitie rules nodig.
this.rules = new ArrayList<>();
}
public void addTransitionRule(TransitionRule transitionRule) {
this.rules.add(transitionRule);
}
// bij de state machine komen zaken binnen; input
// dan moeten we kijek aan den hand van de input of er een transitie rule voor is.
// zo niet;<SUF>
// input zou eigenlijk tree moeten zijn.
public void processInput(String tag) {
// We zoeken eerst op naar welke node de huidige pointer verwijst.
// Dan kijken we welke transitierules er zijn voor dat type node.
boolean found = false;
TransitionRule theRule = null;
for (TransitionRule rule : rules) {
// dit klopt niet!
if (rule.lefthandsideIsApplicableFor(pointerToCurrentNode.tag)) {
found=true;
theRule=rule;
break;
}
}
if (!found) {
throw new RuntimeException("No transition rule found! Current state: "+this.pointerToCurrentNode.tag+" -> "+tag);
}
System.out.println("Transition rule found! We want to know the right hand side");
System.out.println("Expectation: "+theRule.righthandside);
// Nu moeten we checken of de transitierule die we gevonden hebben ook past bij de wat binnen kregen
// Ik weet nog niet hoe dat moet gewoon bij
// We vervangen de aangewezen node door de nieuwe van de RHS
// de current pointer moet dna naar het eerste kind van de RHS
// NB: Dit is te simplistisch.
// check whether tag of right hand side is the same as the incoming tag.
if (theRule.righthandside.root.tag.equals(tag)) {
// woohoo expectations matched!
//throw new RuntimeException("expectations are met!");
// set the current pointer
// aargh we now need a replace, with a parent value, which we don't have yet
// het gebeuren hier is wat moeilijk, want het kan zijn dat de root vervangen wordt..
TransitionRule finalTheRule = theRule;
// als het om de root node gaat vervangen we gewoon de hele tree
if (pointerToCurrentNode == completeTree.root) {
completeTree = finalTheRule.righthandside;
} else {
completeTree.mergeTreeIntoCurrentTree(finalTheRule.righthandside, pointerToCurrentNode);
}
// gaat dit altijd goed... we will see
pointerToCurrentNode = finalTheRule.righthandside.children.get(finalTheRule.righthandside.root).get(0);
}
//! Dan gaan we opzoek naar de transitierule van de huidige state
//! Gegeven de transitierule en de nieuwe op basis van de input.
// we gaan alle transitierules af.
// het zou beter zijn om dit te indexeren; maar ok..
}
}
|
35775_33 | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
/**
* <p>Decodes Codabar barcodes.</p>
*
* @author Bas Vijfwinkel
*/
public final class CodaBarReader extends OneDReader {
private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE
* : c is equal to the * pattern NOTE : d is equal to the e pattern
*/
private static final int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
0x01A, 0x029 //TN
};
// minimal number of characters that should be present (inclusing start and stop characters)
// this check has been added to reduce the number of false positive on other formats
// until the cause for this behaviour has been determined
// under normal circumstances this should be set to 3
private static final int minCharacterLength = 6;
// multiple start/end patterns
// official start and end patterns
private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};
// some codabar generator allow the codabar string to be closed by every character
//private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException {
int[] start = findAsteriskPattern(row);
start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?
int nextStart = start[1];
int end = row.getSize();
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
StringBuffer result = new StringBuffer();
//int[] counters = new int[7];
int[] counters;
int lastStart;
do {
counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters
recordPattern(row, nextStart, counters);
char decodedChar = toNarrowWidePattern(counters);
if (decodedChar == '!') {
throw NotFoundException.getNotFoundInstance();
}
result.append(decodedChar);
lastStart = nextStart;
for (int i = 0; i < counters.length; i++) {
nextStart += counters[i];
}
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
} while (nextStart < end); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int i = 0; i < counters.length; i++) {
lastPatternSize += counters[i];
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {
throw NotFoundException.getNotFoundInstance();
}
// valid result?
if (result.length() < 2)
{
throw NotFoundException.getNotFoundInstance();
}
char startchar = result.charAt(0);
if (!arrayContains(STARTEND_ENCODING, startchar))
{
//invalid start character
throw NotFoundException.getNotFoundInstance();
}
// find stop character
for (int k = 1;k < result.length() ;k++)
{
if (result.charAt(k) == startchar)
{
// found stop character -> discard rest of the string
if ((k+1) != result.length())
{
result.delete(k+1,result.length()-1);
k = result.length();// break out of loop
}
}
}
// remove stop/start characters character and check if a string longer than 5 characters is contained
if (result.length() > minCharacterLength)
{
result.deleteCharAt(result.length()-1);
result.deleteCharAt(0);
}
else
{
// Almost surely a false positive ( start + stop + at least 1 character)
throw NotFoundException.getNotFoundInstance();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = (float) (nextStart + lastStart) / 2.0f;
return new Result(
result.toString(),
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODABAR);
}
private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
int width = row.getSize();
int rowOffset = 0;
while (rowOffset < width) {
if (row.get(rowOffset)) {
break;
}
rowOffset++;
}
int counterPosition = 0;
int[] counters = new int[7];
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
boolean pixel = row.get(i);
if (pixel ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
try {
if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
return new int[]{patternStart, i};
}
}
} catch (IllegalArgumentException re) {
// no match, continue
}
patternStart += counters[0] + counters[1];
for (int y = 2; y < patternLength; y++) {
counters[y - 2] = counters[y];
}
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
private static boolean arrayContains(char[] array, char key) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return true;
}
}
}
return false;
}
private static char toNarrowWidePattern(int[] counters) {
// BAS : I have changed the following part because some codabar images would fail with the original routine
// I took from the Code39Reader.java file
// ----------- change start
int numCounters = counters.length;
int maxNarrowCounter = 0;
int minCounter = Integer.MAX_VALUE;
for (int i = 0; i < numCounters; i++) {
if (counters[i] < minCounter) {
minCounter = counters[i];
}
if (counters[i] > maxNarrowCounter) {
maxNarrowCounter = counters[i];
}
}
// ---------- change end
do {
int wideCounters = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
if (counters[i] > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
}
}
if ((wideCounters == 2) || (wideCounters == 3)) {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
}
maxNarrowCounter--;
} while (maxNarrowCounter > minCounter);
return '!';
}
}
| rhomobile/rhodes | lib/commonAPI/barcode/ext/platform/android/src/com/google/zxing/oned/CodaBarReader.java | 2,809 | // ---------- change end | line_comment | nl | /*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.oned;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;
/**
* <p>Decodes Codabar barcodes.</p>
*
* @author Bas Vijfwinkel
*/
public final class CodaBarReader extends OneDReader {
private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";
private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();
/**
* These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
* each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE
* : c is equal to the * pattern NOTE : d is equal to the e pattern
*/
private static final int[] CHARACTER_ENCODINGS = {
0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
0x01A, 0x029 //TN
};
// minimal number of characters that should be present (inclusing start and stop characters)
// this check has been added to reduce the number of false positive on other formats
// until the cause for this behaviour has been determined
// under normal circumstances this should be set to 3
private static final int minCharacterLength = 6;
// multiple start/end patterns
// official start and end patterns
private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};
// some codabar generator allow the codabar string to be closed by every character
//private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};
// some industries use a checksum standard but this is not part of the original codabar standard
// for more information see : http://www.mecsw.com/specs/codabar.html
public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException {
int[] start = findAsteriskPattern(row);
start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?
int nextStart = start[1];
int end = row.getSize();
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
StringBuffer result = new StringBuffer();
//int[] counters = new int[7];
int[] counters;
int lastStart;
do {
counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters
recordPattern(row, nextStart, counters);
char decodedChar = toNarrowWidePattern(counters);
if (decodedChar == '!') {
throw NotFoundException.getNotFoundInstance();
}
result.append(decodedChar);
lastStart = nextStart;
for (int i = 0; i < counters.length; i++) {
nextStart += counters[i];
}
// Read off white space
while (nextStart < end && !row.get(nextStart)) {
nextStart++;
}
} while (nextStart < end); // no fixed end pattern so keep on reading while data is available
// Look for whitespace after pattern:
int lastPatternSize = 0;
for (int i = 0; i < counters.length; i++) {
lastPatternSize += counters[i];
}
int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
// If 50% of last pattern size, following last pattern, is not whitespace, fail
// (but if it's whitespace to the very end of the image, that's OK)
if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {
throw NotFoundException.getNotFoundInstance();
}
// valid result?
if (result.length() < 2)
{
throw NotFoundException.getNotFoundInstance();
}
char startchar = result.charAt(0);
if (!arrayContains(STARTEND_ENCODING, startchar))
{
//invalid start character
throw NotFoundException.getNotFoundInstance();
}
// find stop character
for (int k = 1;k < result.length() ;k++)
{
if (result.charAt(k) == startchar)
{
// found stop character -> discard rest of the string
if ((k+1) != result.length())
{
result.delete(k+1,result.length()-1);
k = result.length();// break out of loop
}
}
}
// remove stop/start characters character and check if a string longer than 5 characters is contained
if (result.length() > minCharacterLength)
{
result.deleteCharAt(result.length()-1);
result.deleteCharAt(0);
}
else
{
// Almost surely a false positive ( start + stop + at least 1 character)
throw NotFoundException.getNotFoundInstance();
}
float left = (float) (start[1] + start[0]) / 2.0f;
float right = (float) (nextStart + lastStart) / 2.0f;
return new Result(
result.toString(),
null,
new ResultPoint[]{
new ResultPoint(left, (float) rowNumber),
new ResultPoint(right, (float) rowNumber)},
BarcodeFormat.CODABAR);
}
private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
int width = row.getSize();
int rowOffset = 0;
while (rowOffset < width) {
if (row.get(rowOffset)) {
break;
}
rowOffset++;
}
int counterPosition = 0;
int[] counters = new int[7];
int patternStart = rowOffset;
boolean isWhite = false;
int patternLength = counters.length;
for (int i = rowOffset; i < width; i++) {
boolean pixel = row.get(i);
if (pixel ^ isWhite) {
counters[counterPosition]++;
} else {
if (counterPosition == patternLength - 1) {
try {
if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {
// Look for whitespace before start pattern, >= 50% of width of start pattern
if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
return new int[]{patternStart, i};
}
}
} catch (IllegalArgumentException re) {
// no match, continue
}
patternStart += counters[0] + counters[1];
for (int y = 2; y < patternLength; y++) {
counters[y - 2] = counters[y];
}
counters[patternLength - 2] = 0;
counters[patternLength - 1] = 0;
counterPosition--;
} else {
counterPosition++;
}
counters[counterPosition] = 1;
isWhite ^= true; // isWhite = !isWhite;
}
}
throw NotFoundException.getNotFoundInstance();
}
private static boolean arrayContains(char[] array, char key) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
if (array[i] == key) {
return true;
}
}
}
return false;
}
private static char toNarrowWidePattern(int[] counters) {
// BAS : I have changed the following part because some codabar images would fail with the original routine
// I took from the Code39Reader.java file
// ----------- change start
int numCounters = counters.length;
int maxNarrowCounter = 0;
int minCounter = Integer.MAX_VALUE;
for (int i = 0; i < numCounters; i++) {
if (counters[i] < minCounter) {
minCounter = counters[i];
}
if (counters[i] > maxNarrowCounter) {
maxNarrowCounter = counters[i];
}
}
// ---------- change<SUF>
do {
int wideCounters = 0;
int pattern = 0;
for (int i = 0; i < numCounters; i++) {
if (counters[i] > maxNarrowCounter) {
pattern |= 1 << (numCounters - 1 - i);
wideCounters++;
}
}
if ((wideCounters == 2) || (wideCounters == 3)) {
for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
if (CHARACTER_ENCODINGS[i] == pattern) {
return ALPHABET[i];
}
}
}
maxNarrowCounter--;
} while (maxNarrowCounter > minCounter);
return '!';
}
}
|
113906_24 | package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
* @author JSON.org
* @version 2011-02-11
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = new Character('&');
/** The Character '''. */
public static final Character APOS = new Character('\'');
/** The Character '!'. */
public static final Character BANG = new Character('!');
/** The Character '='. */
public static final Character EQ = new Character('=');
/** The Character '>'. */
public static final Character GT = new Character('>');
/** The Character '<'. */
public static final Character LT = new Character('<');
/** The Character '?'. */
public static final Character QUEST = new Character('?');
/** The Character '"'. */
public static final Character QUOT = new Character('"');
/** The Character '/'. */
public static final Character SLASH = new Character('/');
/**
* Replace special characters with XML escapes:
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
* @param string The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes.
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
* @param x The XMLTokener containing the source string.
* @param context The JSONObject that will include the new material.
* @param name The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
JSONObject jsonobject = null;
String string;
String tagName;
Object token;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
token = x.nextToken();
// <!
if (token == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
token = x.nextToken();
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
context.accumulate("content", string);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == LT) {
i += 1;
} else if (token == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (token == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (token == SLASH) {
// Close tag </
token = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag " + token);
}
if (!token.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + token);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
tagName = (String)token;
token = null;
jsonobject = new JSONObject();
for (;;) {
if (token == null) {
token = x.nextToken();
}
// attribute = value
if (token instanceof String) {
string = (String)token;
token = x.nextToken();
if (token == EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
jsonobject.accumulate(string,
XML.stringToValue((String)token));
token = null;
} else {
jsonobject.accumulate(string, "");
}
// Empty tag <.../>
} else if (token == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
if (jsonobject.length() > 0) {
context.accumulate(tagName, jsonobject);
} else {
context.accumulate(tagName, "");
}
return false;
// Content, between <...> and </...>
} else if (token == GT) {
for (;;) {
token = x.nextContent();
if (token == null) {
if (tagName != null) {
throw x.syntaxError("Unclosed tag " + tagName);
}
return false;
} else if (token instanceof String) {
string = (String)token;
if (string.length() > 0) {
jsonobject.accumulate("content",
XML.stringToValue(string));
}
// Nested element
} else if (token == LT) {
if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) {
context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 &&
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content"));
} else {
context.accumulate(tagName, jsonobject);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points.
* @param string A String.
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
if ("".equals(string)) {
return string;
}
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
}
if ("0".equals(string)) {
return new Integer(0);
}
// If it might be a number, try converting it. If that doesn't work,
// return the string.
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}
return string;
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
* because JSON is a data format and XML is a document format. XML uses
* elements, attributes, and content text, while JSON uses unordered
* collections of name/value pairs and arrays of values. JSON does not
* does not like to distinguish between elements and attributes.
* Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code><[ [ ]]></code> are ignored.
* @param string The source string.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, jo, null);
}
return jo;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object) throws JSONException {
return toString(object, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, String tagName)
throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
if (object instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
}
// Loop thru the keys.
jo = (JSONObject)object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
value = jo.opt(key);
if (value == null) {
value = "";
}
if (value instanceof String) {
string = (String)value;
} else {
string = null;
}
// Emit content in body
if ("content".equals(key)) {
if (value instanceof JSONArray) {
ja = (JSONArray)value;
length = ja.length();
for (i = 0; i < length; i += 1) {
if (i > 0) {
sb.append('\n');
}
sb.append(escape(ja.get(i).toString()));
}
} else {
sb.append(escape(value.toString()));
}
// Emit an array of similar keys
} else if (value instanceof JSONArray) {
ja = (JSONArray)value;
length = ja.length();
for (i = 0; i < length; i += 1) {
value = ja.get(i);
if (value instanceof JSONArray) {
sb.append('<');
sb.append(key);
sb.append('>');
sb.append(toString(value));
sb.append("</");
sb.append(key);
sb.append('>');
} else {
sb.append(toString(value, key));
}
}
} else if ("".equals(value)) {
sb.append('<');
sb.append(key);
sb.append("/>");
// Emit a new tag <k>
} else {
sb.append(toString(value, key));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
sb.append("</");
sb.append(tagName);
sb.append('>');
}
return sb.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} else {
if (object.getClass().isArray()) {
object = new JSONArray(object);
}
if (object instanceof JSONArray) {
ja = (JSONArray)object;
length = ja.length();
for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}
} | rhomobile/rhostudio | rhogen-wizard/thridparty/org/json/XML.java | 4,461 | // Content, between <...> and </...> | line_comment | nl | package org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import java.util.Iterator;
/**
* This provides static methods to convert an XML text into a JSONObject,
* and to covert a JSONObject into an XML text.
* @author JSON.org
* @version 2011-02-11
*/
public class XML {
/** The Character '&'. */
public static final Character AMP = new Character('&');
/** The Character '''. */
public static final Character APOS = new Character('\'');
/** The Character '!'. */
public static final Character BANG = new Character('!');
/** The Character '='. */
public static final Character EQ = new Character('=');
/** The Character '>'. */
public static final Character GT = new Character('>');
/** The Character '<'. */
public static final Character LT = new Character('<');
/** The Character '?'. */
public static final Character QUEST = new Character('?');
/** The Character '"'. */
public static final Character QUOT = new Character('"');
/** The Character '/'. */
public static final Character SLASH = new Character('/');
/**
* Replace special characters with XML escapes:
* <pre>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &quot;
* </pre>
* @param string The string to be escaped.
* @return The escaped string.
*/
public static String escape(String string) {
StringBuffer sb = new StringBuffer();
for (int i = 0, length = string.length(); i < length; i++) {
char c = string.charAt(i);
switch (c) {
case '&':
sb.append("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
break;
default:
sb.append(c);
}
}
return sb.toString();
}
/**
* Throw an exception if the string contains whitespace.
* Whitespace is not allowed in tagNames and attributes.
* @param string
* @throws JSONException
*/
public static void noSpace(String string) throws JSONException {
int i, length = string.length();
if (length == 0) {
throw new JSONException("Empty string.");
}
for (i = 0; i < length; i += 1) {
if (Character.isWhitespace(string.charAt(i))) {
throw new JSONException("'" + string +
"' contains a space character.");
}
}
}
/**
* Scan the content following the named tag, attaching it to the context.
* @param x The XMLTokener containing the source string.
* @param context The JSONObject that will include the new material.
* @param name The tag name.
* @return true if the close tag is processed.
* @throws JSONException
*/
private static boolean parse(XMLTokener x, JSONObject context,
String name) throws JSONException {
char c;
int i;
JSONObject jsonobject = null;
String string;
String tagName;
Object token;
// Test for and skip past these forms:
// <!-- ... -->
// <! ... >
// <![ ... ]]>
// <? ... ?>
// Report errors for these forms:
// <>
// <=
// <<
token = x.nextToken();
// <!
if (token == BANG) {
c = x.next();
if (c == '-') {
if (x.next() == '-') {
x.skipPast("-->");
return false;
}
x.back();
} else if (c == '[') {
token = x.nextToken();
if ("CDATA".equals(token)) {
if (x.next() == '[') {
string = x.nextCDATA();
if (string.length() > 0) {
context.accumulate("content", string);
}
return false;
}
}
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
do {
token = x.nextMeta();
if (token == null) {
throw x.syntaxError("Missing '>' after '<!'.");
} else if (token == LT) {
i += 1;
} else if (token == GT) {
i -= 1;
}
} while (i > 0);
return false;
} else if (token == QUEST) {
// <?
x.skipPast("?>");
return false;
} else if (token == SLASH) {
// Close tag </
token = x.nextToken();
if (name == null) {
throw x.syntaxError("Mismatched close tag " + token);
}
if (!token.equals(name)) {
throw x.syntaxError("Mismatched " + name + " and " + token);
}
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped close tag");
}
return true;
} else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
} else {
tagName = (String)token;
token = null;
jsonobject = new JSONObject();
for (;;) {
if (token == null) {
token = x.nextToken();
}
// attribute = value
if (token instanceof String) {
string = (String)token;
token = x.nextToken();
if (token == EQ) {
token = x.nextToken();
if (!(token instanceof String)) {
throw x.syntaxError("Missing value");
}
jsonobject.accumulate(string,
XML.stringToValue((String)token));
token = null;
} else {
jsonobject.accumulate(string, "");
}
// Empty tag <.../>
} else if (token == SLASH) {
if (x.nextToken() != GT) {
throw x.syntaxError("Misshaped tag");
}
if (jsonobject.length() > 0) {
context.accumulate(tagName, jsonobject);
} else {
context.accumulate(tagName, "");
}
return false;
// Content, between<SUF>
} else if (token == GT) {
for (;;) {
token = x.nextContent();
if (token == null) {
if (tagName != null) {
throw x.syntaxError("Unclosed tag " + tagName);
}
return false;
} else if (token instanceof String) {
string = (String)token;
if (string.length() > 0) {
jsonobject.accumulate("content",
XML.stringToValue(string));
}
// Nested element
} else if (token == LT) {
if (parse(x, jsonobject, tagName)) {
if (jsonobject.length() == 0) {
context.accumulate(tagName, "");
} else if (jsonobject.length() == 1 &&
jsonobject.opt("content") != null) {
context.accumulate(tagName,
jsonobject.opt("content"));
} else {
context.accumulate(tagName, jsonobject);
}
return false;
}
}
}
} else {
throw x.syntaxError("Misshaped tag");
}
}
}
}
/**
* Try to convert a string into a number, boolean, or null. If the string
* can't be converted, return the string. This is much less ambitious than
* JSONObject.stringToValue, especially because it does not attempt to
* convert plus forms, octal forms, hex forms, or E forms lacking decimal
* points.
* @param string A String.
* @return A simple JSON value.
*/
public static Object stringToValue(String string) {
if ("".equals(string)) {
return string;
}
if ("true".equalsIgnoreCase(string)) {
return Boolean.TRUE;
}
if ("false".equalsIgnoreCase(string)) {
return Boolean.FALSE;
}
if ("null".equalsIgnoreCase(string)) {
return JSONObject.NULL;
}
if ("0".equals(string)) {
return new Integer(0);
}
// If it might be a number, try converting it. If that doesn't work,
// return the string.
try {
char initial = string.charAt(0);
boolean negative = false;
if (initial == '-') {
initial = string.charAt(1);
negative = true;
}
if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') {
return string;
}
if ((initial >= '0' && initial <= '9')) {
if (string.indexOf('.') >= 0) {
return Double.valueOf(string);
} else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) {
Long myLong = new Long(string);
if (myLong.longValue() == myLong.intValue()) {
return new Integer(myLong.intValue());
} else {
return myLong;
}
}
}
} catch (Exception ignore) {
}
return string;
}
/**
* Convert a well-formed (but not necessarily valid) XML string into a
* JSONObject. Some information may be lost in this transformation
* because JSON is a data format and XML is a document format. XML uses
* elements, attributes, and content text, while JSON uses unordered
* collections of name/value pairs and arrays of values. JSON does not
* does not like to distinguish between elements and attributes.
* Sequences of similar elements are represented as JSONArrays. Content
* text may be placed in a "content" member. Comments, prologs, DTDs, and
* <code><[ [ ]]></code> are ignored.
* @param string The source string.
* @return A JSONObject containing the structured data from the XML string.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
XMLTokener x = new XMLTokener(string);
while (x.more() && x.skipPast("<")) {
parse(x, jo, null);
}
return jo;
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object) throws JSONException {
return toString(object, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, String tagName)
throws JSONException {
StringBuffer sb = new StringBuffer();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator keys;
int length;
String string;
Object value;
if (object instanceof JSONObject) {
// Emit <tagName>
if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
}
// Loop thru the keys.
jo = (JSONObject)object;
keys = jo.keys();
while (keys.hasNext()) {
key = keys.next().toString();
value = jo.opt(key);
if (value == null) {
value = "";
}
if (value instanceof String) {
string = (String)value;
} else {
string = null;
}
// Emit content in body
if ("content".equals(key)) {
if (value instanceof JSONArray) {
ja = (JSONArray)value;
length = ja.length();
for (i = 0; i < length; i += 1) {
if (i > 0) {
sb.append('\n');
}
sb.append(escape(ja.get(i).toString()));
}
} else {
sb.append(escape(value.toString()));
}
// Emit an array of similar keys
} else if (value instanceof JSONArray) {
ja = (JSONArray)value;
length = ja.length();
for (i = 0; i < length; i += 1) {
value = ja.get(i);
if (value instanceof JSONArray) {
sb.append('<');
sb.append(key);
sb.append('>');
sb.append(toString(value));
sb.append("</");
sb.append(key);
sb.append('>');
} else {
sb.append(toString(value, key));
}
}
} else if ("".equals(value)) {
sb.append('<');
sb.append(key);
sb.append("/>");
// Emit a new tag <k>
} else {
sb.append(toString(value, key));
}
}
if (tagName != null) {
// Emit the </tagname> close tag
sb.append("</");
sb.append(tagName);
sb.append('>');
}
return sb.toString();
// XML does not have good support for arrays. If an array appears in a place
// where XML is lacking, synthesize an <array> element.
} else {
if (object.getClass().isArray()) {
object = new JSONArray(object);
}
if (object instanceof JSONArray) {
ja = (JSONArray)object;
length = ja.length();
for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
} else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" :
(string.length() == 0) ? "<" + tagName + "/>" :
"<" + tagName + ">" + string + "</" + tagName + ">";
}
}
}
} |
163363_0 | package nl.itris.mjop.elements.catalog.elementen.entity;
import nl.itris.mjop.elements.catalog.handelingen.boundary.Handeling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Element {
private Long id = null;
private String omschrijving = null;
private String code = null;
private String elementgroep = null;
private String levensduur = null;
private nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort = null;
private Element hoofdelement = null;
private List<Handeling> handelingen = new ArrayList<Handeling>();
/**
**/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
/**
**/
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
* Nieuwbouw
**/
public String getElementgroep() {
return elementgroep;
}
public void setElementgroep(String elementgroep) {
this.elementgroep = elementgroep;
}
/**
**/
public String getLevensduur() {
return levensduur;
}
public void setLevensduur(String levensduur) {
this.levensduur = levensduur;
}
/**
**/
public nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort getStdkostensoort() {
return stdkostensoort;
}
public void setStdkostensoort(nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort) {
this.stdkostensoort = stdkostensoort;
}
/**
**/
public Element getHoofdelement() {
return hoofdelement;
}
public void setHoofdelement(Element hoofdelement) {
this.hoofdelement = hoofdelement;
}
/**
**/
public List<Handeling> getHandelingen() {
return handelingen;
}
public void setHandelingen(List<Handeling> handelingen) {
this.handelingen = handelingen;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Element element = (Element) o;
return Objects.equals(id, element.id) &&
Objects.equals(omschrijving, element.omschrijving) &&
Objects.equals(code, element.code) &&
Objects.equals(elementgroep, element.elementgroep) &&
Objects.equals(levensduur, element.levensduur) &&
Objects.equals(stdkostensoort, element.stdkostensoort) &&
Objects.equals(hoofdelement, element.hoofdelement) &&
Objects.equals(handelingen, element.handelingen);
}
@Override
public int hashCode() {
return Objects.hash(id, omschrijving, code, elementgroep, levensduur, stdkostensoort, hoofdelement, handelingen);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Element {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" omschrijving: ").append(toIndentedString(omschrijving)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" elementgroep: ").append(toIndentedString(elementgroep)).append("\n");
sb.append(" levensduur: ").append(toIndentedString(levensduur)).append("\n");
sb.append(" stdkostensoort: ").append(toIndentedString(stdkostensoort)).append("\n");
sb.append(" hoofdelement: ").append(toIndentedString(hoofdelement)).append("\n");
sb.append(" handelingen: ").append(toIndentedString(handelingen)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| rhuss/fabric8-maven-plugin-1 | src/main/java/nl/itris/mjop/elements/catalog/elementen/entity/Element.java | 1,354 | /**
* Nieuwbouw
**/ | block_comment | nl | package nl.itris.mjop.elements.catalog.elementen.entity;
import nl.itris.mjop.elements.catalog.handelingen.boundary.Handeling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Element {
private Long id = null;
private String omschrijving = null;
private String code = null;
private String elementgroep = null;
private String levensduur = null;
private nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort = null;
private Element hoofdelement = null;
private List<Handeling> handelingen = new ArrayList<Handeling>();
/**
**/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
/**
**/
public String getOmschrijving() {
return omschrijving;
}
public void setOmschrijving(String omschrijving) {
this.omschrijving = omschrijving;
}
/**
**/
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
/**
* Nieuwbouw
<SUF>*/
public String getElementgroep() {
return elementgroep;
}
public void setElementgroep(String elementgroep) {
this.elementgroep = elementgroep;
}
/**
**/
public String getLevensduur() {
return levensduur;
}
public void setLevensduur(String levensduur) {
this.levensduur = levensduur;
}
/**
**/
public nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort getStdkostensoort() {
return stdkostensoort;
}
public void setStdkostensoort(nl.itris.mjop.elements.catalog.elementen.boundary.Kostensoort stdkostensoort) {
this.stdkostensoort = stdkostensoort;
}
/**
**/
public Element getHoofdelement() {
return hoofdelement;
}
public void setHoofdelement(Element hoofdelement) {
this.hoofdelement = hoofdelement;
}
/**
**/
public List<Handeling> getHandelingen() {
return handelingen;
}
public void setHandelingen(List<Handeling> handelingen) {
this.handelingen = handelingen;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Element element = (Element) o;
return Objects.equals(id, element.id) &&
Objects.equals(omschrijving, element.omschrijving) &&
Objects.equals(code, element.code) &&
Objects.equals(elementgroep, element.elementgroep) &&
Objects.equals(levensduur, element.levensduur) &&
Objects.equals(stdkostensoort, element.stdkostensoort) &&
Objects.equals(hoofdelement, element.hoofdelement) &&
Objects.equals(handelingen, element.handelingen);
}
@Override
public int hashCode() {
return Objects.hash(id, omschrijving, code, elementgroep, levensduur, stdkostensoort, hoofdelement, handelingen);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Element {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" omschrijving: ").append(toIndentedString(omschrijving)).append("\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" elementgroep: ").append(toIndentedString(elementgroep)).append("\n");
sb.append(" levensduur: ").append(toIndentedString(levensduur)).append("\n");
sb.append(" stdkostensoort: ").append(toIndentedString(stdkostensoort)).append("\n");
sb.append(" hoofdelement: ").append(toIndentedString(hoofdelement)).append("\n");
sb.append(" handelingen: ").append(toIndentedString(handelingen)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
781_12 | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//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 jd.plugins.decrypter;
import java.util.ArrayList;
import java.util.HashMap;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" })
public class DeredactieBe extends PluginForDecrypt {
public DeredactieBe(PluginWrapper wrapper) {
super(wrapper);
}
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
String parameter = param.toString();
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(parameter);
if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {
decryptedLinks.add(this.createOfflinelink(parameter));
return decryptedLinks;
}
HashMap<String, String> mediaValue = new HashMap<String, String>();
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {
mediaValue.put(s[0], s[1]);
}
final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src");
if (finalurl == null) {
try {
decryptedLinks.add(this.createOfflinelink(parameter));
} catch (final Throwable t) {
logger.info("Offline Link: " + parameter);
}
return decryptedLinks;
}
if (finalurl.contains("youtube.com")) {
decryptedLinks.add(createDownloadlink(finalurl));
} else {
decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/")));
}
return decryptedLinks;
}
/* NO OVERRIDE!! */
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {
return false;
}
} | ribonuclecode/jd | src/jd/plugins/decrypter/DeredactieBe.java | 1,019 | //([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+", "https?://cobra\\.canvas\\.be/.*?/(?:mediatheek|videozone).+" })
| line_comment | nl | //jDownloader - Downloadmanager
//Copyright (C) 2009 JD-Team [email protected]
//
//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 jd.plugins.decrypter;
import java.util.ArrayList;
import java.util.HashMap;
import jd.PluginWrapper;
import jd.controlling.ProgressController;
import jd.plugins.CryptedLink;
import jd.plugins.DecrypterPlugin;
import jd.plugins.DownloadLink;
import jd.plugins.PluginForDecrypt;
@DecrypterPlugin(revision = "$Revision$", interfaceVersion = 2, names = { "deredactie.be", "sporza.be", "cobra.canvas.be" }, urls = { "https?://([a-z0-9]+\\.)?deredactie\\.be/(permalink/\\d\\.\\d+(\\?video=\\d\\.\\d+)?|cm/vrtnieuws([^/]+)?/(mediatheek|videozone).+)", "https?://(?:[a-z0-9]+\\.)?sporza\\.be/.*?/(?:mediatheek|videozone).+",<SUF>
public class DeredactieBe extends PluginForDecrypt {
public DeredactieBe(PluginWrapper wrapper) {
super(wrapper);
}
public ArrayList<DownloadLink> decryptIt(CryptedLink param, ProgressController progress) throws Exception {
ArrayList<DownloadLink> decryptedLinks = new ArrayList<DownloadLink>();
String parameter = param.toString();
this.setBrowserExclusive();
br.setFollowRedirects(true);
br.getPage(parameter);
if (br.getHttpConnection().getResponseCode() == 404 || br.containsHTML("(>Pagina \\- niet gevonden<|>De pagina die u zoekt kan niet gevonden worden)")) {
decryptedLinks.add(this.createOfflinelink(parameter));
return decryptedLinks;
}
HashMap<String, String> mediaValue = new HashMap<String, String>();
for (String[] s : br.getRegex("data\\-video\\-([^=]+)=\"([^\"]+)\"").getMatches()) {
mediaValue.put(s[0], s[1]);
}
final String finalurl = (mediaValue == null || mediaValue.size() == 0) ? null : mediaValue.get("src");
if (finalurl == null) {
try {
decryptedLinks.add(this.createOfflinelink(parameter));
} catch (final Throwable t) {
logger.info("Offline Link: " + parameter);
}
return decryptedLinks;
}
if (finalurl.contains("youtube.com")) {
decryptedLinks.add(createDownloadlink(finalurl));
} else {
decryptedLinks.add(createDownloadlink(parameter.replace(".be/", "decrypted.be/")));
}
return decryptedLinks;
}
/* NO OVERRIDE!! */
public boolean hasCaptcha(CryptedLink link, jd.plugins.Account acc) {
return false;
}
} |
154948_12 | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omaha;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.DateUtils;
import androidx.annotation.IntDef;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.ResettersForTesting;
import org.chromium.base.StreamUtil;
import org.chromium.base.ThreadUtils;
import org.chromium.components.version_info.VersionInfo;
import org.chromium.net.ChromiumNetworkAdapter;
import org.chromium.net.NetworkTrafficAnnotationTag;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
/**
* Keeps tabs on the current state of Chrome, tracking if and when a request should be sent to the
* Omaha Server.
*
* When Chrome is brought to the foreground, it will trigger a call to
* {@link OmahaBase#onForegroundSessionStart}, which kicks off a series of scheduled events
* that allow the class to run. A single alarm is used to trigger the whole pipeline when needed.
* - If Chrome isn't running when the alarm is fired, no pings or update checks will be performed.
* - If Chrome doesn't have a pending request to POST, no POST will be performed.
*
* When a fresh install is detected (or the user clears their data), OmahaBase will send an XML
* request saying that a new install was detected, then follow up with an XML request saying that
* the user was active and that we need to check for Chrome updates.
*
* mevissen suggested being conservative with our timers for sending requests.
* POST attempts that fail to be acknowledged by the server are re-attempted, with at least
* one hour between each attempt.
*
* Status is saved directly to the the disk after every run of the pipeline.
*
* Implementation notes:
* http://docs.google.com/a/google.com/document/d/1scTCovqASf5ktkOeVj8wFRkWTCeDYw2LrOBNn05CDB0/edit
*/
public class OmahaBase {
// Used in various org.chromium.chrome.browser.omaha files.
static final String TAG = "omaha";
/** Version config data structure. */
public static class VersionConfig {
public final String latestVersion;
public final String downloadUrl;
public final int serverDate;
public final String updateStatus;
protected VersionConfig(
String latestVersion, String downloadUrl, int serverDate, String updateStatus) {
this.latestVersion = latestVersion;
this.downloadUrl = downloadUrl;
this.serverDate = serverDate;
this.updateStatus = updateStatus;
}
}
/** Represents the status of a manually-triggered update check. */
@IntDef({UpdateStatus.UPDATED, UpdateStatus.OUTDATED, UpdateStatus.OFFLINE,
UpdateStatus.FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface UpdateStatus {
int UPDATED = 0;
int OUTDATED = 1;
int OFFLINE = 2;
int FAILED = 3;
}
// Flags for retrieving the OmahaClient's state after it's written to disk.
// The PREF_PACKAGE doesn't match the current OmahaClient package for historical reasons.
static final String PREF_PACKAGE = "com.google.android.apps.chrome.omaha";
static final String PREF_INSTALL_SOURCE = "installSource";
static final String PREF_LATEST_VERSION = "latestVersion";
static final String PREF_MARKET_URL = "marketURL";
static final String PREF_SERVER_DATE = "serverDate";
static final String PREF_PERSISTED_REQUEST_ID = "persistedRequestID";
static final String PREF_SEND_INSTALL_EVENT = "sendInstallEvent";
static final String PREF_TIMESTAMP_FOR_NEW_REQUEST = "timestampForNewRequest";
static final String PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT = "timestampForNextPostAttempt";
static final String PREF_TIMESTAMP_OF_INSTALL = "timestampOfInstall";
static final String PREF_TIMESTAMP_OF_REQUEST = "timestampOfRequest";
private static final int UNKNOWN_DATE = -2;
/** Whether or not the Omaha server should really be contacted. */
private static boolean sDisabledForTesting;
// Results of {@link #handlePostRequest()}.
@IntDef({PostResult.NO_REQUEST, PostResult.SENT, PostResult.FAILED, PostResult.SCHEDULED})
@Retention(RetentionPolicy.SOURCE)
@interface PostResult {
int NO_REQUEST = 0;
int SENT = 1;
int FAILED = 2;
int SCHEDULED = 3;
}
/** Deprecated; kept around to cancel alarms set for OmahaClient pre-M58. */
private static final String ACTION_REGISTER_REQUEST =
"org.chromium.chrome.browser.omaha.ACTION_REGISTER_REQUEST";
// Delays between events.
static final long MS_POST_BASE_DELAY = DateUtils.HOUR_IN_MILLIS;
static final long MS_POST_MAX_DELAY = DateUtils.HOUR_IN_MILLIS * 5;
static final long MS_BETWEEN_REQUESTS = DateUtils.HOUR_IN_MILLIS * 5;
static final int MS_CONNECTION_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;
// Strings indicating how the Chrome APK arrived on the user's device. These values MUST NOT
// be changed without updating the corresponding Omaha server strings.
private static final String INSTALL_SOURCE_SYSTEM = "system_image";
private static final String INSTALL_SOURCE_ORGANIC = "organic";
private static final long INVALID_TIMESTAMP = -1;
private static final String INVALID_REQUEST_ID = "invalid";
// Member fields not persisted to disk.
private final OmahaDelegate mDelegate;
private boolean mStateHasBeenRestored;
// State saved written to and read from disk.
private RequestData mCurrentRequest;
private long mTimestampOfInstall;
private long mTimestampForNextPostAttempt;
private long mTimestampForNewRequest;
private int mServerDate;
private String mInstallSource;
protected VersionConfig mVersionConfig;
protected boolean mSendInstallEvent;
// Request failure error code.
private int mRequestErrorCode;
public static void setIsDisabledForTesting(boolean state) {
sDisabledForTesting = state;
ResettersForTesting.register(() -> sDisabledForTesting = false);
}
static boolean isDisabled() {
return sDisabledForTesting;
}
/**
* Constructs a new OmahaBase.
* @param delegate The {@link OmahaDelegate} used to interact with the system.
*/
OmahaBase(OmahaDelegate delegate) {
mDelegate = delegate;
}
/**
* Synchronously checks for updates.
* @return UpdateStatus enum value corresponding to the update state.
*/
public @UpdateStatus int checkForUpdates() {
// Since this update check is synchronous and blocking on the network
// connection, it should not be run on the UI thread.
ThreadUtils.assertOnBackgroundThread();
// This is not available on developer builds.
if (getRequestGenerator() == null) {
Log.w(TAG,
"OmahaBase::checkForUpdates(): Request generator is null. This is probably "
+ "a developer build.");
return UpdateStatus.FAILED;
}
// Create all the metadata needed for an Omaha request.
long currentTimestamp = getBackoffScheduler().getCurrentTime();
String installSource =
mDelegate.isInSystemImage() ? INSTALL_SOURCE_SYSTEM : INSTALL_SOURCE_ORGANIC;
RequestData currentRequest =
createRequestData(false, currentTimestamp, null, installSource);
String sessionID = mDelegate.generateUUID();
long timestampOfInstall = OmahaBase.getSharedPreferences().getLong(
OmahaBase.PREF_TIMESTAMP_OF_INSTALL, currentTimestamp);
// Send the request and parse the response.
VersionConfig versionConfig = generateAndPostRequest(
currentTimestamp, sessionID, currentRequest, timestampOfInstall);
if (versionConfig == null) {
Log.w(TAG, "OmahaBase::checkForUpdates(): versionConfig parsed from response is null.");
return (mRequestErrorCode == RequestFailureException.ERROR_CONNECTIVITY)
? UpdateStatus.OFFLINE
: UpdateStatus.FAILED;
}
// If the version matches exactly, the Omaha server will return status="noupdate" without
// providing the latest version number.
if (versionConfig.updateStatus != null && versionConfig.updateStatus.equals("noupdate")) {
return UpdateStatus.UPDATED;
}
// Compare the current version with the latest received from the server.
VersionNumber current = VersionNumber.fromString(getInstalledVersion());
VersionNumber latest = VersionNumber.fromString(versionConfig.latestVersion);
if (current == null || latest == null) {
return UpdateStatus.FAILED;
}
return current.isSmallerThan(latest) ? UpdateStatus.OUTDATED : UpdateStatus.UPDATED;
}
protected void run() {
if (OmahaBase.isDisabled() || getRequestGenerator() == null) {
Log.v(TAG, "Disabled. Ignoring intent.");
return;
}
restoreState();
long nextTimestamp = Long.MAX_VALUE;
if (mDelegate.isChromeBeingUsed()) {
handleRegisterActiveRequest();
nextTimestamp = Math.min(nextTimestamp, mTimestampForNewRequest);
}
if (hasRequest()) {
@PostResult
int result = handlePostRequest();
if (result == PostResult.FAILED || result == PostResult.SCHEDULED) {
nextTimestamp = Math.min(nextTimestamp, mTimestampForNextPostAttempt);
}
}
// TODO(dfalcantara): Prevent Omaha code from repeatedly rescheduling itself immediately in
// case a scheduling error occurs.
if (nextTimestamp != Long.MAX_VALUE && nextTimestamp >= 0) {
long currentTimestamp = mDelegate.getScheduler().getCurrentTime();
Log.d(TAG, "Attempting to schedule next job for: " + new Date(nextTimestamp));
mDelegate.scheduleService(currentTimestamp, nextTimestamp);
}
saveState();
}
/**
* Determines if a new request should be generated. New requests are only generated if enough
* time has passed between now and the last time a request was generated.
*/
private void handleRegisterActiveRequest() {
// If the current request is too old, generate a new one.
long currentTimestamp = getBackoffScheduler().getCurrentTime();
boolean isTooOld = hasRequest()
&& mCurrentRequest.getAgeInMilliseconds(currentTimestamp) >= MS_BETWEEN_REQUESTS;
boolean isOverdue = currentTimestamp >= mTimestampForNewRequest;
if (isTooOld || isOverdue) {
registerNewRequest(currentTimestamp);
}
}
/**
* Sends the request it is holding.
*/
private @PostResult int handlePostRequest() {
if (!hasRequest()) {
mDelegate.onHandlePostRequestDone(PostResult.NO_REQUEST, false);
return PostResult.NO_REQUEST;
}
// If enough time has passed since the last attempt, try sending a request.
@PostResult
int result;
long currentTimestamp = getBackoffScheduler().getCurrentTime();
boolean installEventWasSent = false;
if (currentTimestamp >= mTimestampForNextPostAttempt) {
// All requests made during the same session should have the same ID.
String sessionID = mDelegate.generateUUID();
boolean sendingInstallRequest = mSendInstallEvent;
boolean succeeded = generateAndPostRequest(currentTimestamp, sessionID);
onResponseReceived(succeeded);
if (succeeded && sendingInstallRequest) {
// Only the first request ever generated should contain an install event.
mSendInstallEvent = false;
installEventWasSent = true;
// Create and immediately send another request for a ping and update check.
registerNewRequest(currentTimestamp);
succeeded &= generateAndPostRequest(currentTimestamp, sessionID);
// Previous line is executed only when succeeded is true, so the updated value
// reflects the status of the last call.
onResponseReceived(succeeded);
}
result = succeeded ? PostResult.SENT : PostResult.FAILED;
} else {
result = PostResult.SCHEDULED;
}
mDelegate.onHandlePostRequestDone(result, installEventWasSent);
return result;
}
/**
* @return version currently installed on the device.
*/
protected String getInstalledVersion() {
return VersionNumberGetter.getInstance().getCurrentlyUsedVersion();
}
protected boolean generateAndPostRequest(long currentTimestamp, String sessionID) {
mVersionConfig = generateAndPostRequest(
currentTimestamp, sessionID, mCurrentRequest, mTimestampOfInstall);
return mVersionConfig != null;
}
protected VersionConfig generateAndPostRequest(long currentTimestamp, String sessionID,
RequestData currentRequest, long timestampOfInstall) {
try {
// Generate the XML for the current request.
long installAgeInDays = RequestGenerator.installAge(
currentTimestamp, timestampOfInstall, currentRequest.isSendInstallEvent());
String xml = getRequestGenerator().generateXML(sessionID, getInstalledVersion(),
installAgeInDays,
mVersionConfig == null ? UNKNOWN_DATE : mVersionConfig.serverDate,
currentRequest);
// Send the request to the server & wait for a response.
String response = postRequest(currentTimestamp, xml);
// Parse out the response.
String appId = getRequestGenerator().getAppId();
ResponseParser parser = new ResponseParser(appId, currentRequest.isSendInstallEvent());
return parser.parseResponse(response);
} catch (RequestFailureException e) {
Log.e(TAG, "Failed to contact server: ", e);
mRequestErrorCode = e.errorCode;
return null;
}
}
protected boolean onResponseReceived(boolean succeeded) {
ExponentialBackoffScheduler scheduler = getBackoffScheduler();
if (succeeded) {
// If we've gotten this far, we've successfully sent a request.
mCurrentRequest = null;
scheduler.resetFailedAttempts();
mTimestampForNewRequest = scheduler.getCurrentTime() + MS_BETWEEN_REQUESTS;
mTimestampForNextPostAttempt = scheduler.calculateNextTimestamp();
Log.d(TAG,
"Request to Server Successful. Timestamp for next request:"
+ mTimestampForNextPostAttempt);
} else {
// Set the alarm to try again later. Failures are incremented after setting the timer
// to allow the first failure to incur the minimum base delay between POSTs.
mTimestampForNextPostAttempt = scheduler.calculateNextTimestamp();
scheduler.increaseFailedAttempts();
}
mDelegate.onGenerateAndPostRequestDone(succeeded);
return succeeded;
}
/**
* Registers a new request with the current timestamp. Internal timestamps are reset to start
* fresh.
* @param currentTimestamp Current time.
*/
private void registerNewRequest(long currentTimestamp) {
mCurrentRequest = createRequestData(currentTimestamp, null);
getBackoffScheduler().resetFailedAttempts();
mTimestampForNextPostAttempt = currentTimestamp;
// Tentatively set the timestamp for a new request. This will be updated when the server
// is successfully contacted.
mTimestampForNewRequest = currentTimestamp + MS_BETWEEN_REQUESTS;
mDelegate.onRegisterNewRequestDone(mTimestampForNewRequest, mTimestampForNextPostAttempt);
}
private RequestData createRequestData(long currentTimestamp, String persistedID) {
return createRequestData(mSendInstallEvent, currentTimestamp, persistedID, mInstallSource);
}
private RequestData createRequestData(boolean sendInstallEvent, long currentTimestamp,
String persistedID, String installSource) {
// If we're sending a persisted event, keep trying to send the same request ID.
String requestID;
if (persistedID == null || INVALID_REQUEST_ID.equals(persistedID)) {
requestID = mDelegate.generateUUID();
} else {
requestID = persistedID;
}
return new RequestData(sendInstallEvent, currentTimestamp, requestID, installSource);
}
private boolean hasRequest() {
return mCurrentRequest != null;
}
/**
* Posts the request to the Omaha server.
* @return the XML response as a String.
* @throws RequestFailureException if the request fails.
*/
private String postRequest(long timestamp, String xml) throws RequestFailureException {
HttpURLConnection urlConnection = createConnection();
try {
// Prepare the HTTP header.
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(
ApiCompatibilityUtils.getBytesUtf8(xml).length);
if (mSendInstallEvent && getBackoffScheduler().getNumFailedAttempts() > 0) {
String age = Long.toString(mCurrentRequest.getAgeInSeconds(timestamp));
urlConnection.addRequestProperty("X-RequestAge", age);
}
return OmahaBase.sendRequestToServer(urlConnection, xml);
} finally {
urlConnection.disconnect();
}
}
/**
* Returns a HttpURLConnection to the server.
*/
@VisibleForTesting
protected HttpURLConnection createConnection() throws RequestFailureException {
// TODO(crbug.com/1139505): Remove the note about UID when UID fallback is removed.
NetworkTrafficAnnotationTag annotation = NetworkTrafficAnnotationTag.createComplete(
"omaha_client_android_uc",
"semantics {"
+ " sender: 'Updates'"
+ " description: "
+ " 'This traffic checks whether the browser is up-to-date and '"
+ " 'provides basic browser telemetry using the Omaha protocol.'"
+ " trigger: 'Manual or automatic checks for updates.'"
+ " data:"
+ " 'Various OS and browser parameters such as version, '"
+ " 'architecture, channel, and the calendar date of the previous '"
+ " 'communication. '"
+ " 'A unique identifier for the device may be transmitted.'"
+ " destination: GOOGLE_OWNED_SERVICE"
+ "}"
+ "policy {"
+ " cookies_allowed: NO"
+ " policy_exception_justification: 'Not implemented.'"
+ " setting: 'This feature cannot be disabled.'"
+ "}");
try {
URL url = new URL(getRequestGenerator().getServerUrl());
HttpURLConnection connection =
(HttpURLConnection) ChromiumNetworkAdapter.openConnection(url, annotation);
connection.setConnectTimeout(MS_CONNECTION_TIMEOUT);
connection.setReadTimeout(MS_CONNECTION_TIMEOUT);
return connection;
} catch (IOException e) {
throw new RequestFailureException("Failed to open connection to URL", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
}
/**
* Reads the data back from the file it was saved to. Uses SharedPreferences to handle I/O.
* Validity checks are performed on the timestamps to guard against clock changing.
*/
private void restoreState() {
if (mStateHasBeenRestored) return;
String installSource =
mDelegate.isInSystemImage() ? INSTALL_SOURCE_SYSTEM : INSTALL_SOURCE_ORGANIC;
ExponentialBackoffScheduler scheduler = getBackoffScheduler();
long currentTime = scheduler.getCurrentTime();
SharedPreferences preferences = OmahaBase.getSharedPreferences();
mTimestampForNewRequest =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_FOR_NEW_REQUEST, currentTime);
mTimestampForNextPostAttempt =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT, currentTime);
mTimestampOfInstall = preferences.getLong(OmahaBase.PREF_TIMESTAMP_OF_INSTALL, currentTime);
mSendInstallEvent = preferences.getBoolean(OmahaBase.PREF_SEND_INSTALL_EVENT, true);
mInstallSource = preferences.getString(OmahaBase.PREF_INSTALL_SOURCE, installSource);
mVersionConfig = getVersionConfig(preferences);
// If we're not sending an install event, don't bother restoring the request ID:
// the server does not expect to have persisted request IDs for pings or update checks.
String persistedRequestId = mSendInstallEvent
? preferences.getString(OmahaBase.PREF_PERSISTED_REQUEST_ID, INVALID_REQUEST_ID)
: INVALID_REQUEST_ID;
long requestTimestamp =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_OF_REQUEST, INVALID_TIMESTAMP);
mCurrentRequest = requestTimestamp == INVALID_TIMESTAMP
? null
: createRequestData(requestTimestamp, persistedRequestId);
// Confirm that the timestamp for the next request is less than the base delay.
long delayToNewRequest = mTimestampForNewRequest - currentTime;
if (delayToNewRequest > MS_BETWEEN_REQUESTS) {
Log.w(TAG,
"Delay to next request (" + delayToNewRequest
+ ") is longer than expected. Resetting to now.");
mTimestampForNewRequest = currentTime;
}
// Confirm that the timestamp for the next POST is less than the current delay.
long delayToNextPost = mTimestampForNextPostAttempt - currentTime;
long lastGeneratedDelay = scheduler.getGeneratedDelay();
if (delayToNextPost > lastGeneratedDelay) {
Log.w(TAG,
"Delay to next post attempt (" + delayToNextPost
+ ") is greater than expected (" + lastGeneratedDelay
+ "). Resetting to now.");
mTimestampForNextPostAttempt = currentTime;
}
mStateHasBeenRestored = true;
}
/**
* Writes out the current state to a file.
*/
private void saveState() {
SharedPreferences prefs = OmahaBase.getSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(OmahaBase.PREF_SEND_INSTALL_EVENT, mSendInstallEvent);
editor.putLong(OmahaBase.PREF_TIMESTAMP_OF_INSTALL, mTimestampOfInstall);
editor.putLong(
OmahaBase.PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT, mTimestampForNextPostAttempt);
editor.putLong(OmahaBase.PREF_TIMESTAMP_FOR_NEW_REQUEST, mTimestampForNewRequest);
editor.putLong(OmahaBase.PREF_TIMESTAMP_OF_REQUEST,
hasRequest() ? mCurrentRequest.getCreationTimestamp() : INVALID_TIMESTAMP);
editor.putString(OmahaBase.PREF_PERSISTED_REQUEST_ID,
hasRequest() ? mCurrentRequest.getRequestID() : INVALID_REQUEST_ID);
editor.putString(OmahaBase.PREF_INSTALL_SOURCE, mInstallSource);
setVersionConfig(editor, mVersionConfig);
editor.apply();
mDelegate.onSaveStateDone(mTimestampForNewRequest, mTimestampForNextPostAttempt);
}
private RequestGenerator getRequestGenerator() {
return mDelegate.getRequestGenerator();
}
private ExponentialBackoffScheduler getBackoffScheduler() {
return mDelegate.getScheduler();
}
/** Begin communicating with the Omaha Update Server. */
public static void onForegroundSessionStart() {
if (!VersionInfo.isOfficialBuild() || isDisabled()) return;
OmahaService.startServiceImmediately();
}
/** Checks whether Chrome has ever tried contacting Omaha before. */
public static boolean isProbablyFreshInstall() {
SharedPreferences prefs = getSharedPreferences();
return prefs.getLong(PREF_TIMESTAMP_OF_INSTALL, -1) == -1;
}
/** Sends the request to the server and returns the response. */
static String sendRequestToServer(HttpURLConnection urlConnection, String request)
throws RequestFailureException {
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(request, 0, request.length());
StreamUtil.closeQuietly(writer);
checkServerResponseCode(urlConnection);
} catch (IOException | SecurityException | IndexOutOfBoundsException
| IllegalArgumentException e) {
// IndexOutOfBoundsException is thought to be triggered by a bug in okio.
// TODO(crbug.com/1111334): Record IndexOutOfBoundsException specifically.
// IllegalArgumentException is triggered by a bug in okio. crbug.com/1149863.
throw new RequestFailureException("Failed to write request to server: ", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
try {
InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(reader);
try {
StringBuilder response = new StringBuilder();
for (String line = in.readLine(); line != null; line = in.readLine()) {
response.append(line);
}
checkServerResponseCode(urlConnection);
return response.toString();
} finally {
StreamUtil.closeQuietly(in);
}
} catch (IOException e) {
throw new RequestFailureException("Failed when reading response from server: ", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
}
/** Confirms that the Omaha server sent back an "OK" code. */
private static void checkServerResponseCode(HttpURLConnection urlConnection)
throws RequestFailureException {
try {
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RequestFailureException("Received " + urlConnection.getResponseCode()
+ " code instead of 200 (OK) from the server. Aborting.");
}
} catch (IOException e) {
throw new RequestFailureException("Failed to read response code from server: ", e);
}
}
/** Returns the Omaha SharedPreferences. */
public static SharedPreferences getSharedPreferences() {
return ContextUtils.getApplicationContext().getSharedPreferences(
PREF_PACKAGE, Context.MODE_PRIVATE);
}
static void setVersionConfig(SharedPreferences.Editor editor, VersionConfig versionConfig) {
editor.putString(OmahaBase.PREF_LATEST_VERSION,
versionConfig == null ? "" : versionConfig.latestVersion);
editor.putString(
OmahaBase.PREF_MARKET_URL, versionConfig == null ? "" : versionConfig.downloadUrl);
if (versionConfig != null) {
editor.putInt(OmahaBase.PREF_SERVER_DATE, versionConfig.serverDate);
}
}
static VersionConfig getVersionConfig(SharedPreferences sharedPref) {
return new VersionConfig(sharedPref.getString(OmahaBase.PREF_LATEST_VERSION, ""),
sharedPref.getString(OmahaBase.PREF_MARKET_URL, ""),
sharedPref.getInt(OmahaBase.PREF_SERVER_DATE, -2),
// updateStatus is only used for the on-demand check.
null);
}
}
| ric2b/Vivaldi-browser | chromium/chrome/android/java/src/org/chromium/chrome/browser/omaha/OmahaBase.java | 7,447 | // Delays between events. | line_comment | nl | // Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.omaha;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.format.DateUtils;
import androidx.annotation.IntDef;
import androidx.annotation.VisibleForTesting;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.ContextUtils;
import org.chromium.base.Log;
import org.chromium.base.ResettersForTesting;
import org.chromium.base.StreamUtil;
import org.chromium.base.ThreadUtils;
import org.chromium.components.version_info.VersionInfo;
import org.chromium.net.ChromiumNetworkAdapter;
import org.chromium.net.NetworkTrafficAnnotationTag;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
/**
* Keeps tabs on the current state of Chrome, tracking if and when a request should be sent to the
* Omaha Server.
*
* When Chrome is brought to the foreground, it will trigger a call to
* {@link OmahaBase#onForegroundSessionStart}, which kicks off a series of scheduled events
* that allow the class to run. A single alarm is used to trigger the whole pipeline when needed.
* - If Chrome isn't running when the alarm is fired, no pings or update checks will be performed.
* - If Chrome doesn't have a pending request to POST, no POST will be performed.
*
* When a fresh install is detected (or the user clears their data), OmahaBase will send an XML
* request saying that a new install was detected, then follow up with an XML request saying that
* the user was active and that we need to check for Chrome updates.
*
* mevissen suggested being conservative with our timers for sending requests.
* POST attempts that fail to be acknowledged by the server are re-attempted, with at least
* one hour between each attempt.
*
* Status is saved directly to the the disk after every run of the pipeline.
*
* Implementation notes:
* http://docs.google.com/a/google.com/document/d/1scTCovqASf5ktkOeVj8wFRkWTCeDYw2LrOBNn05CDB0/edit
*/
public class OmahaBase {
// Used in various org.chromium.chrome.browser.omaha files.
static final String TAG = "omaha";
/** Version config data structure. */
public static class VersionConfig {
public final String latestVersion;
public final String downloadUrl;
public final int serverDate;
public final String updateStatus;
protected VersionConfig(
String latestVersion, String downloadUrl, int serverDate, String updateStatus) {
this.latestVersion = latestVersion;
this.downloadUrl = downloadUrl;
this.serverDate = serverDate;
this.updateStatus = updateStatus;
}
}
/** Represents the status of a manually-triggered update check. */
@IntDef({UpdateStatus.UPDATED, UpdateStatus.OUTDATED, UpdateStatus.OFFLINE,
UpdateStatus.FAILED})
@Retention(RetentionPolicy.SOURCE)
public @interface UpdateStatus {
int UPDATED = 0;
int OUTDATED = 1;
int OFFLINE = 2;
int FAILED = 3;
}
// Flags for retrieving the OmahaClient's state after it's written to disk.
// The PREF_PACKAGE doesn't match the current OmahaClient package for historical reasons.
static final String PREF_PACKAGE = "com.google.android.apps.chrome.omaha";
static final String PREF_INSTALL_SOURCE = "installSource";
static final String PREF_LATEST_VERSION = "latestVersion";
static final String PREF_MARKET_URL = "marketURL";
static final String PREF_SERVER_DATE = "serverDate";
static final String PREF_PERSISTED_REQUEST_ID = "persistedRequestID";
static final String PREF_SEND_INSTALL_EVENT = "sendInstallEvent";
static final String PREF_TIMESTAMP_FOR_NEW_REQUEST = "timestampForNewRequest";
static final String PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT = "timestampForNextPostAttempt";
static final String PREF_TIMESTAMP_OF_INSTALL = "timestampOfInstall";
static final String PREF_TIMESTAMP_OF_REQUEST = "timestampOfRequest";
private static final int UNKNOWN_DATE = -2;
/** Whether or not the Omaha server should really be contacted. */
private static boolean sDisabledForTesting;
// Results of {@link #handlePostRequest()}.
@IntDef({PostResult.NO_REQUEST, PostResult.SENT, PostResult.FAILED, PostResult.SCHEDULED})
@Retention(RetentionPolicy.SOURCE)
@interface PostResult {
int NO_REQUEST = 0;
int SENT = 1;
int FAILED = 2;
int SCHEDULED = 3;
}
/** Deprecated; kept around to cancel alarms set for OmahaClient pre-M58. */
private static final String ACTION_REGISTER_REQUEST =
"org.chromium.chrome.browser.omaha.ACTION_REGISTER_REQUEST";
// Delays between<SUF>
static final long MS_POST_BASE_DELAY = DateUtils.HOUR_IN_MILLIS;
static final long MS_POST_MAX_DELAY = DateUtils.HOUR_IN_MILLIS * 5;
static final long MS_BETWEEN_REQUESTS = DateUtils.HOUR_IN_MILLIS * 5;
static final int MS_CONNECTION_TIMEOUT = (int) DateUtils.MINUTE_IN_MILLIS;
// Strings indicating how the Chrome APK arrived on the user's device. These values MUST NOT
// be changed without updating the corresponding Omaha server strings.
private static final String INSTALL_SOURCE_SYSTEM = "system_image";
private static final String INSTALL_SOURCE_ORGANIC = "organic";
private static final long INVALID_TIMESTAMP = -1;
private static final String INVALID_REQUEST_ID = "invalid";
// Member fields not persisted to disk.
private final OmahaDelegate mDelegate;
private boolean mStateHasBeenRestored;
// State saved written to and read from disk.
private RequestData mCurrentRequest;
private long mTimestampOfInstall;
private long mTimestampForNextPostAttempt;
private long mTimestampForNewRequest;
private int mServerDate;
private String mInstallSource;
protected VersionConfig mVersionConfig;
protected boolean mSendInstallEvent;
// Request failure error code.
private int mRequestErrorCode;
public static void setIsDisabledForTesting(boolean state) {
sDisabledForTesting = state;
ResettersForTesting.register(() -> sDisabledForTesting = false);
}
static boolean isDisabled() {
return sDisabledForTesting;
}
/**
* Constructs a new OmahaBase.
* @param delegate The {@link OmahaDelegate} used to interact with the system.
*/
OmahaBase(OmahaDelegate delegate) {
mDelegate = delegate;
}
/**
* Synchronously checks for updates.
* @return UpdateStatus enum value corresponding to the update state.
*/
public @UpdateStatus int checkForUpdates() {
// Since this update check is synchronous and blocking on the network
// connection, it should not be run on the UI thread.
ThreadUtils.assertOnBackgroundThread();
// This is not available on developer builds.
if (getRequestGenerator() == null) {
Log.w(TAG,
"OmahaBase::checkForUpdates(): Request generator is null. This is probably "
+ "a developer build.");
return UpdateStatus.FAILED;
}
// Create all the metadata needed for an Omaha request.
long currentTimestamp = getBackoffScheduler().getCurrentTime();
String installSource =
mDelegate.isInSystemImage() ? INSTALL_SOURCE_SYSTEM : INSTALL_SOURCE_ORGANIC;
RequestData currentRequest =
createRequestData(false, currentTimestamp, null, installSource);
String sessionID = mDelegate.generateUUID();
long timestampOfInstall = OmahaBase.getSharedPreferences().getLong(
OmahaBase.PREF_TIMESTAMP_OF_INSTALL, currentTimestamp);
// Send the request and parse the response.
VersionConfig versionConfig = generateAndPostRequest(
currentTimestamp, sessionID, currentRequest, timestampOfInstall);
if (versionConfig == null) {
Log.w(TAG, "OmahaBase::checkForUpdates(): versionConfig parsed from response is null.");
return (mRequestErrorCode == RequestFailureException.ERROR_CONNECTIVITY)
? UpdateStatus.OFFLINE
: UpdateStatus.FAILED;
}
// If the version matches exactly, the Omaha server will return status="noupdate" without
// providing the latest version number.
if (versionConfig.updateStatus != null && versionConfig.updateStatus.equals("noupdate")) {
return UpdateStatus.UPDATED;
}
// Compare the current version with the latest received from the server.
VersionNumber current = VersionNumber.fromString(getInstalledVersion());
VersionNumber latest = VersionNumber.fromString(versionConfig.latestVersion);
if (current == null || latest == null) {
return UpdateStatus.FAILED;
}
return current.isSmallerThan(latest) ? UpdateStatus.OUTDATED : UpdateStatus.UPDATED;
}
protected void run() {
if (OmahaBase.isDisabled() || getRequestGenerator() == null) {
Log.v(TAG, "Disabled. Ignoring intent.");
return;
}
restoreState();
long nextTimestamp = Long.MAX_VALUE;
if (mDelegate.isChromeBeingUsed()) {
handleRegisterActiveRequest();
nextTimestamp = Math.min(nextTimestamp, mTimestampForNewRequest);
}
if (hasRequest()) {
@PostResult
int result = handlePostRequest();
if (result == PostResult.FAILED || result == PostResult.SCHEDULED) {
nextTimestamp = Math.min(nextTimestamp, mTimestampForNextPostAttempt);
}
}
// TODO(dfalcantara): Prevent Omaha code from repeatedly rescheduling itself immediately in
// case a scheduling error occurs.
if (nextTimestamp != Long.MAX_VALUE && nextTimestamp >= 0) {
long currentTimestamp = mDelegate.getScheduler().getCurrentTime();
Log.d(TAG, "Attempting to schedule next job for: " + new Date(nextTimestamp));
mDelegate.scheduleService(currentTimestamp, nextTimestamp);
}
saveState();
}
/**
* Determines if a new request should be generated. New requests are only generated if enough
* time has passed between now and the last time a request was generated.
*/
private void handleRegisterActiveRequest() {
// If the current request is too old, generate a new one.
long currentTimestamp = getBackoffScheduler().getCurrentTime();
boolean isTooOld = hasRequest()
&& mCurrentRequest.getAgeInMilliseconds(currentTimestamp) >= MS_BETWEEN_REQUESTS;
boolean isOverdue = currentTimestamp >= mTimestampForNewRequest;
if (isTooOld || isOverdue) {
registerNewRequest(currentTimestamp);
}
}
/**
* Sends the request it is holding.
*/
private @PostResult int handlePostRequest() {
if (!hasRequest()) {
mDelegate.onHandlePostRequestDone(PostResult.NO_REQUEST, false);
return PostResult.NO_REQUEST;
}
// If enough time has passed since the last attempt, try sending a request.
@PostResult
int result;
long currentTimestamp = getBackoffScheduler().getCurrentTime();
boolean installEventWasSent = false;
if (currentTimestamp >= mTimestampForNextPostAttempt) {
// All requests made during the same session should have the same ID.
String sessionID = mDelegate.generateUUID();
boolean sendingInstallRequest = mSendInstallEvent;
boolean succeeded = generateAndPostRequest(currentTimestamp, sessionID);
onResponseReceived(succeeded);
if (succeeded && sendingInstallRequest) {
// Only the first request ever generated should contain an install event.
mSendInstallEvent = false;
installEventWasSent = true;
// Create and immediately send another request for a ping and update check.
registerNewRequest(currentTimestamp);
succeeded &= generateAndPostRequest(currentTimestamp, sessionID);
// Previous line is executed only when succeeded is true, so the updated value
// reflects the status of the last call.
onResponseReceived(succeeded);
}
result = succeeded ? PostResult.SENT : PostResult.FAILED;
} else {
result = PostResult.SCHEDULED;
}
mDelegate.onHandlePostRequestDone(result, installEventWasSent);
return result;
}
/**
* @return version currently installed on the device.
*/
protected String getInstalledVersion() {
return VersionNumberGetter.getInstance().getCurrentlyUsedVersion();
}
protected boolean generateAndPostRequest(long currentTimestamp, String sessionID) {
mVersionConfig = generateAndPostRequest(
currentTimestamp, sessionID, mCurrentRequest, mTimestampOfInstall);
return mVersionConfig != null;
}
protected VersionConfig generateAndPostRequest(long currentTimestamp, String sessionID,
RequestData currentRequest, long timestampOfInstall) {
try {
// Generate the XML for the current request.
long installAgeInDays = RequestGenerator.installAge(
currentTimestamp, timestampOfInstall, currentRequest.isSendInstallEvent());
String xml = getRequestGenerator().generateXML(sessionID, getInstalledVersion(),
installAgeInDays,
mVersionConfig == null ? UNKNOWN_DATE : mVersionConfig.serverDate,
currentRequest);
// Send the request to the server & wait for a response.
String response = postRequest(currentTimestamp, xml);
// Parse out the response.
String appId = getRequestGenerator().getAppId();
ResponseParser parser = new ResponseParser(appId, currentRequest.isSendInstallEvent());
return parser.parseResponse(response);
} catch (RequestFailureException e) {
Log.e(TAG, "Failed to contact server: ", e);
mRequestErrorCode = e.errorCode;
return null;
}
}
protected boolean onResponseReceived(boolean succeeded) {
ExponentialBackoffScheduler scheduler = getBackoffScheduler();
if (succeeded) {
// If we've gotten this far, we've successfully sent a request.
mCurrentRequest = null;
scheduler.resetFailedAttempts();
mTimestampForNewRequest = scheduler.getCurrentTime() + MS_BETWEEN_REQUESTS;
mTimestampForNextPostAttempt = scheduler.calculateNextTimestamp();
Log.d(TAG,
"Request to Server Successful. Timestamp for next request:"
+ mTimestampForNextPostAttempt);
} else {
// Set the alarm to try again later. Failures are incremented after setting the timer
// to allow the first failure to incur the minimum base delay between POSTs.
mTimestampForNextPostAttempt = scheduler.calculateNextTimestamp();
scheduler.increaseFailedAttempts();
}
mDelegate.onGenerateAndPostRequestDone(succeeded);
return succeeded;
}
/**
* Registers a new request with the current timestamp. Internal timestamps are reset to start
* fresh.
* @param currentTimestamp Current time.
*/
private void registerNewRequest(long currentTimestamp) {
mCurrentRequest = createRequestData(currentTimestamp, null);
getBackoffScheduler().resetFailedAttempts();
mTimestampForNextPostAttempt = currentTimestamp;
// Tentatively set the timestamp for a new request. This will be updated when the server
// is successfully contacted.
mTimestampForNewRequest = currentTimestamp + MS_BETWEEN_REQUESTS;
mDelegate.onRegisterNewRequestDone(mTimestampForNewRequest, mTimestampForNextPostAttempt);
}
private RequestData createRequestData(long currentTimestamp, String persistedID) {
return createRequestData(mSendInstallEvent, currentTimestamp, persistedID, mInstallSource);
}
private RequestData createRequestData(boolean sendInstallEvent, long currentTimestamp,
String persistedID, String installSource) {
// If we're sending a persisted event, keep trying to send the same request ID.
String requestID;
if (persistedID == null || INVALID_REQUEST_ID.equals(persistedID)) {
requestID = mDelegate.generateUUID();
} else {
requestID = persistedID;
}
return new RequestData(sendInstallEvent, currentTimestamp, requestID, installSource);
}
private boolean hasRequest() {
return mCurrentRequest != null;
}
/**
* Posts the request to the Omaha server.
* @return the XML response as a String.
* @throws RequestFailureException if the request fails.
*/
private String postRequest(long timestamp, String xml) throws RequestFailureException {
HttpURLConnection urlConnection = createConnection();
try {
// Prepare the HTTP header.
urlConnection.setDoOutput(true);
urlConnection.setFixedLengthStreamingMode(
ApiCompatibilityUtils.getBytesUtf8(xml).length);
if (mSendInstallEvent && getBackoffScheduler().getNumFailedAttempts() > 0) {
String age = Long.toString(mCurrentRequest.getAgeInSeconds(timestamp));
urlConnection.addRequestProperty("X-RequestAge", age);
}
return OmahaBase.sendRequestToServer(urlConnection, xml);
} finally {
urlConnection.disconnect();
}
}
/**
* Returns a HttpURLConnection to the server.
*/
@VisibleForTesting
protected HttpURLConnection createConnection() throws RequestFailureException {
// TODO(crbug.com/1139505): Remove the note about UID when UID fallback is removed.
NetworkTrafficAnnotationTag annotation = NetworkTrafficAnnotationTag.createComplete(
"omaha_client_android_uc",
"semantics {"
+ " sender: 'Updates'"
+ " description: "
+ " 'This traffic checks whether the browser is up-to-date and '"
+ " 'provides basic browser telemetry using the Omaha protocol.'"
+ " trigger: 'Manual or automatic checks for updates.'"
+ " data:"
+ " 'Various OS and browser parameters such as version, '"
+ " 'architecture, channel, and the calendar date of the previous '"
+ " 'communication. '"
+ " 'A unique identifier for the device may be transmitted.'"
+ " destination: GOOGLE_OWNED_SERVICE"
+ "}"
+ "policy {"
+ " cookies_allowed: NO"
+ " policy_exception_justification: 'Not implemented.'"
+ " setting: 'This feature cannot be disabled.'"
+ "}");
try {
URL url = new URL(getRequestGenerator().getServerUrl());
HttpURLConnection connection =
(HttpURLConnection) ChromiumNetworkAdapter.openConnection(url, annotation);
connection.setConnectTimeout(MS_CONNECTION_TIMEOUT);
connection.setReadTimeout(MS_CONNECTION_TIMEOUT);
return connection;
} catch (IOException e) {
throw new RequestFailureException("Failed to open connection to URL", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
}
/**
* Reads the data back from the file it was saved to. Uses SharedPreferences to handle I/O.
* Validity checks are performed on the timestamps to guard against clock changing.
*/
private void restoreState() {
if (mStateHasBeenRestored) return;
String installSource =
mDelegate.isInSystemImage() ? INSTALL_SOURCE_SYSTEM : INSTALL_SOURCE_ORGANIC;
ExponentialBackoffScheduler scheduler = getBackoffScheduler();
long currentTime = scheduler.getCurrentTime();
SharedPreferences preferences = OmahaBase.getSharedPreferences();
mTimestampForNewRequest =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_FOR_NEW_REQUEST, currentTime);
mTimestampForNextPostAttempt =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT, currentTime);
mTimestampOfInstall = preferences.getLong(OmahaBase.PREF_TIMESTAMP_OF_INSTALL, currentTime);
mSendInstallEvent = preferences.getBoolean(OmahaBase.PREF_SEND_INSTALL_EVENT, true);
mInstallSource = preferences.getString(OmahaBase.PREF_INSTALL_SOURCE, installSource);
mVersionConfig = getVersionConfig(preferences);
// If we're not sending an install event, don't bother restoring the request ID:
// the server does not expect to have persisted request IDs for pings or update checks.
String persistedRequestId = mSendInstallEvent
? preferences.getString(OmahaBase.PREF_PERSISTED_REQUEST_ID, INVALID_REQUEST_ID)
: INVALID_REQUEST_ID;
long requestTimestamp =
preferences.getLong(OmahaBase.PREF_TIMESTAMP_OF_REQUEST, INVALID_TIMESTAMP);
mCurrentRequest = requestTimestamp == INVALID_TIMESTAMP
? null
: createRequestData(requestTimestamp, persistedRequestId);
// Confirm that the timestamp for the next request is less than the base delay.
long delayToNewRequest = mTimestampForNewRequest - currentTime;
if (delayToNewRequest > MS_BETWEEN_REQUESTS) {
Log.w(TAG,
"Delay to next request (" + delayToNewRequest
+ ") is longer than expected. Resetting to now.");
mTimestampForNewRequest = currentTime;
}
// Confirm that the timestamp for the next POST is less than the current delay.
long delayToNextPost = mTimestampForNextPostAttempt - currentTime;
long lastGeneratedDelay = scheduler.getGeneratedDelay();
if (delayToNextPost > lastGeneratedDelay) {
Log.w(TAG,
"Delay to next post attempt (" + delayToNextPost
+ ") is greater than expected (" + lastGeneratedDelay
+ "). Resetting to now.");
mTimestampForNextPostAttempt = currentTime;
}
mStateHasBeenRestored = true;
}
/**
* Writes out the current state to a file.
*/
private void saveState() {
SharedPreferences prefs = OmahaBase.getSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(OmahaBase.PREF_SEND_INSTALL_EVENT, mSendInstallEvent);
editor.putLong(OmahaBase.PREF_TIMESTAMP_OF_INSTALL, mTimestampOfInstall);
editor.putLong(
OmahaBase.PREF_TIMESTAMP_FOR_NEXT_POST_ATTEMPT, mTimestampForNextPostAttempt);
editor.putLong(OmahaBase.PREF_TIMESTAMP_FOR_NEW_REQUEST, mTimestampForNewRequest);
editor.putLong(OmahaBase.PREF_TIMESTAMP_OF_REQUEST,
hasRequest() ? mCurrentRequest.getCreationTimestamp() : INVALID_TIMESTAMP);
editor.putString(OmahaBase.PREF_PERSISTED_REQUEST_ID,
hasRequest() ? mCurrentRequest.getRequestID() : INVALID_REQUEST_ID);
editor.putString(OmahaBase.PREF_INSTALL_SOURCE, mInstallSource);
setVersionConfig(editor, mVersionConfig);
editor.apply();
mDelegate.onSaveStateDone(mTimestampForNewRequest, mTimestampForNextPostAttempt);
}
private RequestGenerator getRequestGenerator() {
return mDelegate.getRequestGenerator();
}
private ExponentialBackoffScheduler getBackoffScheduler() {
return mDelegate.getScheduler();
}
/** Begin communicating with the Omaha Update Server. */
public static void onForegroundSessionStart() {
if (!VersionInfo.isOfficialBuild() || isDisabled()) return;
OmahaService.startServiceImmediately();
}
/** Checks whether Chrome has ever tried contacting Omaha before. */
public static boolean isProbablyFreshInstall() {
SharedPreferences prefs = getSharedPreferences();
return prefs.getLong(PREF_TIMESTAMP_OF_INSTALL, -1) == -1;
}
/** Sends the request to the server and returns the response. */
static String sendRequestToServer(HttpURLConnection urlConnection, String request)
throws RequestFailureException {
try {
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
OutputStreamWriter writer = new OutputStreamWriter(out);
writer.write(request, 0, request.length());
StreamUtil.closeQuietly(writer);
checkServerResponseCode(urlConnection);
} catch (IOException | SecurityException | IndexOutOfBoundsException
| IllegalArgumentException e) {
// IndexOutOfBoundsException is thought to be triggered by a bug in okio.
// TODO(crbug.com/1111334): Record IndexOutOfBoundsException specifically.
// IllegalArgumentException is triggered by a bug in okio. crbug.com/1149863.
throw new RequestFailureException("Failed to write request to server: ", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
try {
InputStreamReader reader = new InputStreamReader(urlConnection.getInputStream());
BufferedReader in = new BufferedReader(reader);
try {
StringBuilder response = new StringBuilder();
for (String line = in.readLine(); line != null; line = in.readLine()) {
response.append(line);
}
checkServerResponseCode(urlConnection);
return response.toString();
} finally {
StreamUtil.closeQuietly(in);
}
} catch (IOException e) {
throw new RequestFailureException("Failed when reading response from server: ", e,
RequestFailureException.ERROR_CONNECTIVITY);
}
}
/** Confirms that the Omaha server sent back an "OK" code. */
private static void checkServerResponseCode(HttpURLConnection urlConnection)
throws RequestFailureException {
try {
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RequestFailureException("Received " + urlConnection.getResponseCode()
+ " code instead of 200 (OK) from the server. Aborting.");
}
} catch (IOException e) {
throw new RequestFailureException("Failed to read response code from server: ", e);
}
}
/** Returns the Omaha SharedPreferences. */
public static SharedPreferences getSharedPreferences() {
return ContextUtils.getApplicationContext().getSharedPreferences(
PREF_PACKAGE, Context.MODE_PRIVATE);
}
static void setVersionConfig(SharedPreferences.Editor editor, VersionConfig versionConfig) {
editor.putString(OmahaBase.PREF_LATEST_VERSION,
versionConfig == null ? "" : versionConfig.latestVersion);
editor.putString(
OmahaBase.PREF_MARKET_URL, versionConfig == null ? "" : versionConfig.downloadUrl);
if (versionConfig != null) {
editor.putInt(OmahaBase.PREF_SERVER_DATE, versionConfig.serverDate);
}
}
static VersionConfig getVersionConfig(SharedPreferences sharedPref) {
return new VersionConfig(sharedPref.getString(OmahaBase.PREF_LATEST_VERSION, ""),
sharedPref.getString(OmahaBase.PREF_MARKET_URL, ""),
sharedPref.getInt(OmahaBase.PREF_SERVER_DATE, -2),
// updateStatus is only used for the on-demand check.
null);
}
}
|
113807_7 | package com.geo;
import java.util.List;
import java.util.Random;
/**
* Created by jiangfei on 2018/7/5.
*/
public class LocationUtils {
static final double EARTH_RADIUS = 6372.796924;
static final double PI = 3.1415926535898;
/**
* 根据中心坐标获取指定距离的随机坐标点
*
* @param center 中心坐标
* @param distance 离中心坐标距离(单位:米)
* @return 随机坐标
*/
public static LatitudeLongitudePair getRandomLocation(LatitudeLongitudePair center, double distance) {
if (distance <= 0) distance = 50;
double lat, lon, brg;
double dist = 0;
double rad360 = 2 * PI;
distance = distance / 1000;
LatitudeLongitudePair location = new LatitudeLongitudePair();
double maxdist = distance;
maxdist = maxdist / EARTH_RADIUS;
double startlat = rad(center.getLatitude());
double startlon = rad(center.getLongitude());
double cosdif = Math.cos(maxdist) - 1;
double sinstartlat = Math.sin(startlat);
double cosstartlat = Math.cos(startlat);
dist = Math.acos((new Random().nextDouble() * cosdif + 1));
brg = rad360 * new Random().nextDouble();
lat = Math.asin(sinstartlat * Math.cos(dist) + cosstartlat * Math.sin(dist) * Math.cos(brg));
lon = deg(normalizeLongitude(startlon * 1 + Math.atan2(Math.sin(brg) * Math.sin(dist) * cosstartlat, Math.cos(dist) - sinstartlat * Math.sin(lat))));
lat = deg(lat);
location.setLatitude(padZeroRight(lat));
location.setLongitude(padZeroRight(lon));
return location;
}
/**
* 获取两点间的距离(单位:米)
*
* @param start 起始坐标
* @param end 结束坐标
* @return 距离
*/
public static double getDistance(LatitudeLongitudePair start, LatitudeLongitudePair end) {
double radLat1 = rad(start.getLatitude());
double radLat2 = rad(end.getLatitude());
double a = radLat1 - radLat2;
double b = rad(start.getLongitude()) - rad(end.getLongitude());
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = (int) (s * 10000000) / 10000;
return s;
}
/**
* 是否在范围内
*
* @param point
* @param pts
* @return
*/
public static boolean IsPtInPoly(LatitudeLongitudePair point, List<LatitudeLongitudePair> pts) {
int N = pts.size();
boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;//cross points count of x
double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
LatitudeLongitudePair p1, p2;//neighbour bound vertices
LatitudeLongitudePair p = point; //当前点
p1 = pts.get(0);//left vertex
for (int i = 1; i <= N; ++i) {//check all rays
if (p.equals(p1)) {
return boundOrVertex;//p is an vertex
}
p2 = pts.get(i % N);//right vertex
if (p.getLongitude() < Math.min(p1.getLongitude(), p2.getLongitude()) ||
p.getLongitude() > Math.max(p1.getLongitude(), p2.getLongitude())) {//ray is outside of our interests
p1 = p2;
continue;//next ray left point
}
if (p.getLongitude() > Math.min(p1.getLongitude(), p2.getLongitude()) &&
p.getLongitude() < Math.max(p1.getLongitude(), p2.getLongitude())) {//ray is crossing over by the algorithm (common part of)
if (p.getLatitude() <= Math.max(p1.getLatitude(), p2.getLatitude())) {//x is before of ray
if (p1.getLongitude() == p2.getLongitude() &&
p.getLatitude() >= Math.min(p1.getLatitude(), p2.getLatitude())) {//overlies on a horizontal ray
return boundOrVertex;
}
if (p1.getLatitude() == p2.getLatitude()) {//ray is vertical
if (p1.getLatitude() == p.getLatitude()) {//overlies on a vertical ray
return boundOrVertex;
} else {//before ray
++intersectCount;
}
} else {//cross point on the left side
double xinters = (p.getLongitude() - p1.getLongitude()) *
(p2.getLatitude() - p1.getLatitude()) / (p2.getLongitude() - p1.getLongitude()) + p1.getLatitude();//cross point of y
if (Math.abs(p.getLatitude() - xinters) < precision) {//overlies on a ray
return boundOrVertex;
}
if (p.getLatitude() < xinters) {//before ray
++intersectCount;
}
}
}
} else {//special case when ray is crossing through the vertex
if (p.getLongitude() == p2.getLongitude() && p.getLatitude() <= p2.getLatitude()) {//p crossing over p2
LatitudeLongitudePair p3 = pts.get((i + 1) % N); //next vertex
if (p.getLongitude() >= Math.min(p1.getLongitude(), p3.getLongitude()) &&
p.getLongitude() <= Math.max(p1.getLongitude(), p3.getLongitude())) {//p.x lies between p1.x & p3.x
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2;//next ray left point
}
if (intersectCount % 2 == 0) {//偶数在多边形外
return false;
} else { //奇数在多边形内
return true;
}
}
//=====================================分割线========================//
/**
* 弧度
*
* @param d
* @return
*/
private static double rad(double d) {
return d * PI / 180.0;
}
/**
* 角度
*
* @param rd
* @return
*/
private static double deg(double rd) {
return (rd * 180 / Math.PI);
}
private static double normalizeLongitude(double lon) {
double n = PI;
if (lon > n) {
lon = lon - 2 * n;
} else if (lon < -n) {
lon = lon + 2 * n;
}
return lon;
}
private static double padZeroRight(double s) {
double sigDigits = 8;
s = Math.round(s * Math.pow(10, sigDigits)) / Math.pow(10, sigDigits);
return s;
}
}
| richardkelly2014/security | src/main/java/com/geo/LocationUtils.java | 2,057 | //p is an vertex | line_comment | nl | package com.geo;
import java.util.List;
import java.util.Random;
/**
* Created by jiangfei on 2018/7/5.
*/
public class LocationUtils {
static final double EARTH_RADIUS = 6372.796924;
static final double PI = 3.1415926535898;
/**
* 根据中心坐标获取指定距离的随机坐标点
*
* @param center 中心坐标
* @param distance 离中心坐标距离(单位:米)
* @return 随机坐标
*/
public static LatitudeLongitudePair getRandomLocation(LatitudeLongitudePair center, double distance) {
if (distance <= 0) distance = 50;
double lat, lon, brg;
double dist = 0;
double rad360 = 2 * PI;
distance = distance / 1000;
LatitudeLongitudePair location = new LatitudeLongitudePair();
double maxdist = distance;
maxdist = maxdist / EARTH_RADIUS;
double startlat = rad(center.getLatitude());
double startlon = rad(center.getLongitude());
double cosdif = Math.cos(maxdist) - 1;
double sinstartlat = Math.sin(startlat);
double cosstartlat = Math.cos(startlat);
dist = Math.acos((new Random().nextDouble() * cosdif + 1));
brg = rad360 * new Random().nextDouble();
lat = Math.asin(sinstartlat * Math.cos(dist) + cosstartlat * Math.sin(dist) * Math.cos(brg));
lon = deg(normalizeLongitude(startlon * 1 + Math.atan2(Math.sin(brg) * Math.sin(dist) * cosstartlat, Math.cos(dist) - sinstartlat * Math.sin(lat))));
lat = deg(lat);
location.setLatitude(padZeroRight(lat));
location.setLongitude(padZeroRight(lon));
return location;
}
/**
* 获取两点间的距离(单位:米)
*
* @param start 起始坐标
* @param end 结束坐标
* @return 距离
*/
public static double getDistance(LatitudeLongitudePair start, LatitudeLongitudePair end) {
double radLat1 = rad(start.getLatitude());
double radLat2 = rad(end.getLatitude());
double a = radLat1 - radLat2;
double b = rad(start.getLongitude()) - rad(end.getLongitude());
double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
s = s * EARTH_RADIUS;
s = (int) (s * 10000000) / 10000;
return s;
}
/**
* 是否在范围内
*
* @param point
* @param pts
* @return
*/
public static boolean IsPtInPoly(LatitudeLongitudePair point, List<LatitudeLongitudePair> pts) {
int N = pts.size();
boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
int intersectCount = 0;//cross points count of x
double precision = 2e-10; //浮点类型计算时候与0比较时候的容差
LatitudeLongitudePair p1, p2;//neighbour bound vertices
LatitudeLongitudePair p = point; //当前点
p1 = pts.get(0);//left vertex
for (int i = 1; i <= N; ++i) {//check all rays
if (p.equals(p1)) {
return boundOrVertex;//p is<SUF>
}
p2 = pts.get(i % N);//right vertex
if (p.getLongitude() < Math.min(p1.getLongitude(), p2.getLongitude()) ||
p.getLongitude() > Math.max(p1.getLongitude(), p2.getLongitude())) {//ray is outside of our interests
p1 = p2;
continue;//next ray left point
}
if (p.getLongitude() > Math.min(p1.getLongitude(), p2.getLongitude()) &&
p.getLongitude() < Math.max(p1.getLongitude(), p2.getLongitude())) {//ray is crossing over by the algorithm (common part of)
if (p.getLatitude() <= Math.max(p1.getLatitude(), p2.getLatitude())) {//x is before of ray
if (p1.getLongitude() == p2.getLongitude() &&
p.getLatitude() >= Math.min(p1.getLatitude(), p2.getLatitude())) {//overlies on a horizontal ray
return boundOrVertex;
}
if (p1.getLatitude() == p2.getLatitude()) {//ray is vertical
if (p1.getLatitude() == p.getLatitude()) {//overlies on a vertical ray
return boundOrVertex;
} else {//before ray
++intersectCount;
}
} else {//cross point on the left side
double xinters = (p.getLongitude() - p1.getLongitude()) *
(p2.getLatitude() - p1.getLatitude()) / (p2.getLongitude() - p1.getLongitude()) + p1.getLatitude();//cross point of y
if (Math.abs(p.getLatitude() - xinters) < precision) {//overlies on a ray
return boundOrVertex;
}
if (p.getLatitude() < xinters) {//before ray
++intersectCount;
}
}
}
} else {//special case when ray is crossing through the vertex
if (p.getLongitude() == p2.getLongitude() && p.getLatitude() <= p2.getLatitude()) {//p crossing over p2
LatitudeLongitudePair p3 = pts.get((i + 1) % N); //next vertex
if (p.getLongitude() >= Math.min(p1.getLongitude(), p3.getLongitude()) &&
p.getLongitude() <= Math.max(p1.getLongitude(), p3.getLongitude())) {//p.x lies between p1.x & p3.x
++intersectCount;
} else {
intersectCount += 2;
}
}
}
p1 = p2;//next ray left point
}
if (intersectCount % 2 == 0) {//偶数在多边形外
return false;
} else { //奇数在多边形内
return true;
}
}
//=====================================分割线========================//
/**
* 弧度
*
* @param d
* @return
*/
private static double rad(double d) {
return d * PI / 180.0;
}
/**
* 角度
*
* @param rd
* @return
*/
private static double deg(double rd) {
return (rd * 180 / Math.PI);
}
private static double normalizeLongitude(double lon) {
double n = PI;
if (lon > n) {
lon = lon - 2 * n;
} else if (lon < -n) {
lon = lon + 2 * n;
}
return lon;
}
private static double padZeroRight(double s) {
double sigDigits = 8;
s = Math.round(s * Math.pow(10, sigDigits)) / Math.pow(10, sigDigits);
return s;
}
}
|
46346_1 | package com.example.plugindemo.activity.category;
import java.text.Collator;
import android.app.TwsActivity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.plugindemo.R;
import com.tencent.tws.assistant.widget.SideBar;
import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener;
public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener {
private ListView mListView;
private SideBar mSideBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sidebar_widget);
setTitle("测试共享控件SideBar");
mListView = (ListView) findViewById(R.id.listview);
mSideBar = (SideBar) findViewById(R.id.sidebar);
mSideBar.setIsCSP(true);
mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings));
mSideBar.updateEntriesPropWithContentArray(mStrings);
mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000
mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is 0xFFe5e5e5
mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF
mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is
// 0xFFFFFFFF
mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000
mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000
mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6
mSideBar.updateEntriesPropWithContentArray(mStrings);
mListView.setOnScrollListener(this);
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int index = getSectionForPosition(firstVisibleItem);
mSideBar.updateCurrentIndex(index);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(int letterIndex) {
}
@Override
public void onTouchingLetterChanged(String touchIndexString) {
int index = getPositionForSection(touchIndexString);
mListView.setSelection(index);
}
@Override
public void onTouchUp() {
}
};
public int getPositionForSection(String s) {
for (int i = 0; i < mStrings.length; i++) {
char firstLetter = mStrings[i].charAt(0);
if (compare(firstLetter + "", s) == 0) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
char firstLetter = mStrings[position].charAt(0);
String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries();
for (int i = 0; i < DEFALUT_ENTRIES.length; i++) {
if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) {
return i;
}
}
return 0; // Don't recognize the letter - falls under zero'th section
}
protected int compare(String word, String letter) {
final String firstLetter;
if (word.length() == 0) {
firstLetter = " ";
} else {
firstLetter = word.substring(0, 1);
}
Collator collator = java.text.Collator.getInstance();
collator.setStrength(java.text.Collator.PRIMARY);
return collator.compare(firstLetter, letter);
}
public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance",
"Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon",
"Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno",
"Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou",
"Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille",
"Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus",
"Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa",
"Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille",
"Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere",
"Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow",
"Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu",
"Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi",
"King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase",
"L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell",
"Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo",
"Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot",
"Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn",
"Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern",
"Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq",
"Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost",
"Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar",
"Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille",
"Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water",
"Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin",
"Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier",
"Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette",
"Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois",
"Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves",
"Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera",
"Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve",
"Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson",
"Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano",
"Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" };
}
| rickdynasty/TwsPluginFramework | TwsPluginDemo/src/main/java/com/example/plugindemo/activity/category/SideBarActivity.java | 3,132 | // default is 0xFFe5e5e5 | line_comment | nl | package com.example.plugindemo.activity.category;
import java.text.Collator;
import android.app.TwsActivity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.plugindemo.R;
import com.tencent.tws.assistant.widget.SideBar;
import com.tencent.tws.assistant.widget.SideBar.OnTouchingLetterChangedListener;
public class SideBarActivity extends TwsActivity implements ListView.OnScrollListener {
private ListView mListView;
private SideBar mSideBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sidebar_widget);
setTitle("测试共享控件SideBar");
mListView = (ListView) findViewById(R.id.listview);
mSideBar = (SideBar) findViewById(R.id.sidebar);
mSideBar.setIsCSP(true);
mSideBar.setOnTouchingLetterChangedListener(mLetterChangedListener);
mListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStrings));
mSideBar.updateEntriesPropWithContentArray(mStrings);
mSideBar.setHubbleNormalBgColor(0xFF60DBAA); // default is 0xFF000000
mSideBar.setHubbleNonExistBgColor(0xFFc5c5c5); // default is<SUF>
mSideBar.setHubbleNormalTextColor(0xFFFFFFFF); // default is 0xFFFFFFFF
mSideBar.setHubbleNonExistTextColor(0xFFdddddd); // default is
// 0xFFFFFFFF
mSideBar.setNormalColor(0xFF101010); // default is 0xcc000000
mSideBar.setNonExistColor(0xFFc5c5c5); // default is 0x4c000000
mSideBar.setSelectedColor(0xff22b2b6); // default is 0xff22b2b6
mSideBar.updateEntriesPropWithContentArray(mStrings);
mListView.setOnScrollListener(this);
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int index = getSectionForPosition(firstVisibleItem);
mSideBar.updateCurrentIndex(index);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
OnTouchingLetterChangedListener mLetterChangedListener = new OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(int letterIndex) {
}
@Override
public void onTouchingLetterChanged(String touchIndexString) {
int index = getPositionForSection(touchIndexString);
mListView.setSelection(index);
}
@Override
public void onTouchUp() {
}
};
public int getPositionForSection(String s) {
for (int i = 0; i < mStrings.length; i++) {
char firstLetter = mStrings[i].charAt(0);
if (compare(firstLetter + "", s) == 0) {
return i;
}
}
return -1;
}
public int getSectionForPosition(int position) {
char firstLetter = mStrings[position].charAt(0);
String[] DEFALUT_ENTRIES = (String[]) mSideBar.getSideBarEntries();
for (int i = 0; i < DEFALUT_ENTRIES.length; i++) {
if (compare(firstLetter + "", DEFALUT_ENTRIES[i]) == 0) {
return i;
}
}
return 0; // Don't recognize the letter - falls under zero'th section
}
protected int compare(String word, String letter) {
final String firstLetter;
if (word.length() == 0) {
firstLetter = " ";
} else {
firstLetter = word.substring(0, 1);
}
Collator collator = java.text.Collator.getInstance();
collator.setStrength(java.text.Collator.PRIMARY);
return collator.compare(firstLetter, letter);
}
public static final String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance",
"Ackawi", "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
"Caciocavallo", "Caciotta", "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
"Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat", "Capriole Banon",
"Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano", "Castelleno", "Castelmagno",
"Castelo Branco", "Castigliano", "Cathelain", "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou",
"Chabichou du Poitou", "Chabis de Gatine", "Double Gloucester", "Double Worcester", "Dreux a la Feuille",
"Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue", "Duroblando", "Durrus",
"Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz", "Gammelost", "Gaperon a l'Ail", "Garrotxa",
"Gastanberra", "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
"Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
"Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel", "Grataron d' Areches", "Gratte-Paille",
"Graviera", "Greuilh", "Greve", "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
"Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti", "Heidi Gruyere",
"Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve", "Hipi Iti", "Hubbardston Blue Cow",
"Hushallsost", "Iberico", "Idaho Goatster", "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu",
"Isle of Mull", "Jarlsberg", "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
"Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine", "Kikorangi",
"King Island Cape Wickham Brie", "King River Gold", "Klosterkaese", "Knockalara", "Kugelkase",
"L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere", "La Vache Qui Rit", "Laguiole", "Lairobell",
"Lajta", "Lanark Blue", "Lancashire", "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo",
"Le Lacandou", "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
"Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings", "Livarot",
"Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse", "Loddiswell Avondale", "Longhorn",
"Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam", "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern",
"Mamirolle", "Manchego", "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
"Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)", "Mascarpone Torta", "Matocq",
"Maytag Blue", "Meira", "Menallack Farmhouse", "Menonita", "Meredith Blue", "Mesost",
"Metton (Cancoillotte)", "Meyer Vintage Gouda", "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar",
"Mini Baby Bells", "Mixte", "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
"Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne", "Mothais a la Feuille",
"Mozzarella", "Mozzarella (Australian)", "Mozzarella di Bufala", "Mozzarella Fresh, in water",
"Mozzarella Rolls", "Munster", "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
"Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca", "Olde York", "Olivet au Foin",
"Olivet Bleu", "Olivet Cendre", "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier",
"Ossau-Iraty", "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
"Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano", "Pas de l'Escalette",
"Passendale", "Pasteurized Processed", "Pate de Fromage", "Patefine Fort", "Pave d'Affinois",
"Pave d'Auge", "Pave de Chirac", "Pave du Berry", "Pecorino", "Pecorino in Walnut Leaves",
"Pecorino Romano", "Peekskill Pyramid", "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera",
"Penbryn", "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
"Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin", "Plateau de Herve",
"Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin", "Pont l'Eveque", "Port Nicholson",
"Port-Salut", "Postel", "Pouligny-Saint-Pierre", "Zamorano", "Zanetti Grana Padano",
"Zanetti Parmigiano Reggiano", "# Reggiano", "★ Zaneo" };
}
|
175582_7 | import java.util.Scanner;
public class Exercise19 {
public static void main(String[] args) {
// INTERLEAVE
Scanner console = new Scanner(System.in);
System.out.print("First string: ");
String first = console.nextLine();
System.out.print("Second string: ");
String second = console.nextLine();
// 1. Write a loop to interleave two strings to form a new string.
// To interleave, during each loop take one character from the first string and add it to the result
// and take one character from the second string and add it to the result.
// If there are no more characters available, don't add characters.
// 2. Print the result.
// Examples
// "abc", "123" -> "a1b2c3"
// "cat", "dog" -> "cdaotg"
// "wonder", "o" -> "woonder"
// "B", "igstar" -> "Bigstar"
// "", "huh?" -> "huh?"
// "wha?", "" -> "wha?"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < first.length(); i++ ) {
sb.append(first.charAt(i));
sb.append(second.charAt(i));
}
String interLeaved = sb.toString();
System.out.println(interLeaved);
}
}
| rickmansfield/dev10-coursework | week-01/exercises/repetition-exercises/src/Exercise19.java | 388 | // "wonder", "o" -> "woonder"
| line_comment | nl | import java.util.Scanner;
public class Exercise19 {
public static void main(String[] args) {
// INTERLEAVE
Scanner console = new Scanner(System.in);
System.out.print("First string: ");
String first = console.nextLine();
System.out.print("Second string: ");
String second = console.nextLine();
// 1. Write a loop to interleave two strings to form a new string.
// To interleave, during each loop take one character from the first string and add it to the result
// and take one character from the second string and add it to the result.
// If there are no more characters available, don't add characters.
// 2. Print the result.
// Examples
// "abc", "123" -> "a1b2c3"
// "cat", "dog" -> "cdaotg"
// "wonder", "o"<SUF>
// "B", "igstar" -> "Bigstar"
// "", "huh?" -> "huh?"
// "wha?", "" -> "wha?"
StringBuilder sb = new StringBuilder();
for (int i = 0; i < first.length(); i++ ) {
sb.append(first.charAt(i));
sb.append(second.charAt(i));
}
String interLeaved = sb.toString();
System.out.println(interLeaved);
}
}
|
102590_3 | package com.example.saxion.nl.projectpersistant;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.saxion.nl.projectpersistant.Classes.Gebruiker;
import com.example.saxion.nl.projectpersistant.Networking.Get;
import com.example.saxion.nl.projectpersistant.fragments.AgendaFragment;
import com.example.saxion.nl.projectpersistant.fragments.BeschikbaarFragment;
import com.example.saxion.nl.projectpersistant.fragments.DetailsFragment;
import com.example.saxion.nl.projectpersistant.model.Afspraak;
import com.example.saxion.nl.projectpersistant.model.Reservation;
import com.example.saxion.nl.projectpersistant.model.Room;
import com.example.saxion.nl.projectpersistant.model.Singleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
/**
* Pendurable("eeuwigdurend) is de stand van de app zoals die aan de muur wordt opgehangen.
* Landscape is enforced.
*/
public class PerdurableActivity extends FragmentActivity implements BeschikbaarFragment.OnMenuClickListener {
private Singleton singleton;
@Override
public void goToMenu() {
Intent i = new Intent(this, ReservationActivity.class);
startActivity(i);
}
public enum STATUS {AVAILABLE, BUSY, ERROR}
private BeschikbaarFragment fragment;
private AgendaFragment agendaFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perdurable);
singleton = Singleton.getInstance();
Button reserveringen = (Button) findViewById(R.id.button);
reserveringen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(PerdurableActivity.this, FancyPerdurable.class);
startActivity(i);
}
});
}
private void executeServerRequest() {
try {
Log.d("EXE1", "exe");
String output = new Get().execute(
new URL(singleton.REST_URL + "/api/reservations/1")
).get();
Log.d("exe",output);
JSONObject object = new JSONObject(output);
if (object.has("http_status")) {
//HTTP status code ophalen
int status = object.getInt("http_status");
//Alles met status 200 is goed
if (status >= 200 && status <= 200) {
//Haal hier de server response in JSON op
JSONArray server_response = new JSONArray(object.getString("server_response"));
//Log voor debug purposes
System.out.println(server_response.toString());
for(int i = 0; i<server_response.length();i++){
JSONObject jsonObject = server_response.getJSONObject(i);
String beschrijving = jsonObject.getString("description");
Afspraak tmp = new Afspraak("900", beschrijving);
//voeg afspraak aan model toe
Singleton.getInstance().addAfspraak(tmp);
}
//afspraken toegevoegd dus update view
agendaFragment.update();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
} | rickvanw/2016-2017-Project-Persistent | app/src/main/java/com/example/saxion/nl/projectpersistant/PerdurableActivity.java | 1,149 | //Haal hier de server response in JSON op | line_comment | nl | package com.example.saxion.nl.projectpersistant;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.saxion.nl.projectpersistant.Classes.Gebruiker;
import com.example.saxion.nl.projectpersistant.Networking.Get;
import com.example.saxion.nl.projectpersistant.fragments.AgendaFragment;
import com.example.saxion.nl.projectpersistant.fragments.BeschikbaarFragment;
import com.example.saxion.nl.projectpersistant.fragments.DetailsFragment;
import com.example.saxion.nl.projectpersistant.model.Afspraak;
import com.example.saxion.nl.projectpersistant.model.Reservation;
import com.example.saxion.nl.projectpersistant.model.Room;
import com.example.saxion.nl.projectpersistant.model.Singleton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
/**
* Pendurable("eeuwigdurend) is de stand van de app zoals die aan de muur wordt opgehangen.
* Landscape is enforced.
*/
public class PerdurableActivity extends FragmentActivity implements BeschikbaarFragment.OnMenuClickListener {
private Singleton singleton;
@Override
public void goToMenu() {
Intent i = new Intent(this, ReservationActivity.class);
startActivity(i);
}
public enum STATUS {AVAILABLE, BUSY, ERROR}
private BeschikbaarFragment fragment;
private AgendaFragment agendaFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_perdurable);
singleton = Singleton.getInstance();
Button reserveringen = (Button) findViewById(R.id.button);
reserveringen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(PerdurableActivity.this, FancyPerdurable.class);
startActivity(i);
}
});
}
private void executeServerRequest() {
try {
Log.d("EXE1", "exe");
String output = new Get().execute(
new URL(singleton.REST_URL + "/api/reservations/1")
).get();
Log.d("exe",output);
JSONObject object = new JSONObject(output);
if (object.has("http_status")) {
//HTTP status code ophalen
int status = object.getInt("http_status");
//Alles met status 200 is goed
if (status >= 200 && status <= 200) {
//Haal hier<SUF>
JSONArray server_response = new JSONArray(object.getString("server_response"));
//Log voor debug purposes
System.out.println(server_response.toString());
for(int i = 0; i<server_response.length();i++){
JSONObject jsonObject = server_response.getJSONObject(i);
String beschrijving = jsonObject.getString("description");
Afspraak tmp = new Afspraak("900", beschrijving);
//voeg afspraak aan model toe
Singleton.getInstance().addAfspraak(tmp);
}
//afspraken toegevoegd dus update view
agendaFragment.update();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
} |
17418_7 | import java.util.Random;
/**
* Created by rickv on 8-9-2016.
*/
public class Opdracht1_2 {
public static void main(String[] args) {
// Het aantal te sorteren getallen
int amount = 800000;
int arr[];
arr = new int[amount];
// Maakt de random getallen aan
for (int i = 0; i < amount; i++) {
Random random = new Random();
int getal = random.nextInt(amount);
arr[i]=getal;
}
int[] part1 = new int[amount/2];
int[] part2 = new int[amount/2];
// Splitst de arrays in twee delen
System.arraycopy(arr, 0, part1, 0, part1.length);
System.arraycopy(arr, part1.length, part2, 0, part2.length);
// Uitvoer ter controle
//System.out.println("Array vóór sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(arr[i] + " ");
}
//System.out.println();
// Plaatst de twee delen van de array in een eigen bubblesort
BubbleSort bubbleSort = new BubbleSort(part1);
BubbleSort bubbleSort2 = new BubbleSort(part2);
// Maakt een thread aan voor beide bubbesort
Thread t1 = new Thread(bubbleSort);
Thread t2 = new Thread(bubbleSort2);
// START TIMER
long startTime = System.currentTimeMillis();
// Voer beide threads uit
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException IE) {}
// Voegt gesorteerde arrays samen tot één gesorteerde array
int[] mergedArray = Merge.Merge(bubbleSort.getArr(), bubbleSort2.getArr());
// EIND TIMER
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime + " ms");
// Uitvoer ter controle
//System.out.println("Array na sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(mergedArray[i] + " ");
}
}
}
| rickvanw/Assignment1Concurrency | src/Opdracht1_2.java | 637 | // Plaatst de twee delen van de array in een eigen bubblesort | line_comment | nl | import java.util.Random;
/**
* Created by rickv on 8-9-2016.
*/
public class Opdracht1_2 {
public static void main(String[] args) {
// Het aantal te sorteren getallen
int amount = 800000;
int arr[];
arr = new int[amount];
// Maakt de random getallen aan
for (int i = 0; i < amount; i++) {
Random random = new Random();
int getal = random.nextInt(amount);
arr[i]=getal;
}
int[] part1 = new int[amount/2];
int[] part2 = new int[amount/2];
// Splitst de arrays in twee delen
System.arraycopy(arr, 0, part1, 0, part1.length);
System.arraycopy(arr, part1.length, part2, 0, part2.length);
// Uitvoer ter controle
//System.out.println("Array vóór sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(arr[i] + " ");
}
//System.out.println();
// Plaatst de<SUF>
BubbleSort bubbleSort = new BubbleSort(part1);
BubbleSort bubbleSort2 = new BubbleSort(part2);
// Maakt een thread aan voor beide bubbesort
Thread t1 = new Thread(bubbleSort);
Thread t2 = new Thread(bubbleSort2);
// START TIMER
long startTime = System.currentTimeMillis();
// Voer beide threads uit
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException IE) {}
// Voegt gesorteerde arrays samen tot één gesorteerde array
int[] mergedArray = Merge.Merge(bubbleSort.getArr(), bubbleSort2.getArr());
// EIND TIMER
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println(totalTime + " ms");
// Uitvoer ter controle
//System.out.println("Array na sortering");
for(int i=0; i < arr.length; i++){
//System.out.print(mergedArray[i] + " ");
}
}
}
|
29710_18 | package com.company;
// 6 softwareontwikkelaars
// 10 gebruikers
// SoftwareOntwikkelaarOverleg 3 softwareontwikkelaars met product owner userstories opgesteld en geprioriteerd
// GebruikersOverleg 1 softwareontwikkelaar met 1 gebruiker en product owner problemen gebruikers besproken
// gebruiker heeft probleem, meldt bij bedrijf, wacht tot uitgenodigd voor overleg, als uitgenodigd: reist naar bedrijf en meldt dat aangekomen is, wacht tot jaap zegt dat kan overleggen
// softwareontwikkelaar meldt regelmatig dat beschikbaar is overleg. Projectleider in overleg: softwareontwikkelaar weer aan het werk.
// Projectleider niet in overleg: wacht tot projectleider uitnodigt OF wacht tot constateerd dat hij niet hoeft deel te nemen aan gesprek, daarna weer aan werk
// Softwareontwikkelaar kan beide gesprekken hebben
// Gebruikersoverleg
// Als gebruiker meldt en geen wachtende SO, dan wacht projectleider tot meldt.
import java.util.concurrent.Semaphore;
/**
* Created by rickv on 19-9-2016.
*/
public class Bedrijf2 {
private static final int AANTAL_SOFTWAREONTWIKKELAARS = 6;
private static final int AANTAL_GEBRUIKERS = 10;
private int AANTAL_SOFTWAREONTWIKKELAARS_BINNEN;
private int AANTAL_GEBRUIKERS_BINNEN;
private int wachtendeSoftwareOntwikkelaars;
private Gebruiker[] gebruiker;
private Softwareontwikkelaar[] softwareontwikkelaar;
private ProductOwner productOwner;
private Semaphore probleemMelding, uitnodigingGesprek, aankomstMelding, gesprekUitnodiging,
beschikbaarVoorOverleg, inOverleg, checkin;
public Bedrijf2() {
checkin = new Semaphore(AANTAL_GEBRUIKERS+AANTAL_SOFTWAREONTWIKKELAARS, true);
uitnodigingGesprek = new Semaphore(0, true);
inOverleg = new Semaphore(0,true);
gebruiker = new Gebruiker[AANTAL_GEBRUIKERS];
for(int i=0; i < AANTAL_GEBRUIKERS; i++){
gebruiker[i] = new Gebruiker("g"+i,i);
gebruiker[i].start();
}
softwareontwikkelaar = new Softwareontwikkelaar[AANTAL_SOFTWAREONTWIKKELAARS];
for(int i=0; i < AANTAL_SOFTWAREONTWIKKELAARS; i++){
softwareontwikkelaar[i] = new Softwareontwikkelaar("s"+i,i);
softwareontwikkelaar[i].start();
}
productOwner = new ProductOwner();
productOwner.start();
}
private void SoftwareOntwikkelaarOverleg(){
/*
try{
// 3 softwareontwikkelaars melden dan uitnodiging
uitnodigingGesprek.release();
// gebruiksoverleg of ontwikkelaaresoverleg (gebruiks heeft voorrang)
// overleg klaar
inOverleg.release();
// softwareontwikkelaars weer werken, product owner slapen
} catch(InterruptedException e){
}
*/
}
private void GebruikersOverleg(){
try{
// gebruiker meld, zijn al wachtende softwareontwikkelaars dan punt 2
aankomstMelding.acquire();
// 1. softwareontwikkelaar meld
// meerdere gemeldde gebruikers toelaten
// alle gebruikers uitnodigen
// 2. gebruiker meteen uitgenodigd naar bedrijf
// gebruiker uitgenodig voor gesprek
// wachtende softwareontwikkelaars op de hoogte gebracht van gesprek
inOverleg.release();
} catch(InterruptedException e){
}
}
public class Softwareontwikkelaar extends Thread{
private int myId;
public Softwareontwikkelaar(String name, int id){
super(name);
myId = id;
}
public void run() {
while (true) {
try {
checkin.acquire();
// meldt regelmatig dat beshcikbaar is voor overleg
// als projectleider in overleg is, verder met werk
// als projectleider niet in overleg is, wachten voor uitnodiging voor een overleg
// OF tot geconstateerd dat niet bij gesprek hoort, dan verder met werk
} catch (InterruptedException e) {}
}
}
}
public class ProductOwner extends Thread{
public void run() {
while (true) {
/*try {
} catch (InterruptedException e) {}*/
}
}
private void overleg(){
try{
System.out.println("in overleg");
Thread.sleep((int)(Math.random()*1000));
} catch(InterruptedException e){}
}
}
public class Gebruiker extends Thread{
private int myId;
public Gebruiker(String name, int id){
super(name);
myId = id;
}
public void run() {
while (true) {
try {
checkin.acquire();
// probleem?, melden bij bedrijf
// wachten tot uitgenodigd voor overleg
// reizen naar bedrijf en melden aangekomen om te overleggen
// wachten tot product owner zegt dat gesprek begint
} catch (InterruptedException e) {}
}
}
}
}
| rickvanw/Assignment2Concurrency | src/com/company/Bedrijf2.java | 1,551 | // als projectleider niet in overleg is, wachten voor uitnodiging voor een overleg | line_comment | nl | package com.company;
// 6 softwareontwikkelaars
// 10 gebruikers
// SoftwareOntwikkelaarOverleg 3 softwareontwikkelaars met product owner userstories opgesteld en geprioriteerd
// GebruikersOverleg 1 softwareontwikkelaar met 1 gebruiker en product owner problemen gebruikers besproken
// gebruiker heeft probleem, meldt bij bedrijf, wacht tot uitgenodigd voor overleg, als uitgenodigd: reist naar bedrijf en meldt dat aangekomen is, wacht tot jaap zegt dat kan overleggen
// softwareontwikkelaar meldt regelmatig dat beschikbaar is overleg. Projectleider in overleg: softwareontwikkelaar weer aan het werk.
// Projectleider niet in overleg: wacht tot projectleider uitnodigt OF wacht tot constateerd dat hij niet hoeft deel te nemen aan gesprek, daarna weer aan werk
// Softwareontwikkelaar kan beide gesprekken hebben
// Gebruikersoverleg
// Als gebruiker meldt en geen wachtende SO, dan wacht projectleider tot meldt.
import java.util.concurrent.Semaphore;
/**
* Created by rickv on 19-9-2016.
*/
public class Bedrijf2 {
private static final int AANTAL_SOFTWAREONTWIKKELAARS = 6;
private static final int AANTAL_GEBRUIKERS = 10;
private int AANTAL_SOFTWAREONTWIKKELAARS_BINNEN;
private int AANTAL_GEBRUIKERS_BINNEN;
private int wachtendeSoftwareOntwikkelaars;
private Gebruiker[] gebruiker;
private Softwareontwikkelaar[] softwareontwikkelaar;
private ProductOwner productOwner;
private Semaphore probleemMelding, uitnodigingGesprek, aankomstMelding, gesprekUitnodiging,
beschikbaarVoorOverleg, inOverleg, checkin;
public Bedrijf2() {
checkin = new Semaphore(AANTAL_GEBRUIKERS+AANTAL_SOFTWAREONTWIKKELAARS, true);
uitnodigingGesprek = new Semaphore(0, true);
inOverleg = new Semaphore(0,true);
gebruiker = new Gebruiker[AANTAL_GEBRUIKERS];
for(int i=0; i < AANTAL_GEBRUIKERS; i++){
gebruiker[i] = new Gebruiker("g"+i,i);
gebruiker[i].start();
}
softwareontwikkelaar = new Softwareontwikkelaar[AANTAL_SOFTWAREONTWIKKELAARS];
for(int i=0; i < AANTAL_SOFTWAREONTWIKKELAARS; i++){
softwareontwikkelaar[i] = new Softwareontwikkelaar("s"+i,i);
softwareontwikkelaar[i].start();
}
productOwner = new ProductOwner();
productOwner.start();
}
private void SoftwareOntwikkelaarOverleg(){
/*
try{
// 3 softwareontwikkelaars melden dan uitnodiging
uitnodigingGesprek.release();
// gebruiksoverleg of ontwikkelaaresoverleg (gebruiks heeft voorrang)
// overleg klaar
inOverleg.release();
// softwareontwikkelaars weer werken, product owner slapen
} catch(InterruptedException e){
}
*/
}
private void GebruikersOverleg(){
try{
// gebruiker meld, zijn al wachtende softwareontwikkelaars dan punt 2
aankomstMelding.acquire();
// 1. softwareontwikkelaar meld
// meerdere gemeldde gebruikers toelaten
// alle gebruikers uitnodigen
// 2. gebruiker meteen uitgenodigd naar bedrijf
// gebruiker uitgenodig voor gesprek
// wachtende softwareontwikkelaars op de hoogte gebracht van gesprek
inOverleg.release();
} catch(InterruptedException e){
}
}
public class Softwareontwikkelaar extends Thread{
private int myId;
public Softwareontwikkelaar(String name, int id){
super(name);
myId = id;
}
public void run() {
while (true) {
try {
checkin.acquire();
// meldt regelmatig dat beshcikbaar is voor overleg
// als projectleider in overleg is, verder met werk
// als projectleider<SUF>
// OF tot geconstateerd dat niet bij gesprek hoort, dan verder met werk
} catch (InterruptedException e) {}
}
}
}
public class ProductOwner extends Thread{
public void run() {
while (true) {
/*try {
} catch (InterruptedException e) {}*/
}
}
private void overleg(){
try{
System.out.println("in overleg");
Thread.sleep((int)(Math.random()*1000));
} catch(InterruptedException e){}
}
}
public class Gebruiker extends Thread{
private int myId;
public Gebruiker(String name, int id){
super(name);
myId = id;
}
public void run() {
while (true) {
try {
checkin.acquire();
// probleem?, melden bij bedrijf
// wachten tot uitgenodigd voor overleg
// reizen naar bedrijf en melden aangekomen om te overleggen
// wachten tot product owner zegt dat gesprek begint
} catch (InterruptedException e) {}
}
}
}
}
|
129519_5 | import Classes.Gebruiker;
import Classes.Kamer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@WebServlet("/ShowPersonsServlet")
public class ShowPersonsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Gebruiker> gebruiker_lijst = ((ArrayList<Gebruiker>) getServletContext().getAttribute("users"));
int visitCount = (int) getServletContext().getAttribute("visitCount");
visitCount++;
HttpSession session = request.getSession(false);
if(session == null || session.getAttribute("gebruikersnaam") == null) {
response.sendRedirect("unauthorized.html");
return;
}
// huidige datum toevoegen aan cookie
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Cookie[] cookies = request.getCookies();
String history = null;
for(Cookie cookie : cookies) {
if(cookie.getName().equals("history")) {
history = cookie.getValue();
}
}
Cookie cookie = new Cookie("history", "" + date);
cookie.setMaxAge(24 * 60 * 60);
response.addCookie(cookie);
// // Print aantal keren dat de pagin bezocht is + laatse keer bezocht
// response.getWriter().println("Times visited: " + visitCount);
// if(history != null)
// response.getWriter().println("Last time visited: " + history);
//
// HTML pagina met alle gebruikers in het model
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Times visited: " + visitCount);
out.println("<br>");
out.println("Last time visited: " + history);
out.println("<HTML>");
out.println("<HEAD><TITLE>Gebruikers</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H3>Gebruikers</H3>");
for(Gebruiker gebruiker: gebruiker_lijst) {
out.print(gebruiker.getGebruikersnaam() + " " + gebruiker.getRol());
out.print("<br>");
}
out.println("<br>");
out.println("<a href=\"logout\">Log out</a>");
out.println("</BODY></HTML>");
}
}
| rickvanw/WebApp2 | src/ShowPersonsServlet.java | 755 | // HTML pagina met alle gebruikers in het model | line_comment | nl | import Classes.Gebruiker;
import Classes.Kamer;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@WebServlet("/ShowPersonsServlet")
public class ShowPersonsServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Gebruiker> gebruiker_lijst = ((ArrayList<Gebruiker>) getServletContext().getAttribute("users"));
int visitCount = (int) getServletContext().getAttribute("visitCount");
visitCount++;
HttpSession session = request.getSession(false);
if(session == null || session.getAttribute("gebruikersnaam") == null) {
response.sendRedirect("unauthorized.html");
return;
}
// huidige datum toevoegen aan cookie
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
Cookie[] cookies = request.getCookies();
String history = null;
for(Cookie cookie : cookies) {
if(cookie.getName().equals("history")) {
history = cookie.getValue();
}
}
Cookie cookie = new Cookie("history", "" + date);
cookie.setMaxAge(24 * 60 * 60);
response.addCookie(cookie);
// // Print aantal keren dat de pagin bezocht is + laatse keer bezocht
// response.getWriter().println("Times visited: " + visitCount);
// if(history != null)
// response.getWriter().println("Last time visited: " + history);
//
// HTML pagina<SUF>
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Times visited: " + visitCount);
out.println("<br>");
out.println("Last time visited: " + history);
out.println("<HTML>");
out.println("<HEAD><TITLE>Gebruikers</TITLE></HEAD>");
out.println("<BODY>");
out.println("<H3>Gebruikers</H3>");
for(Gebruiker gebruiker: gebruiker_lijst) {
out.print(gebruiker.getGebruikersnaam() + " " + gebruiker.getRol());
out.print("<br>");
}
out.println("<br>");
out.println("<a href=\"logout\">Log out</a>");
out.println("</BODY></HTML>");
}
}
|
83715_11 | package me.rikmentink.dp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
import me.rikmentink.dp.models.*;
public class Main {
private static String DATABASE_URL = "jdbc:postgresql://localhost/hu-dp";
private static Connection conn;
public static void main(String[] args) throws SQLException {
conn = getConnection();
ReizigerDAO rdao = new ReizigerDAOPsql(conn);
AdresDAO adao = new AdresDAOPsql(conn);
OVChipkaartDAO odao = new OVChipkaartDAOPsql(conn);
ProductDAO pdao = new ProductDAOPsql(conn);
odao.setProductDAO(pdao);
pdao.setKaartDAO(odao);
testReizigerDAO(rdao);
testAdresDAO(rdao, adao);
testOVChipkaartDAO(rdao, odao);
testProductDAO(pdao);
testOVChipkaartProduct(rdao, odao, pdao);
closeConnection();
}
private static Connection getConnection() throws SQLException {
Properties props = new Properties();
props.setProperty("user", "rikmentink");
props.setProperty("password", "wachtwoord");
return DriverManager.getConnection(DATABASE_URL, props);
}
private static void closeConnection() throws SQLException {
if (conn != null) {
conn.close();
}
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
Reiziger sietske = new Reiziger(77, "S", "", "Boers", LocalDate.parse("1981-03-14", DateTimeFormatter.ofPattern("yyyy-MM-dd")));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers");
// Verander de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst was de naam " + sietske.getNaam());
sietske.setAchternaam("Jansen");
rdao.update(sietske);
sietske = rdao.findById(sietske.getId());
System.out.println(", na ReizigerDAO.update() is de naam " + sietske.getNaam());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.delete() ");
rdao.delete(sietske);
reizigers = rdao.findAll();
System.out.print(reizigers.size() + " reizigers");
}
private static void testAdresDAO(ReizigerDAO rdao, AdresDAO adao) throws SQLException {
System.out.println("\n\n---------- Test AdresDAO -------------");
// Haal alle adressen op uit de database
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:");
for (Adres a : adressen) {
System.out.println(String.format("Reiziger {%s, Adres {%s}}", a.getReiziger(), a));
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
Reiziger reiziger = new Reiziger(77, "S", "", "Boers", LocalDate.parse("1981-03-14", DateTimeFormatter.ofPattern("yyyy-MM-dd")));
rdao.save(reiziger);
// Maak een nieuwe adres aan en persisteer deze in de database
Adres adres = new Adres(12, "3584 CS", "15", "Heidelberglaan", "Utrecht", reiziger);
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save() ");
adao.save(adres);
adressen = adao.findAll();
System.out.println(adressen.size() + " adressen");
// Verander het zojuist gemaakte adres en persisteer
System.out.print("[Test] Eerst was de postcode " + adres.getPostcode());
adres.setPostcode("3846 EG");
adao.update(adres);
adres = adao.findById(adres.getId());
System.out.println(", na AdresDAO.update() is de postcode " + adres.getPostcode());
// Verwijder het zojuist gemaakte adres en persisteer
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.delete() ");
adao.delete(adres);
adressen = adao.findAll();
System.out.print(adressen.size() + " adressen");
// Verwijder de tijdelijk gemaakte reiziger
rdao.delete(reiziger);
}
private static void testOVChipkaartDAO(ReizigerDAO rdao, OVChipkaartDAO odao) throws SQLException {
System.out.println("\n\n---------- Test OVChipkaartDAO -------------");
// Haal alle OV-chipkaarten op uit de database
List<OVChipkaart> kaarten = odao.findAll();
System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende OV-chipkaarten:");
for (OVChipkaart k : kaarten) {
System.out.println(k);
}
// Maak een nieuwe OV-chipkaart aan en persisteer deze in de database
Reiziger reiziger = new Reiziger(6, "R", "", "Mentink", LocalDate.of(2004, Month.JULY, 15));
OVChipkaart kaart = new OVChipkaart(69, LocalDate.of(2023, Month.SEPTEMBER, 16), 1, 30.5, reiziger);
System.out.print("[Test] Eerst " + kaarten.size() + " OV-chipkaarten, na OVChipkaartDAO.save() ");
rdao.save(reiziger);
odao.save(kaart);
kaarten = odao.findAll();
System.out.println(kaarten.size() + " kaarten");
// Verander de zojuist gemaakte OV-chipkaart en persisteer
System.out.print("[Test] Eerst was het saldo " + kaart.getSaldo());
kaart.setSaldo(100.0);
odao.update(kaart);
kaart = odao.findByKaartnummer(kaart.getKaartnummer());
System.out.println(", na OVChipkaartDAO.update() is het saldo " + kaart.getSaldo());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + kaarten.size() + " OV-chipkaarten, na OVChipkaartDAO.delete() ");
odao.delete(kaart);
kaarten = odao.findAll();
System.out.println(kaarten.size() + " OV-chipkaarten");
// Verwijder de tijdelijk gemaakte reiziger
rdao.delete(reiziger);
}
private static void testProductDAO(ProductDAO pdao) throws SQLException {
System.out.println("\n\n---------- Test ProductDAO -------------");
// Haal alle producten op uit de database
List<Product> producten = pdao.findAll();
System.out.println("[Test] ProductDAO.findAll() geeft de volgende producten:");
for (Product p : producten) {
System.out.println(p);
}
// Maak een nieuwe producten aan en persisteer deze in de database
Product product = new Product(10, "Jongerendagkaart", "Voordelig een hele dag reizen voor jongeren.", 7.50);
System.out.print("[Test] Eerst " + producten.size() + " producten, na ProductDAO.save() ");
pdao.save(product);
producten = pdao.findAll();
System.out.println(producten.size() + " producten");
// Verander de zojuist gemaakte OV-chipkaart en persisteer
System.out.print("[Test] Eerst was de prijs " + product.getPrijs());
product.setPrijs(10.0);
pdao.update(product);
product = pdao.findByProductNummer(product.getProductNummer());
System.out.println(", na ProductDAO.update() is de prijs " + product.getPrijs());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + producten.size() + " producten, na ProductDAO.delete() ");
pdao.delete(product);
producten = pdao.findAll();
System.out.println(producten.size() + " producten");
}
private static void testOVChipkaartProduct(ReizigerDAO rdao, OVChipkaartDAO odao, ProductDAO pdao) throws SQLException {
System.out.println("\n\n---------- Test OVChipkaart-Product Relatie -------------");
// Maak een nieuwe OV-chipkaart aan met een reiziger en persisteer
Reiziger reiziger = new Reiziger(7, "R", "", "Mentink", LocalDate.of(2004, Month.JULY, 15));
OVChipkaart kaart = new OVChipkaart(1001, LocalDate.now().plusYears(1), 2, 50.0, reiziger);
System.out.print("[Test] Eerst geen producten gekoppeld aan OVChipkaart ");
rdao.save(reiziger);
odao.save(kaart);
List<Product> products = pdao.findByOVChipkaart(kaart);
System.out.println("[" + products.size() + " producten]");
// Maak nieuwe producten aan en koppel ze aan de OV-chipkaart
Product product = new Product(10, "Jongerendagkaart", "Voordelig een hele dag reizen voor jongeren.", 7.50);
Product product2 = new Product(11, "NS Flex", "Geen idee, maar het heeft irritante reclames.", 30.0);
product.addKaart(kaart);
product2.addKaart(kaart);
// Persisteer de zojuist gemaakte producten
System.out.println("\n[Test] Eerst " + products.size() + " producten, na ProductDAO.save():");
pdao.save(product);
pdao.save(product2);
products = pdao.findByOVChipkaart(kaart);
int i = 0;
for (Product p : products) {
System.out.println(i+1 + ": " + p);
i++;
}
// Pas de producten van de OV-chipkaart aan en persisteer
System.out.println("\n[Test] Eerst " + products.size() + " producten, na OVChipkaartDAO.update():");
kaart.removeProduct(product);
odao.update(kaart);
products = pdao.findByOVChipkaart(kaart);
i = 0;
for (Product p : products) {
System.out.println(i+1 + ": " + p);
i++;
}
// Verwijder een product dat gekoppeld is aan een OV-chipkaart en persisteer
System.out.print("\n[Test] Eerst " + products.size() + " producten, na ProductDAO.delete() ");
pdao.delete(product2);
products = pdao.findByOVChipkaart(kaart);
System.out.println("[" + products.size() + " producten]");
// Verwijder de tijdelijk gemaakte reiziger, OV-chipkaart en product
pdao.delete(product);
odao.delete(kaart);
rdao.delete(reiziger);
}
} | rikmentink/hu-dp-ovchip | src/main/java/me/rikmentink/dp/Main.java | 3,570 | // Maak een nieuwe OV-chipkaart aan en persisteer deze in de database | line_comment | nl | package me.rikmentink.dp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
import me.rikmentink.dp.models.*;
public class Main {
private static String DATABASE_URL = "jdbc:postgresql://localhost/hu-dp";
private static Connection conn;
public static void main(String[] args) throws SQLException {
conn = getConnection();
ReizigerDAO rdao = new ReizigerDAOPsql(conn);
AdresDAO adao = new AdresDAOPsql(conn);
OVChipkaartDAO odao = new OVChipkaartDAOPsql(conn);
ProductDAO pdao = new ProductDAOPsql(conn);
odao.setProductDAO(pdao);
pdao.setKaartDAO(odao);
testReizigerDAO(rdao);
testAdresDAO(rdao, adao);
testOVChipkaartDAO(rdao, odao);
testProductDAO(pdao);
testOVChipkaartProduct(rdao, odao, pdao);
closeConnection();
}
private static Connection getConnection() throws SQLException {
Properties props = new Properties();
props.setProperty("user", "rikmentink");
props.setProperty("password", "wachtwoord");
return DriverManager.getConnection(DATABASE_URL, props);
}
private static void closeConnection() throws SQLException {
if (conn != null) {
conn.close();
}
}
private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException {
System.out.println("\n---------- Test ReizigerDAO -------------");
// Haal alle reizigers op uit de database
List<Reiziger> reizigers = rdao.findAll();
System.out.println("[Test] ReizigerDAO.findAll() geeft de volgende reizigers:");
for (Reiziger r : reizigers) {
System.out.println(r);
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
Reiziger sietske = new Reiziger(77, "S", "", "Boers", LocalDate.parse("1981-03-14", DateTimeFormatter.ofPattern("yyyy-MM-dd")));
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.save() ");
rdao.save(sietske);
reizigers = rdao.findAll();
System.out.println(reizigers.size() + " reizigers");
// Verander de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst was de naam " + sietske.getNaam());
sietske.setAchternaam("Jansen");
rdao.update(sietske);
sietske = rdao.findById(sietske.getId());
System.out.println(", na ReizigerDAO.update() is de naam " + sietske.getNaam());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + reizigers.size() + " reizigers, na ReizigerDAO.delete() ");
rdao.delete(sietske);
reizigers = rdao.findAll();
System.out.print(reizigers.size() + " reizigers");
}
private static void testAdresDAO(ReizigerDAO rdao, AdresDAO adao) throws SQLException {
System.out.println("\n\n---------- Test AdresDAO -------------");
// Haal alle adressen op uit de database
List<Adres> adressen = adao.findAll();
System.out.println("[Test] AdresDAO.findAll() geeft de volgende adressen:");
for (Adres a : adressen) {
System.out.println(String.format("Reiziger {%s, Adres {%s}}", a.getReiziger(), a));
}
// Maak een nieuwe reiziger aan en persisteer deze in de database
Reiziger reiziger = new Reiziger(77, "S", "", "Boers", LocalDate.parse("1981-03-14", DateTimeFormatter.ofPattern("yyyy-MM-dd")));
rdao.save(reiziger);
// Maak een nieuwe adres aan en persisteer deze in de database
Adres adres = new Adres(12, "3584 CS", "15", "Heidelberglaan", "Utrecht", reiziger);
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.save() ");
adao.save(adres);
adressen = adao.findAll();
System.out.println(adressen.size() + " adressen");
// Verander het zojuist gemaakte adres en persisteer
System.out.print("[Test] Eerst was de postcode " + adres.getPostcode());
adres.setPostcode("3846 EG");
adao.update(adres);
adres = adao.findById(adres.getId());
System.out.println(", na AdresDAO.update() is de postcode " + adres.getPostcode());
// Verwijder het zojuist gemaakte adres en persisteer
System.out.print("[Test] Eerst " + adressen.size() + " adressen, na AdresDAO.delete() ");
adao.delete(adres);
adressen = adao.findAll();
System.out.print(adressen.size() + " adressen");
// Verwijder de tijdelijk gemaakte reiziger
rdao.delete(reiziger);
}
private static void testOVChipkaartDAO(ReizigerDAO rdao, OVChipkaartDAO odao) throws SQLException {
System.out.println("\n\n---------- Test OVChipkaartDAO -------------");
// Haal alle OV-chipkaarten op uit de database
List<OVChipkaart> kaarten = odao.findAll();
System.out.println("[Test] OVChipkaartDAO.findAll() geeft de volgende OV-chipkaarten:");
for (OVChipkaart k : kaarten) {
System.out.println(k);
}
// Maak een<SUF>
Reiziger reiziger = new Reiziger(6, "R", "", "Mentink", LocalDate.of(2004, Month.JULY, 15));
OVChipkaart kaart = new OVChipkaart(69, LocalDate.of(2023, Month.SEPTEMBER, 16), 1, 30.5, reiziger);
System.out.print("[Test] Eerst " + kaarten.size() + " OV-chipkaarten, na OVChipkaartDAO.save() ");
rdao.save(reiziger);
odao.save(kaart);
kaarten = odao.findAll();
System.out.println(kaarten.size() + " kaarten");
// Verander de zojuist gemaakte OV-chipkaart en persisteer
System.out.print("[Test] Eerst was het saldo " + kaart.getSaldo());
kaart.setSaldo(100.0);
odao.update(kaart);
kaart = odao.findByKaartnummer(kaart.getKaartnummer());
System.out.println(", na OVChipkaartDAO.update() is het saldo " + kaart.getSaldo());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + kaarten.size() + " OV-chipkaarten, na OVChipkaartDAO.delete() ");
odao.delete(kaart);
kaarten = odao.findAll();
System.out.println(kaarten.size() + " OV-chipkaarten");
// Verwijder de tijdelijk gemaakte reiziger
rdao.delete(reiziger);
}
private static void testProductDAO(ProductDAO pdao) throws SQLException {
System.out.println("\n\n---------- Test ProductDAO -------------");
// Haal alle producten op uit de database
List<Product> producten = pdao.findAll();
System.out.println("[Test] ProductDAO.findAll() geeft de volgende producten:");
for (Product p : producten) {
System.out.println(p);
}
// Maak een nieuwe producten aan en persisteer deze in de database
Product product = new Product(10, "Jongerendagkaart", "Voordelig een hele dag reizen voor jongeren.", 7.50);
System.out.print("[Test] Eerst " + producten.size() + " producten, na ProductDAO.save() ");
pdao.save(product);
producten = pdao.findAll();
System.out.println(producten.size() + " producten");
// Verander de zojuist gemaakte OV-chipkaart en persisteer
System.out.print("[Test] Eerst was de prijs " + product.getPrijs());
product.setPrijs(10.0);
pdao.update(product);
product = pdao.findByProductNummer(product.getProductNummer());
System.out.println(", na ProductDAO.update() is de prijs " + product.getPrijs());
// Verwijder de zojuist gemaakte reiziger en persisteer
System.out.print("[Test] Eerst " + producten.size() + " producten, na ProductDAO.delete() ");
pdao.delete(product);
producten = pdao.findAll();
System.out.println(producten.size() + " producten");
}
private static void testOVChipkaartProduct(ReizigerDAO rdao, OVChipkaartDAO odao, ProductDAO pdao) throws SQLException {
System.out.println("\n\n---------- Test OVChipkaart-Product Relatie -------------");
// Maak een nieuwe OV-chipkaart aan met een reiziger en persisteer
Reiziger reiziger = new Reiziger(7, "R", "", "Mentink", LocalDate.of(2004, Month.JULY, 15));
OVChipkaart kaart = new OVChipkaart(1001, LocalDate.now().plusYears(1), 2, 50.0, reiziger);
System.out.print("[Test] Eerst geen producten gekoppeld aan OVChipkaart ");
rdao.save(reiziger);
odao.save(kaart);
List<Product> products = pdao.findByOVChipkaart(kaart);
System.out.println("[" + products.size() + " producten]");
// Maak nieuwe producten aan en koppel ze aan de OV-chipkaart
Product product = new Product(10, "Jongerendagkaart", "Voordelig een hele dag reizen voor jongeren.", 7.50);
Product product2 = new Product(11, "NS Flex", "Geen idee, maar het heeft irritante reclames.", 30.0);
product.addKaart(kaart);
product2.addKaart(kaart);
// Persisteer de zojuist gemaakte producten
System.out.println("\n[Test] Eerst " + products.size() + " producten, na ProductDAO.save():");
pdao.save(product);
pdao.save(product2);
products = pdao.findByOVChipkaart(kaart);
int i = 0;
for (Product p : products) {
System.out.println(i+1 + ": " + p);
i++;
}
// Pas de producten van de OV-chipkaart aan en persisteer
System.out.println("\n[Test] Eerst " + products.size() + " producten, na OVChipkaartDAO.update():");
kaart.removeProduct(product);
odao.update(kaart);
products = pdao.findByOVChipkaart(kaart);
i = 0;
for (Product p : products) {
System.out.println(i+1 + ": " + p);
i++;
}
// Verwijder een product dat gekoppeld is aan een OV-chipkaart en persisteer
System.out.print("\n[Test] Eerst " + products.size() + " producten, na ProductDAO.delete() ");
pdao.delete(product2);
products = pdao.findByOVChipkaart(kaart);
System.out.println("[" + products.size() + " producten]");
// Verwijder de tijdelijk gemaakte reiziger, OV-chipkaart en product
pdao.delete(product);
odao.delete(kaart);
rdao.delete(reiziger);
}
} |
118887_2 | /*
This file is part of javaProject2TI.
javaProject2TI 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.
javaProject2TI 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 javaProject2TI. If not, see <http://www.gnu.org/licenses/>.
*/
package info.toegepaste.www;
import info.toegepaste.www.entity.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author robin
*/
@WebServlet(name = "DocentServlet", urlPatterns = {"/DocentServlet"})
public class DocentServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
EntityManagerFactory emf = null;
HttpSession session = request.getSession();
try {
RequestDispatcher rd = null;
emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU");
EntityManager em = emf.createEntityManager();
if (!(request.getParameter("docentToevoegen") == null)) {
rd = request.getRequestDispatcher("toevoegenDocent.jsp");
rd.forward(request, response);
} else if (!(request.getParameter("docentToevoegenBevestigen") == null)) {
String voornaam = request.getParameter("voornaamDocent");
String familienaam = request.getParameter("familienaamDocent");
String email = request.getParameter("emailDocent");
String nummer = request.getParameter("nummerDocent");
String docentId = request.getParameter("docentId");
Docent docent = new Docent();
docent.setVoornaam(voornaam);
docent.setFamilienaam(familienaam);
docent.setEmail(email);
docent.setNummer(nummer);
EntityTransaction tx = em.getTransaction();
tx.begin();
if (!docentId.isEmpty() && !(docentId == null)) {
docent.setId(Long.parseLong(docentId));
em.merge(docent);
}
else{
em.persist(docent);
}
tx.commit();
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
session.setAttribute("docenten", docenten);
em.close();
rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
else if(session.getAttribute("ingelogd")!=null){
if (!(request.getParameter("docenten") == null)) {
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
em.close();
request.setAttribute("docenten", docenten);
rd = request.getRequestDispatcher("overzichtDocenten.jsp");
rd.forward(request, response);
}
else if (!(request.getParameter("wijzigenDocent") == null)) {
String docentId = request.getParameter("wijzigenDocent");
Docent docent = em.find(Docent.class, Long.parseLong(docentId));
em.close();
request.setAttribute("docent", docent);
rd = request.getRequestDispatcher("toevoegenDocent.jsp");
rd.forward(request, response);
}
else if (!(request.getParameter("deleteDocent") == null)) {
String docentId = request.getParameter("deleteDocent");
Docent docent = em.find(Docent.class, Long.parseLong(docentId));
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
em.remove(docent);
tx.commit();
} catch (Exception e) {
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
request.setAttribute("docenten", docenten);
em.close();
String boodschap = "Deze docent kan niet verwijderd worden!";
request.setAttribute("boodschap", boodschap);
rd = request.getRequestDispatcher("boodschap.jsp");
rd.forward(request, response);
}
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
session.setAttribute("docenten", docenten);
em.close();
rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
else{
response.sendRedirect("index.jsp");
}
//let op: gebruik hier de juiste naam van de persistence unit
//(zoek op in persistence.xml)
/*
emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Docent docentEen = new Docent();
Docent docentTwee = new Docent();
Examen examenEen = new Examen();
Examen examenTwee = new Examen();
Examen examenDrie = new Examen();
ComputerLokaal computerLokaal = new ComputerLokaal();
GewoonLokaal gewoonLokaal = new GewoonLokaal();
Vak vakEen = new Vak();
Vak vakTwee = new Vak();
Vak vakDrie = new Vak();
tx.begin();
computerLokaal.setAantalPlaatsen(100);
computerLokaal.setNummer("D101");
computerLokaal.setLaptop(false);
computerLokaal.setInfo("Niet roken!");
em.persist(computerLokaal);
vakEen.setNummer("s5454");
vakEen.setNaam("C#");
em.persist(vakEen);
docentEen.setNummer("r00001");
docentEen.setVoornaam("Miranda");
docentEen.setFamilienaam("Decabooter");
docentEen.setEmail("[email protected]");
em.persist(docentEen);
examenEen.setVak(vakEen);
examenEen.setDocent(docentEen);
examenEen.setDatum(new GregorianCalendar());
examenEen.setLokaal(computerLokaal);
examenEen.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenEen);
//Insert 2
gewoonLokaal.setAantalPlaatsen(50);
gewoonLokaal.setNummer("Noord-Korea");
gewoonLokaal.setWhiteBoard(true);
em.persist(gewoonLokaal);
vakTwee.setNummer("s5455");
vakTwee.setNaam("Dynamische webapplicaties in PHP");
em.persist(vakTwee);
examenTwee.setVak(vakTwee);
examenTwee.setDocent(docentEen);
examenTwee.setDatum(new GregorianCalendar());
examenTwee.setLokaal(gewoonLokaal);
examenTwee.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenTwee);
//Insert 3
vakDrie.setNummer("s5456");
vakDrie.setNaam("UML");
em.persist(vakDrie);
docentTwee.setNummer("r00002");
docentTwee.setVoornaam("Christine");
docentTwee.setFamilienaam("Smeets");
docentTwee.setEmail("[email protected]");
em.persist(docentTwee);
examenDrie.setVak(vakDrie);
examenDrie.setDocent(docentTwee);
examenDrie.setDatum(new GregorianCalendar());
examenDrie.setLokaal(gewoonLokaal);
examenDrie.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenDrie);
tx.commit();
em.close();
*/
} catch (Exception e) {
e.printStackTrace();
} finally {
emf.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| ripperr/javaProject2TI | src/java/info/toegepaste/www/DocentServlet.java | 3,183 | //let op: gebruik hier de juiste naam van de persistence unit
| line_comment | nl | /*
This file is part of javaProject2TI.
javaProject2TI 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.
javaProject2TI 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 javaProject2TI. If not, see <http://www.gnu.org/licenses/>.
*/
package info.toegepaste.www;
import info.toegepaste.www.entity.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author robin
*/
@WebServlet(name = "DocentServlet", urlPatterns = {"/DocentServlet"})
public class DocentServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
EntityManagerFactory emf = null;
HttpSession session = request.getSession();
try {
RequestDispatcher rd = null;
emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU");
EntityManager em = emf.createEntityManager();
if (!(request.getParameter("docentToevoegen") == null)) {
rd = request.getRequestDispatcher("toevoegenDocent.jsp");
rd.forward(request, response);
} else if (!(request.getParameter("docentToevoegenBevestigen") == null)) {
String voornaam = request.getParameter("voornaamDocent");
String familienaam = request.getParameter("familienaamDocent");
String email = request.getParameter("emailDocent");
String nummer = request.getParameter("nummerDocent");
String docentId = request.getParameter("docentId");
Docent docent = new Docent();
docent.setVoornaam(voornaam);
docent.setFamilienaam(familienaam);
docent.setEmail(email);
docent.setNummer(nummer);
EntityTransaction tx = em.getTransaction();
tx.begin();
if (!docentId.isEmpty() && !(docentId == null)) {
docent.setId(Long.parseLong(docentId));
em.merge(docent);
}
else{
em.persist(docent);
}
tx.commit();
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
session.setAttribute("docenten", docenten);
em.close();
rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
else if(session.getAttribute("ingelogd")!=null){
if (!(request.getParameter("docenten") == null)) {
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
em.close();
request.setAttribute("docenten", docenten);
rd = request.getRequestDispatcher("overzichtDocenten.jsp");
rd.forward(request, response);
}
else if (!(request.getParameter("wijzigenDocent") == null)) {
String docentId = request.getParameter("wijzigenDocent");
Docent docent = em.find(Docent.class, Long.parseLong(docentId));
em.close();
request.setAttribute("docent", docent);
rd = request.getRequestDispatcher("toevoegenDocent.jsp");
rd.forward(request, response);
}
else if (!(request.getParameter("deleteDocent") == null)) {
String docentId = request.getParameter("deleteDocent");
Docent docent = em.find(Docent.class, Long.parseLong(docentId));
EntityTransaction tx = em.getTransaction();
tx.begin();
try {
em.remove(docent);
tx.commit();
} catch (Exception e) {
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
request.setAttribute("docenten", docenten);
em.close();
String boodschap = "Deze docent kan niet verwijderd worden!";
request.setAttribute("boodschap", boodschap);
rd = request.getRequestDispatcher("boodschap.jsp");
rd.forward(request, response);
}
Query q = em.createNamedQuery("Docenten.alle");
List<Docent> docenten = q.getResultList();
session.setAttribute("docenten", docenten);
em.close();
rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
}
}
else{
response.sendRedirect("index.jsp");
}
//let op:<SUF>
//(zoek op in persistence.xml)
/*
emf = Persistence.createEntityManagerFactory("2TI3_Cominotto_Robin_project2013PU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Docent docentEen = new Docent();
Docent docentTwee = new Docent();
Examen examenEen = new Examen();
Examen examenTwee = new Examen();
Examen examenDrie = new Examen();
ComputerLokaal computerLokaal = new ComputerLokaal();
GewoonLokaal gewoonLokaal = new GewoonLokaal();
Vak vakEen = new Vak();
Vak vakTwee = new Vak();
Vak vakDrie = new Vak();
tx.begin();
computerLokaal.setAantalPlaatsen(100);
computerLokaal.setNummer("D101");
computerLokaal.setLaptop(false);
computerLokaal.setInfo("Niet roken!");
em.persist(computerLokaal);
vakEen.setNummer("s5454");
vakEen.setNaam("C#");
em.persist(vakEen);
docentEen.setNummer("r00001");
docentEen.setVoornaam("Miranda");
docentEen.setFamilienaam("Decabooter");
docentEen.setEmail("[email protected]");
em.persist(docentEen);
examenEen.setVak(vakEen);
examenEen.setDocent(docentEen);
examenEen.setDatum(new GregorianCalendar());
examenEen.setLokaal(computerLokaal);
examenEen.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenEen);
//Insert 2
gewoonLokaal.setAantalPlaatsen(50);
gewoonLokaal.setNummer("Noord-Korea");
gewoonLokaal.setWhiteBoard(true);
em.persist(gewoonLokaal);
vakTwee.setNummer("s5455");
vakTwee.setNaam("Dynamische webapplicaties in PHP");
em.persist(vakTwee);
examenTwee.setVak(vakTwee);
examenTwee.setDocent(docentEen);
examenTwee.setDatum(new GregorianCalendar());
examenTwee.setLokaal(gewoonLokaal);
examenTwee.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenTwee);
//Insert 3
vakDrie.setNummer("s5456");
vakDrie.setNaam("UML");
em.persist(vakDrie);
docentTwee.setNummer("r00002");
docentTwee.setVoornaam("Christine");
docentTwee.setFamilienaam("Smeets");
docentTwee.setEmail("[email protected]");
em.persist(docentTwee);
examenDrie.setVak(vakDrie);
examenDrie.setDocent(docentTwee);
examenDrie.setDatum(new GregorianCalendar());
examenDrie.setLokaal(gewoonLokaal);
examenDrie.setSoort(Soort.SCHRIFTELIJK);
em.persist(examenDrie);
tx.commit();
em.close();
*/
} catch (Exception e) {
e.printStackTrace();
} finally {
emf.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
|
122344_18 | package org.ripple.bouncycastle.asn1.isismtt.x509;
import java.util.Enumeration;
import org.ripple.bouncycastle.asn1.ASN1Encodable;
import org.ripple.bouncycastle.asn1.ASN1EncodableVector;
import org.ripple.bouncycastle.asn1.ASN1Object;
import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.ripple.bouncycastle.asn1.ASN1OctetString;
import org.ripple.bouncycastle.asn1.ASN1Primitive;
import org.ripple.bouncycastle.asn1.ASN1Sequence;
import org.ripple.bouncycastle.asn1.ASN1TaggedObject;
import org.ripple.bouncycastle.asn1.DEROctetString;
import org.ripple.bouncycastle.asn1.DERPrintableString;
import org.ripple.bouncycastle.asn1.DERSequence;
import org.ripple.bouncycastle.asn1.DERTaggedObject;
import org.ripple.bouncycastle.asn1.x500.DirectoryString;
/**
* Professions, specializations, disciplines, fields of activity, etc.
*
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @see org.ripple.bouncycastle.asn1.isismtt.x509.AdmissionSyntax
*/
public class ProfessionInfo
extends ASN1Object
{
/**
* Rechtsanw�ltin
*/
public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1");
/**
* Rechtsanwalt
*/
public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2");
/**
* Rechtsbeistand
*/
public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3");
/**
* Steuerberaterin
*/
public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4");
/**
* Steuerberater
*/
public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5");
/**
* Steuerbevollm�chtigte
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6");
/**
* Steuerbevollm�chtigter
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7");
/**
* Notarin
*/
public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8");
/**
* Notar
*/
public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9");
/**
* Notarvertreterin
*/
public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10");
/**
* Notarvertreter
*/
public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11");
/**
* Notariatsverwalterin
*/
public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12");
/**
* Notariatsverwalter
*/
public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13");
/**
* Wirtschaftspr�ferin
*/
public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14");
/**
* Wirtschaftspr�fer
*/
public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15");
/**
* Vereidigte Buchpr�ferin
*/
public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16");
/**
* Vereidigter Buchpr�fer
*/
public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17");
/**
* Patentanw�ltin
*/
public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18");
/**
* Patentanwalt
*/
public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19");
private NamingAuthority namingAuthority;
private ASN1Sequence professionItems;
private ASN1Sequence professionOIDs;
private String registrationNumber;
private ASN1OctetString addProfessionInfo;
public static ProfessionInfo getInstance(Object obj)
{
if (obj == null || obj instanceof ProfessionInfo)
{
return (ProfessionInfo)obj;
}
if (obj instanceof ASN1Sequence)
{
return new ProfessionInfo((ASN1Sequence)obj);
}
throw new IllegalArgumentException("illegal object in getInstance: "
+ obj.getClass().getName());
}
/**
* Constructor from ASN1Sequence.
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @param seq The ASN.1 sequence.
*/
private ProfessionInfo(ASN1Sequence seq)
{
if (seq.size() > 5)
{
throw new IllegalArgumentException("Bad sequence size: "
+ seq.size());
}
Enumeration e = seq.getObjects();
ASN1Encodable o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1TaggedObject)
{
if (((ASN1TaggedObject)o).getTagNo() != 0)
{
throw new IllegalArgumentException("Bad tag number: "
+ ((ASN1TaggedObject)o).getTagNo());
}
namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true);
o = (ASN1Encodable)e.nextElement();
}
professionItems = ASN1Sequence.getInstance(o);
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1Sequence)
{
professionOIDs = ASN1Sequence.getInstance(o);
}
else if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof ASN1OctetString)
{
addProfessionInfo = ASN1OctetString.getInstance(o);
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
}
/**
* Constructor from given details.
* <p>
* <code>professionItems</code> is mandatory, all other parameters are
* optional.
*
* @param namingAuthority The naming authority.
* @param professionItems Directory strings of the profession.
* @param professionOIDs DERObjectIdentfier objects for the
* profession.
* @param registrationNumber Registration number.
* @param addProfessionInfo Additional infos in encoded form.
*/
public ProfessionInfo(NamingAuthority namingAuthority,
DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs,
String registrationNumber, ASN1OctetString addProfessionInfo)
{
this.namingAuthority = namingAuthority;
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != professionItems.length; i++)
{
v.add(professionItems[i]);
}
this.professionItems = new DERSequence(v);
if (professionOIDs != null)
{
v = new ASN1EncodableVector();
for (int i = 0; i != professionOIDs.length; i++)
{
v.add(professionOIDs[i]);
}
this.professionOIDs = new DERSequence(v);
}
this.registrationNumber = registrationNumber;
this.addProfessionInfo = addProfessionInfo;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <p>
* Returns:
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @return a DERObject
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector vec = new ASN1EncodableVector();
if (namingAuthority != null)
{
vec.add(new DERTaggedObject(true, 0, namingAuthority));
}
vec.add(professionItems);
if (professionOIDs != null)
{
vec.add(professionOIDs);
}
if (registrationNumber != null)
{
vec.add(new DERPrintableString(registrationNumber, true));
}
if (addProfessionInfo != null)
{
vec.add(addProfessionInfo);
}
return new DERSequence(vec);
}
/**
* @return Returns the addProfessionInfo.
*/
public ASN1OctetString getAddProfessionInfo()
{
return addProfessionInfo;
}
/**
* @return Returns the namingAuthority.
*/
public NamingAuthority getNamingAuthority()
{
return namingAuthority;
}
/**
* @return Returns the professionItems.
*/
public DirectoryString[] getProfessionItems()
{
DirectoryString[] items = new DirectoryString[professionItems.size()];
int count = 0;
for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();)
{
items[count++] = DirectoryString.getInstance(e.nextElement());
}
return items;
}
/**
* @return Returns the professionOIDs.
*/
public ASN1ObjectIdentifier[] getProfessionOIDs()
{
if (professionOIDs == null)
{
return new ASN1ObjectIdentifier[0];
}
ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()];
int count = 0;
for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();)
{
oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement());
}
return oids;
}
/**
* @return Returns the registrationNumber.
*/
public String getRegistrationNumber()
{
return registrationNumber;
}
}
| ripple-unmaintained/ripple-lib-java | ripple-bouncycastle/src/main/java/org/ripple/bouncycastle/asn1/isismtt/x509/ProfessionInfo.java | 4,055 | /**
* Patentanw�ltin
*/ | block_comment | nl | package org.ripple.bouncycastle.asn1.isismtt.x509;
import java.util.Enumeration;
import org.ripple.bouncycastle.asn1.ASN1Encodable;
import org.ripple.bouncycastle.asn1.ASN1EncodableVector;
import org.ripple.bouncycastle.asn1.ASN1Object;
import org.ripple.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.ripple.bouncycastle.asn1.ASN1OctetString;
import org.ripple.bouncycastle.asn1.ASN1Primitive;
import org.ripple.bouncycastle.asn1.ASN1Sequence;
import org.ripple.bouncycastle.asn1.ASN1TaggedObject;
import org.ripple.bouncycastle.asn1.DEROctetString;
import org.ripple.bouncycastle.asn1.DERPrintableString;
import org.ripple.bouncycastle.asn1.DERSequence;
import org.ripple.bouncycastle.asn1.DERTaggedObject;
import org.ripple.bouncycastle.asn1.x500.DirectoryString;
/**
* Professions, specializations, disciplines, fields of activity, etc.
*
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @see org.ripple.bouncycastle.asn1.isismtt.x509.AdmissionSyntax
*/
public class ProfessionInfo
extends ASN1Object
{
/**
* Rechtsanw�ltin
*/
public static final ASN1ObjectIdentifier Rechtsanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".1");
/**
* Rechtsanwalt
*/
public static final ASN1ObjectIdentifier Rechtsanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".2");
/**
* Rechtsbeistand
*/
public static final ASN1ObjectIdentifier Rechtsbeistand = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".3");
/**
* Steuerberaterin
*/
public static final ASN1ObjectIdentifier Steuerberaterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".4");
/**
* Steuerberater
*/
public static final ASN1ObjectIdentifier Steuerberater = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".5");
/**
* Steuerbevollm�chtigte
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigte = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".6");
/**
* Steuerbevollm�chtigter
*/
public static final ASN1ObjectIdentifier Steuerbevollmchtigter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".7");
/**
* Notarin
*/
public static final ASN1ObjectIdentifier Notarin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".8");
/**
* Notar
*/
public static final ASN1ObjectIdentifier Notar = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".9");
/**
* Notarvertreterin
*/
public static final ASN1ObjectIdentifier Notarvertreterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".10");
/**
* Notarvertreter
*/
public static final ASN1ObjectIdentifier Notarvertreter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".11");
/**
* Notariatsverwalterin
*/
public static final ASN1ObjectIdentifier Notariatsverwalterin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".12");
/**
* Notariatsverwalter
*/
public static final ASN1ObjectIdentifier Notariatsverwalter = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".13");
/**
* Wirtschaftspr�ferin
*/
public static final ASN1ObjectIdentifier Wirtschaftsprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".14");
/**
* Wirtschaftspr�fer
*/
public static final ASN1ObjectIdentifier Wirtschaftsprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".15");
/**
* Vereidigte Buchpr�ferin
*/
public static final ASN1ObjectIdentifier VereidigteBuchprferin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".16");
/**
* Vereidigter Buchpr�fer
*/
public static final ASN1ObjectIdentifier VereidigterBuchprfer = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".17");
/**
* Patentanw�ltin
<SUF>*/
public static final ASN1ObjectIdentifier Patentanwltin = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".18");
/**
* Patentanwalt
*/
public static final ASN1ObjectIdentifier Patentanwalt = new ASN1ObjectIdentifier(
NamingAuthority.id_isismtt_at_namingAuthorities_RechtWirtschaftSteuern + ".19");
private NamingAuthority namingAuthority;
private ASN1Sequence professionItems;
private ASN1Sequence professionOIDs;
private String registrationNumber;
private ASN1OctetString addProfessionInfo;
public static ProfessionInfo getInstance(Object obj)
{
if (obj == null || obj instanceof ProfessionInfo)
{
return (ProfessionInfo)obj;
}
if (obj instanceof ASN1Sequence)
{
return new ProfessionInfo((ASN1Sequence)obj);
}
throw new IllegalArgumentException("illegal object in getInstance: "
+ obj.getClass().getName());
}
/**
* Constructor from ASN1Sequence.
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @param seq The ASN.1 sequence.
*/
private ProfessionInfo(ASN1Sequence seq)
{
if (seq.size() > 5)
{
throw new IllegalArgumentException("Bad sequence size: "
+ seq.size());
}
Enumeration e = seq.getObjects();
ASN1Encodable o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1TaggedObject)
{
if (((ASN1TaggedObject)o).getTagNo() != 0)
{
throw new IllegalArgumentException("Bad tag number: "
+ ((ASN1TaggedObject)o).getTagNo());
}
namingAuthority = NamingAuthority.getInstance((ASN1TaggedObject)o, true);
o = (ASN1Encodable)e.nextElement();
}
professionItems = ASN1Sequence.getInstance(o);
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof ASN1Sequence)
{
professionOIDs = ASN1Sequence.getInstance(o);
}
else if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof ASN1OctetString)
{
addProfessionInfo = ASN1OctetString.getInstance(o);
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DERPrintableString)
{
registrationNumber = DERPrintableString.getInstance(o).getString();
}
else if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
if (e.hasMoreElements())
{
o = (ASN1Encodable)e.nextElement();
if (o instanceof DEROctetString)
{
addProfessionInfo = (DEROctetString)o;
}
else
{
throw new IllegalArgumentException("Bad object encountered: "
+ o.getClass());
}
}
}
/**
* Constructor from given details.
* <p>
* <code>professionItems</code> is mandatory, all other parameters are
* optional.
*
* @param namingAuthority The naming authority.
* @param professionItems Directory strings of the profession.
* @param professionOIDs DERObjectIdentfier objects for the
* profession.
* @param registrationNumber Registration number.
* @param addProfessionInfo Additional infos in encoded form.
*/
public ProfessionInfo(NamingAuthority namingAuthority,
DirectoryString[] professionItems, ASN1ObjectIdentifier[] professionOIDs,
String registrationNumber, ASN1OctetString addProfessionInfo)
{
this.namingAuthority = namingAuthority;
ASN1EncodableVector v = new ASN1EncodableVector();
for (int i = 0; i != professionItems.length; i++)
{
v.add(professionItems[i]);
}
this.professionItems = new DERSequence(v);
if (professionOIDs != null)
{
v = new ASN1EncodableVector();
for (int i = 0; i != professionOIDs.length; i++)
{
v.add(professionOIDs[i]);
}
this.professionOIDs = new DERSequence(v);
}
this.registrationNumber = registrationNumber;
this.addProfessionInfo = addProfessionInfo;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <p>
* Returns:
* <pre>
* ProfessionInfo ::= SEQUENCE
* {
* namingAuthority [0] EXPLICIT NamingAuthority OPTIONAL,
* professionItems SEQUENCE OF DirectoryString (SIZE(1..128)),
* professionOIDs SEQUENCE OF OBJECT IDENTIFIER OPTIONAL,
* registrationNumber PrintableString(SIZE(1..128)) OPTIONAL,
* addProfessionInfo OCTET STRING OPTIONAL
* }
* </pre>
*
* @return a DERObject
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector vec = new ASN1EncodableVector();
if (namingAuthority != null)
{
vec.add(new DERTaggedObject(true, 0, namingAuthority));
}
vec.add(professionItems);
if (professionOIDs != null)
{
vec.add(professionOIDs);
}
if (registrationNumber != null)
{
vec.add(new DERPrintableString(registrationNumber, true));
}
if (addProfessionInfo != null)
{
vec.add(addProfessionInfo);
}
return new DERSequence(vec);
}
/**
* @return Returns the addProfessionInfo.
*/
public ASN1OctetString getAddProfessionInfo()
{
return addProfessionInfo;
}
/**
* @return Returns the namingAuthority.
*/
public NamingAuthority getNamingAuthority()
{
return namingAuthority;
}
/**
* @return Returns the professionItems.
*/
public DirectoryString[] getProfessionItems()
{
DirectoryString[] items = new DirectoryString[professionItems.size()];
int count = 0;
for (Enumeration e = professionItems.getObjects(); e.hasMoreElements();)
{
items[count++] = DirectoryString.getInstance(e.nextElement());
}
return items;
}
/**
* @return Returns the professionOIDs.
*/
public ASN1ObjectIdentifier[] getProfessionOIDs()
{
if (professionOIDs == null)
{
return new ASN1ObjectIdentifier[0];
}
ASN1ObjectIdentifier[] oids = new ASN1ObjectIdentifier[professionOIDs.size()];
int count = 0;
for (Enumeration e = professionOIDs.getObjects(); e.hasMoreElements();)
{
oids[count++] = ASN1ObjectIdentifier.getInstance(e.nextElement());
}
return oids;
}
/**
* @return Returns the registrationNumber.
*/
public String getRegistrationNumber()
{
return registrationNumber;
}
}
|
129160_6 | /*
* Framework code written for the Multimedia course taught in the first year
* of the UvA Informatica bachelor.
*
* Nardi Lam, 2015 (based on code by I.M.J. Kamps, S.J.R. van Schaik, R. de Vries, 2013)
*/
package comthedudifulmoneymoneymoney.httpsgithub.coincounter;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.graphics.Bitmap;
/*
* This is a View that displays incoming images.
*/
public class ImageDisplayView extends View implements ImageListener {
CircleDetection CD_cur = new CircleDetection();
CircleDetection CD_done = new CircleDetection();
// Canvas matrix om image te roteren en schalen
Matrix matrix = new Matrix();
// Thread om cirkeldetectie in te draaien
Thread t = null;
/*** Constructors ***/
public ImageDisplayView(Context context) {
super(context);
}
public ImageDisplayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ImageDisplayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
/*** Image drawing ***/
private Bitmap currentImage = null;
@Override
public void onImage(Bitmap argb) {
// Voeg schaling toe aan canvas matrix
matrix.reset();
matrix.postScale(((float) this.getHeight()) / argb.getWidth(), ((float) this.getWidth()) / argb.getHeight());
// Laad nieuwe frame
CD_done.LoadImage(argb);
// Alleen eerste frame (bij opstarten camera)
if (t == null) {
Log.i("Thread", "Threading begonnen");
// Doe eerste berekening in Main thread
CD_done.run();
// Start nieuwe Thread
CD_cur = new CircleDetection(argb);
t = new Thread(CD_cur);
t.start();
}
// Als de Thread klaar is met rekenen
if (!this.t.isAlive()) {
// Einde Thread afhandelen
CD_done = CD_cur;
CD_done.LoadImage(argb);
// Nieuwe Thread beginnen
CD_cur = new CircleDetection(argb);
t = new Thread(CD_cur);
t.start();
}
// Geef frame door
this.currentImage = CD_done.image;
this.invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/* If there is an image to be drawn: */
if (this.currentImage != null) {
// Teken meest recente cirkels + totaal op frame
CD_done.DrawCircles();
MainActivity.text.setText("Totaal: \u20ac" + String.format("%.2f", CD_done.totaal));
// Pas canvas matrix aan
matrix.postRotate(90);
matrix.postTranslate(canvas.getWidth(), dpToPx(30));
canvas.setMatrix(matrix);
canvas.drawBitmap(CD_done.image, 0, 0, null);
}
}
/*** Source selection ***/
private ImageSource source = null;
public void setImageSource(ImageSource source) {
if (this.source != null) {
this.source.setOnImageListener(null);
}
source.setOnImageListener(this);
this.source = source;
}
public ImageSource getImageSource() {
return this.source;
}
} | rkalis/uva-multimedia | app/src/main/java/comthedudifulmoneymoneymoney/httpsgithub/coincounter/ImageDisplayView.java | 1,158 | // Alleen eerste frame (bij opstarten camera)
| line_comment | nl | /*
* Framework code written for the Multimedia course taught in the first year
* of the UvA Informatica bachelor.
*
* Nardi Lam, 2015 (based on code by I.M.J. Kamps, S.J.R. van Schaik, R. de Vries, 2013)
*/
package comthedudifulmoneymoneymoney.httpsgithub.coincounter;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.graphics.Bitmap;
/*
* This is a View that displays incoming images.
*/
public class ImageDisplayView extends View implements ImageListener {
CircleDetection CD_cur = new CircleDetection();
CircleDetection CD_done = new CircleDetection();
// Canvas matrix om image te roteren en schalen
Matrix matrix = new Matrix();
// Thread om cirkeldetectie in te draaien
Thread t = null;
/*** Constructors ***/
public ImageDisplayView(Context context) {
super(context);
}
public ImageDisplayView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ImageDisplayView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getContext().getResources().getDisplayMetrics();
int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
return px;
}
/*** Image drawing ***/
private Bitmap currentImage = null;
@Override
public void onImage(Bitmap argb) {
// Voeg schaling toe aan canvas matrix
matrix.reset();
matrix.postScale(((float) this.getHeight()) / argb.getWidth(), ((float) this.getWidth()) / argb.getHeight());
// Laad nieuwe frame
CD_done.LoadImage(argb);
// Alleen eerste<SUF>
if (t == null) {
Log.i("Thread", "Threading begonnen");
// Doe eerste berekening in Main thread
CD_done.run();
// Start nieuwe Thread
CD_cur = new CircleDetection(argb);
t = new Thread(CD_cur);
t.start();
}
// Als de Thread klaar is met rekenen
if (!this.t.isAlive()) {
// Einde Thread afhandelen
CD_done = CD_cur;
CD_done.LoadImage(argb);
// Nieuwe Thread beginnen
CD_cur = new CircleDetection(argb);
t = new Thread(CD_cur);
t.start();
}
// Geef frame door
this.currentImage = CD_done.image;
this.invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/* If there is an image to be drawn: */
if (this.currentImage != null) {
// Teken meest recente cirkels + totaal op frame
CD_done.DrawCircles();
MainActivity.text.setText("Totaal: \u20ac" + String.format("%.2f", CD_done.totaal));
// Pas canvas matrix aan
matrix.postRotate(90);
matrix.postTranslate(canvas.getWidth(), dpToPx(30));
canvas.setMatrix(matrix);
canvas.drawBitmap(CD_done.image, 0, 0, null);
}
}
/*** Source selection ***/
private ImageSource source = null;
public void setImageSource(ImageSource source) {
if (this.source != null) {
this.source.setOnImageListener(null);
}
source.setOnImageListener(this);
this.source = source;
}
public ImageSource getImageSource() {
return this.source;
}
} |
34643_1 | import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import twitter4j.JSONException;
import twitter4j.JSONObject;
import java.util.Map;
public class HashTagTopNBolt extends BaseRichBolt{
private final long interval;
private OutputCollector collector;
HashTagTopNBolt(long interval) {
this.interval = interval;
}
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(Tuple input) {
String topNJson = input.getString(0);
try {
JSONObject topN = new JSONObject(topNJson);
// TODO Sorteer het json object, pak de top 10, emit die
// TODO daarna moet een volgende bolt ze mergen en in redis opslaan, overschrijft telkens de oude waarden.
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields());
}
}
| rlenferink/bdph-apache-flink | src/HashTagTopNBolt.java | 367 | // TODO daarna moet een volgende bolt ze mergen en in redis opslaan, overschrijft telkens de oude waarden. | line_comment | nl | import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import twitter4j.JSONException;
import twitter4j.JSONObject;
import java.util.Map;
public class HashTagTopNBolt extends BaseRichBolt{
private final long interval;
private OutputCollector collector;
HashTagTopNBolt(long interval) {
this.interval = interval;
}
@Override
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
@Override
public void execute(Tuple input) {
String topNJson = input.getString(0);
try {
JSONObject topN = new JSONObject(topNJson);
// TODO Sorteer het json object, pak de top 10, emit die
// TODO daarna<SUF>
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields());
}
}
|
167376_33 | /*
* 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.
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* SMOTE.java
*
* Copyright (C) 2008 Ryan Lichtenwalter
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.supervised.instance;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.UnsupportedClassTypeException;
import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
<!-- globalinfo-start -->
* Resamples a dataset by applying the Synthetic Minority Oversampling TEchnique (SMOTE). The original dataset must fit entirely in memory. The amount of SMOTE and number of nearest neighbors may be specified. For more information, see <br/>
* <br/>
* Nitesh V. Chawla et. al. (2002). Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research. 16:321-357.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{al.2002,
* author = {Nitesh V. Chawla et. al.},
* journal = {Journal of Artificial Intelligence Research},
* pages = {321-357},
* title = {Synthetic Minority Over-sampling Technique},
* volume = {16},
* year = {2002}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <num>
* Specifies the random number seed (default 1)</pre>
*
* <pre> -P <percentage>
* Specifies percentage of SMOTE instances to create. (default 100.0)
* </pre>
*
* <pre> -K <nearest-neighbors>
* Specifies the number of nearest neighbors to use. (default 5)
* </pre>
*
* <pre> -C <value-index>
* Specifies the index of the nominal class value to SMOTE
* (default 0: auto-detect non-empty minority class))
* </pre>
*
<!-- options-end -->
*
* @author Ryan Lichtenwalter ([email protected])
* @version $Revision: 1.0$
*/
public class SMOTE extends Filter
implements SupervisedFilter, OptionHandler, TechnicalInformationHandler {
static final long serialVersionUID = -1653880819059250364L;
protected int m_NearestNeighbors = 5;
protected int m_RandomSeed = 1;
protected double m_Percentage = 100.0;
protected String m_ClassValueIndex = "0";
protected boolean m_DetectMinorityClass = true;
/**
* Returns a string describing this classifier
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Resamples a dataset by applying the Synthetic Minority Oversampling TEchnique (SMOTE)." +
" The original dataset must fit entirely in memory." +
" The amount of SMOTE and number of nearest neighbors may be specified." +
" For more information, see \n\n" + getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result = new TechnicalInformation( Type.ARTICLE );
result.setValue( Field.AUTHOR, "Nitesh V. Chawla et. al." );
result.setValue( Field.TITLE, "Synthetic Minority Over-sampling Technique" );
result.setValue( Field.JOURNAL, "Journal of Artificial Intelligence Research" );
result.setValue( Field.YEAR, "2002" );
result.setValue( Field.VOLUME, "16" );
result.setValue( Field.PAGES, "321-357" );
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract( "$Revision: 1.0$" );
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enableAllAttributes();
result.enable( Capability.MISSING_VALUES );
// class
result.enable( Capability.NOMINAL_CLASS );
result.enable( Capability.MISSING_CLASS_VALUES );
return result;
}
/**
* Default constructor.
*/
public SMOTE() {
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector( 3 );
newVector.addElement( new Option(
"\tSpecifies the random number seed (default 1)",
"S", 1, "-S <num>" ) );
newVector.addElement( new Option(
"\tSpecifies percentage of SMOTE instances to create. (default 100.0)\n",
"P", 1, "-P <percentage>" ) );
newVector.addElement( new Option(
"\tSpecifies the number of nearest neighbors to use. (default 5)\n",
"K", 1, "-K <nearest-neighbors>" ) );
newVector.addElement( new Option(
"\tSpecifies the index of the nominal class value to SMOTE\n" + "\t(default 0: auto-detect non-empty minority class))\n",
"C", 1, "-C <value-index>" ) );
/* newVector.addElement( new Option(
"\tSpecifies whether the non-empty minority class should be auto-detected (default true)\n",
"d", 1, "-d" ) ); */
return newVector.elements();
}
/**
* Parses a given list of options.
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <num>
* Specifies the random number seed (default 1)</pre>
*
* <pre> -P <percentage>
* Specifies percentage of SMOTE instances to create. (default 100.0)
* </pre>
*
* <pre> -K <nearest-neighbors>
* Specifies the number of nearest neighbors to use. (default 5)
* </pre>
*
* <pre> -C <value-index>
* Specifies the index of the nominal class value to SMOTE
* (default 0: auto-detect non-empty minority class))
* </pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions( String[] options ) throws Exception {
String seedStr = Utils.getOption( 'S', options );
if( seedStr.length() != 0 ) {
setRandomSeed( Integer.parseInt( seedStr ) );
} else {
setRandomSeed( 1 );
}
String percentageStr = Utils.getOption( 'P', options );
if( percentageStr.length() != 0 ) {
double percentage = new Double( percentageStr ).doubleValue();
if( percentage < 0 ) {
throw new Exception( "P must be >= 0" );
} else {
setPercentage( percentage );
}
} else {
setPercentage( 100.0 );
}
String nnStr = Utils.getOption( 'K', options );
if( nnStr.length() != 0 ) {
int nn = Integer.parseInt( nnStr );
if( nn < 1 ) {
throw new Exception( "K must be >= 1" );
} else {
setNearestNeighbors( nn );
}
} else {
setNearestNeighbors( 5 );
}
String classValueIndexStr = Utils.getOption( 'C', options );
if( classValueIndexStr.length() != 0 ) {
setClassValue( classValueIndexStr );
if( classValueIndexStr.equals( "0" ) ) {
m_DetectMinorityClass = true;
} else {
m_DetectMinorityClass = false;
}
} else {
m_DetectMinorityClass = true;
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
public String[] getOptions() {
String[] options = new String[11];
int current = 0;
options[current++] = "-C";
options[current++] = getClassValue();
options[current++] = "-K";
options[current++] = "" + getNearestNeighbors();
options[current++] = "-P";
options[current++] = "" + getPercentage();
options[current++] = "-S";
options[current++] = "" + getRandomSeed();
while( current < options.length ) {
options[current++] = "";
}
return options;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String randomSeedTipText() {
return "The seed used for random sampling.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed( int newSeed ) {
m_RandomSeed = newSeed;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String percentageTipText() {
return "The percentage of SMOTE instances to create.";
}
/**
* Sets the percentage of SMOTE instances to create.
*
* @param percentage
*/
public void setPercentage( double percentage ) {
m_Percentage = percentage;
}
/**
* Gets the percentage of SMOTE instances to create.
*
* @return the percentage of SMOTE instances to create
*/
public double getPercentage() {
return m_Percentage;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String nearestNeighborsTipText() {
return "The number of nearest neighbors to use.";
}
/**
* Sets the number of nearest neighbors to use.
*
* @param nearestNeighbors
*/
public void setNearestNeighbors( int nearestNeighbors ) {
m_NearestNeighbors = nearestNeighbors;
}
/**
* Gets the number of nearest neighbors to use.
*
* @return the number of nearest neighbors to use
*/
public int getNearestNeighbors() {
return m_NearestNeighbors;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String classValueTipText() {
return "The index of the class value to which SMOTE should be applied. " +
"Use a value of 0 to auto-detect the non-empty minority class.";
}
/**
* Sets the index of the class value to which SMOTE should be applied.
*
* @param classValueIndex
*/
public void setClassValue( String classValueIndex ) {
m_ClassValueIndex = classValueIndex;
}
/**
* Gets the index of the class value to which SMOTE should be applied.
*
* @return the index of the clas value to which SMOTE should be applied
*/
public String getClassValue() {
return m_ClassValueIndex;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String detectMinorityClassTipText() {
return "Whether the non-empty minority class should be automatically " +
"detected.";
}
/**
* Sets whether or not the minority class should be auto-detected.
*
* @param detectMinorityClass
*/
public void setDetectMinorityClass( boolean detectMinorityClass ) {
m_DetectMinorityClass = detectMinorityClass;
}
/**
* Gets whether or not the minority class should be auto-detected.
*
* @return true if the minority class should be auto-detected;
* false otherwise
*
public boolean getDetectMinorityClass() {
return m_DetectMinorityClass;
} */
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input
* instance structure (any instances contained in the object are
* ignored - only the structure is required).
* @return true if the outputFormat may be collected immediately
* @exception Exception if the input format can't be set
* successfully
*/
public boolean setInputFormat( Instances instanceInfo ) throws Exception {
super.setInputFormat( instanceInfo );
super.setOutputFormat( instanceInfo );
return true;
}
/**
* Input an instance for filtering. Filter requires all
* training instances be read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @exception IllegalStateException if no input structure has been defined
*/
public boolean input( Instance instance ) {
if( getInputFormat() == null ) {
throw new IllegalStateException( "No input instance format defined" );
}
if( m_NewBatch ) {
resetQueue();
m_NewBatch = false;
}
if( m_FirstBatchDone ) {
push( instance );
return true;
} else {
bufferInput( instance );
return false;
}
}
/**
* Signify that this batch of input to the filter is finished.
* If the filter requires all instances prior to filtering,
* output() may now be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @exception IllegalStateException if no input structure has been defined
* @exception Exception if provided options cannot be executed
* on input instances
*/
public boolean batchFinished() throws Exception {
if( getInputFormat() == null ) {
throw new IllegalStateException( "No input instance format defined" );
}
if( !m_FirstBatchDone ) {
// Do SMOTE, and clear the input instances.
doSMOTE();
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* The procedure implementing the SMOTE algorithm. The output
* instances are pushed onto the output queue for collection.
*
* @exception Exception if provided options cannot be executed
* on input instances
*/
public void doSMOTE() throws Exception {
int minIndex = 0;
int min = Integer.MAX_VALUE;
int[] classCounts = getInputFormat().attributeStats( getInputFormat().classIndex() ).nominalCounts;
if( m_DetectMinorityClass ) {
// find minority class
for( int i = 0; i < classCounts.length; i++ ) {
if( classCounts[i] != 0 && classCounts[i] < min ) {
min = classCounts[i];
minIndex = i;
}
}
} else {
String classVal = getClassValue();
if( classVal.equalsIgnoreCase( "first" ) ) {
minIndex = 1;
} else if( classVal.equalsIgnoreCase( "last" ) ) {
minIndex = getInputFormat().numClasses();
} else {
minIndex = Integer.parseInt( classVal );
}
if( minIndex > getInputFormat().numClasses() ) {
throw new Exception( "value index must be <= the number of classes" );
}
minIndex--; // make it an index
min = classCounts[minIndex];
}
int nearestNeighbors = Math.min( getNearestNeighbors(), min - 1 );
// compose minority class dataset
// also push all dataset instances
Instances sample = getInputFormat().stringFreeStructure();
Enumeration instanceEnum = getInputFormat().enumerateInstances();
while( instanceEnum.hasMoreElements() ) {
Instance instance = (Instance) instanceEnum.nextElement();
push( (Instance) instance.copy() );
if( (int) instance.classValue() == minIndex ) {
sample.add( instance );
}
}
// compute Value Distance Metric matrices for nominal features
Map vdmMap = new HashMap();
Enumeration attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
if( attr.isNominal() || attr.isString() ) {
double[][] vdm = new double[attr.numValues()][attr.numValues()];
vdmMap.put( attr, vdm );
int[] featureValueCounts = new int[attr.numValues()];
int[][] featureValueCountsByClass = new int[getInputFormat().classAttribute().numValues()][attr.numValues()];
instanceEnum = getInputFormat().enumerateInstances();
while( instanceEnum.hasMoreElements() ) {
Instance instance = (Instance) instanceEnum.nextElement();
int value = (int) instance.value( attr );
int classValue = (int) instance.classValue();
featureValueCounts[value]++;
featureValueCountsByClass[classValue][value]++;
}
for( int valueIndex1 = 0; valueIndex1 < attr.numValues(); valueIndex1++ ) {
for( int valueIndex2 = 0; valueIndex2 < attr.numValues(); valueIndex2++ ) {
double sum = 0;
for( int classValueIndex = 0; classValueIndex < getInputFormat().numClasses(); classValueIndex++ ) {
double c1i = (double) featureValueCountsByClass[classValueIndex][valueIndex1];
double c2i = (double) featureValueCountsByClass[classValueIndex][valueIndex2];
double c1 = (double) featureValueCounts[valueIndex1];
double c2 = (double) featureValueCounts[valueIndex2];
double term1 = c1i / c1;
double term2 = c2i / c2;
sum += Math.abs( term1 - term2 );
}
vdm[valueIndex1][valueIndex2] = sum;
}
}
}
}
}
// use this random source for all required randomness
Random rand = new Random( getRandomSeed() );
// find the set of extra indices to use if the percentage is not evenly divisible by 100
List extraIndices = new LinkedList();
double percentageRemainder = (getPercentage() / 100) - Math.floor( getPercentage() / 100.0 );
int extraIndicesCount = (int) (percentageRemainder * sample.numInstances());
if( extraIndicesCount >= 1 ) {
for( int i = 0; i < sample.numInstances(); i++ ) {
extraIndices.add( i );
}
}
Collections.shuffle( extraIndices, rand );
extraIndices = extraIndices.subList( 0, extraIndicesCount );
Set extraIndexSet = new HashSet( extraIndices );
// the main loop to handle computing nearest neighbors and generating SMOTE
// examples from each instance in the original minority class data
Instance[] nnArray = new Instance[nearestNeighbors];
for( int i = 0; i < sample.numInstances(); i++ ) {
Instance instanceI = sample.instance( i );
// find k nearest neighbors for each instance
List distanceToInstance = new LinkedList();
for( int j = 0; j < sample.numInstances(); j++ ) {
Instance instanceJ = sample.instance( j );
if( i != j ) {
double distance = 0;
attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
double iVal = instanceI.value( attr );
double jVal = instanceJ.value( attr );
if( attr.isNumeric() ) {
distance += Math.pow( iVal - jVal, 2 );
} else {
distance += ((double[][]) vdmMap.get( attr ))[(int) iVal][(int) jVal];
}
}
}
distance = Math.pow( distance, .5 );
distanceToInstance.add( new Object[]{distance, instanceJ} );
}
}
// sort the neighbors according to distance
Collections.sort( distanceToInstance, new Comparator() {
public int compare( Object o1, Object o2 ) {
double distance1 = (Double) ((Object[]) o1)[0];
double distance2 = (Double) ((Object[]) o2)[0];
return (int) Math.ceil( distance1 - distance2 );
}
} );
// populate the actual nearest neighbor instance array
Iterator entryIterator = distanceToInstance.iterator();
int j = 0;
while( entryIterator.hasNext() && j < nearestNeighbors ) {
nnArray[j] = (Instance) ((Object[]) entryIterator.next())[1];
j++;
}
// create synthetic examples
if( nearestNeighbors == 0 ) {
return;
}
int n = (int) Math.floor( getPercentage() / 100 );
while( n > 0 || extraIndexSet.remove( i ) ) {
double[] values = new double[sample.numAttributes()];
int nn = rand.nextInt( nearestNeighbors );
attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
if( attr.isNumeric() ) {
double dif = nnArray[nn].value( attr ) - instanceI.value( attr );
double gap = rand.nextDouble();
values[attr.index()] = (double) (instanceI.value( attr ) + gap * dif);
} else if( attr.isDate() ) {
double dif = nnArray[nn].value( attr ) - instanceI.value( attr );
double gap = rand.nextDouble();
values[attr.index()] = (long) (instanceI.value( attr ) + gap * dif);
} else {
int[] valueCounts = new int[attr.numValues()];
int iVal = (int) instanceI.value( attr );
valueCounts[iVal]++;
for( int nnEx = 0; nnEx < nearestNeighbors; nnEx++ ) {
int val = (int) nnArray[nnEx].value( attr );
valueCounts[val]++;
}
int maxIndex = 0;
int max = Integer.MIN_VALUE;
for( int index = 0; index < attr.numValues(); index++ ) {
if( valueCounts[index] > max ) {
max = valueCounts[index];
maxIndex = index;
}
}
values[attr.index()] = maxIndex;
}
}
}
values[sample.classIndex()] = minIndex;
Instance synthetic = new Instance( 1.0, values );
push( synthetic );
n--;
}
}
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter:
* use -h for help
*/
public static void main( String[] argv ) {
try {
if( Utils.getFlag( 'b', argv ) ) {
Filter.batchFilterFile( new SMOTE(), argv );
} else {
Filter.filterFile( new SMOTE(), argv );
}
} catch( Exception ex ) {
ex.printStackTrace();
System.out.println( ex.getMessage() );
}
}
}
| rlichtenwalter/LPmade | weka/src/weka/filters/supervised/instance/SMOTE.java | 7,212 | // make it an index | line_comment | nl | /*
* 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.
*
* 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, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* SMOTE.java
*
* Copyright (C) 2008 Ryan Lichtenwalter
* Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
*/
package weka.filters.supervised.instance;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformationHandler;
import weka.core.UnsupportedClassTypeException;
import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.SupervisedFilter;
/**
<!-- globalinfo-start -->
* Resamples a dataset by applying the Synthetic Minority Oversampling TEchnique (SMOTE). The original dataset must fit entirely in memory. The amount of SMOTE and number of nearest neighbors may be specified. For more information, see <br/>
* <br/>
* Nitesh V. Chawla et. al. (2002). Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research. 16:321-357.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @article{al.2002,
* author = {Nitesh V. Chawla et. al.},
* journal = {Journal of Artificial Intelligence Research},
* pages = {321-357},
* title = {Synthetic Minority Over-sampling Technique},
* volume = {16},
* year = {2002}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <num>
* Specifies the random number seed (default 1)</pre>
*
* <pre> -P <percentage>
* Specifies percentage of SMOTE instances to create. (default 100.0)
* </pre>
*
* <pre> -K <nearest-neighbors>
* Specifies the number of nearest neighbors to use. (default 5)
* </pre>
*
* <pre> -C <value-index>
* Specifies the index of the nominal class value to SMOTE
* (default 0: auto-detect non-empty minority class))
* </pre>
*
<!-- options-end -->
*
* @author Ryan Lichtenwalter ([email protected])
* @version $Revision: 1.0$
*/
public class SMOTE extends Filter
implements SupervisedFilter, OptionHandler, TechnicalInformationHandler {
static final long serialVersionUID = -1653880819059250364L;
protected int m_NearestNeighbors = 5;
protected int m_RandomSeed = 1;
protected double m_Percentage = 100.0;
protected String m_ClassValueIndex = "0";
protected boolean m_DetectMinorityClass = true;
/**
* Returns a string describing this classifier
* @return a description of the classifier suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return "Resamples a dataset by applying the Synthetic Minority Oversampling TEchnique (SMOTE)." +
" The original dataset must fit entirely in memory." +
" The amount of SMOTE and number of nearest neighbors may be specified." +
" For more information, see \n\n" + getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result = new TechnicalInformation( Type.ARTICLE );
result.setValue( Field.AUTHOR, "Nitesh V. Chawla et. al." );
result.setValue( Field.TITLE, "Synthetic Minority Over-sampling Technique" );
result.setValue( Field.JOURNAL, "Journal of Artificial Intelligence Research" );
result.setValue( Field.YEAR, "2002" );
result.setValue( Field.VOLUME, "16" );
result.setValue( Field.PAGES, "321-357" );
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract( "$Revision: 1.0$" );
}
/**
* Returns the Capabilities of this filter.
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enableAllAttributes();
result.enable( Capability.MISSING_VALUES );
// class
result.enable( Capability.NOMINAL_CLASS );
result.enable( Capability.MISSING_CLASS_VALUES );
return result;
}
/**
* Default constructor.
*/
public SMOTE() {
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector( 3 );
newVector.addElement( new Option(
"\tSpecifies the random number seed (default 1)",
"S", 1, "-S <num>" ) );
newVector.addElement( new Option(
"\tSpecifies percentage of SMOTE instances to create. (default 100.0)\n",
"P", 1, "-P <percentage>" ) );
newVector.addElement( new Option(
"\tSpecifies the number of nearest neighbors to use. (default 5)\n",
"K", 1, "-K <nearest-neighbors>" ) );
newVector.addElement( new Option(
"\tSpecifies the index of the nominal class value to SMOTE\n" + "\t(default 0: auto-detect non-empty minority class))\n",
"C", 1, "-C <value-index>" ) );
/* newVector.addElement( new Option(
"\tSpecifies whether the non-empty minority class should be auto-detected (default true)\n",
"d", 1, "-d" ) ); */
return newVector.elements();
}
/**
* Parses a given list of options.
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S <num>
* Specifies the random number seed (default 1)</pre>
*
* <pre> -P <percentage>
* Specifies percentage of SMOTE instances to create. (default 100.0)
* </pre>
*
* <pre> -K <nearest-neighbors>
* Specifies the number of nearest neighbors to use. (default 5)
* </pre>
*
* <pre> -C <value-index>
* Specifies the index of the nominal class value to SMOTE
* (default 0: auto-detect non-empty minority class))
* </pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
public void setOptions( String[] options ) throws Exception {
String seedStr = Utils.getOption( 'S', options );
if( seedStr.length() != 0 ) {
setRandomSeed( Integer.parseInt( seedStr ) );
} else {
setRandomSeed( 1 );
}
String percentageStr = Utils.getOption( 'P', options );
if( percentageStr.length() != 0 ) {
double percentage = new Double( percentageStr ).doubleValue();
if( percentage < 0 ) {
throw new Exception( "P must be >= 0" );
} else {
setPercentage( percentage );
}
} else {
setPercentage( 100.0 );
}
String nnStr = Utils.getOption( 'K', options );
if( nnStr.length() != 0 ) {
int nn = Integer.parseInt( nnStr );
if( nn < 1 ) {
throw new Exception( "K must be >= 1" );
} else {
setNearestNeighbors( nn );
}
} else {
setNearestNeighbors( 5 );
}
String classValueIndexStr = Utils.getOption( 'C', options );
if( classValueIndexStr.length() != 0 ) {
setClassValue( classValueIndexStr );
if( classValueIndexStr.equals( "0" ) ) {
m_DetectMinorityClass = true;
} else {
m_DetectMinorityClass = false;
}
} else {
m_DetectMinorityClass = true;
}
}
/**
* Gets the current settings of the filter.
*
* @return an array of strings suitable for passing to setOptions
*/
public String[] getOptions() {
String[] options = new String[11];
int current = 0;
options[current++] = "-C";
options[current++] = getClassValue();
options[current++] = "-K";
options[current++] = "" + getNearestNeighbors();
options[current++] = "-P";
options[current++] = "" + getPercentage();
options[current++] = "-S";
options[current++] = "" + getRandomSeed();
while( current < options.length ) {
options[current++] = "";
}
return options;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String randomSeedTipText() {
return "The seed used for random sampling.";
}
/**
* Gets the random number seed.
*
* @return the random number seed.
*/
public int getRandomSeed() {
return m_RandomSeed;
}
/**
* Sets the random number seed.
*
* @param newSeed the new random number seed.
*/
public void setRandomSeed( int newSeed ) {
m_RandomSeed = newSeed;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String percentageTipText() {
return "The percentage of SMOTE instances to create.";
}
/**
* Sets the percentage of SMOTE instances to create.
*
* @param percentage
*/
public void setPercentage( double percentage ) {
m_Percentage = percentage;
}
/**
* Gets the percentage of SMOTE instances to create.
*
* @return the percentage of SMOTE instances to create
*/
public double getPercentage() {
return m_Percentage;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String nearestNeighborsTipText() {
return "The number of nearest neighbors to use.";
}
/**
* Sets the number of nearest neighbors to use.
*
* @param nearestNeighbors
*/
public void setNearestNeighbors( int nearestNeighbors ) {
m_NearestNeighbors = nearestNeighbors;
}
/**
* Gets the number of nearest neighbors to use.
*
* @return the number of nearest neighbors to use
*/
public int getNearestNeighbors() {
return m_NearestNeighbors;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String classValueTipText() {
return "The index of the class value to which SMOTE should be applied. " +
"Use a value of 0 to auto-detect the non-empty minority class.";
}
/**
* Sets the index of the class value to which SMOTE should be applied.
*
* @param classValueIndex
*/
public void setClassValue( String classValueIndex ) {
m_ClassValueIndex = classValueIndex;
}
/**
* Gets the index of the class value to which SMOTE should be applied.
*
* @return the index of the clas value to which SMOTE should be applied
*/
public String getClassValue() {
return m_ClassValueIndex;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String detectMinorityClassTipText() {
return "Whether the non-empty minority class should be automatically " +
"detected.";
}
/**
* Sets whether or not the minority class should be auto-detected.
*
* @param detectMinorityClass
*/
public void setDetectMinorityClass( boolean detectMinorityClass ) {
m_DetectMinorityClass = detectMinorityClass;
}
/**
* Gets whether or not the minority class should be auto-detected.
*
* @return true if the minority class should be auto-detected;
* false otherwise
*
public boolean getDetectMinorityClass() {
return m_DetectMinorityClass;
} */
/**
* Sets the format of the input instances.
*
* @param instanceInfo an Instances object containing the input
* instance structure (any instances contained in the object are
* ignored - only the structure is required).
* @return true if the outputFormat may be collected immediately
* @exception Exception if the input format can't be set
* successfully
*/
public boolean setInputFormat( Instances instanceInfo ) throws Exception {
super.setInputFormat( instanceInfo );
super.setOutputFormat( instanceInfo );
return true;
}
/**
* Input an instance for filtering. Filter requires all
* training instances be read before producing output.
*
* @param instance the input instance
* @return true if the filtered instance may now be
* collected with output().
* @exception IllegalStateException if no input structure has been defined
*/
public boolean input( Instance instance ) {
if( getInputFormat() == null ) {
throw new IllegalStateException( "No input instance format defined" );
}
if( m_NewBatch ) {
resetQueue();
m_NewBatch = false;
}
if( m_FirstBatchDone ) {
push( instance );
return true;
} else {
bufferInput( instance );
return false;
}
}
/**
* Signify that this batch of input to the filter is finished.
* If the filter requires all instances prior to filtering,
* output() may now be called to retrieve the filtered instances.
*
* @return true if there are instances pending output
* @exception IllegalStateException if no input structure has been defined
* @exception Exception if provided options cannot be executed
* on input instances
*/
public boolean batchFinished() throws Exception {
if( getInputFormat() == null ) {
throw new IllegalStateException( "No input instance format defined" );
}
if( !m_FirstBatchDone ) {
// Do SMOTE, and clear the input instances.
doSMOTE();
}
flushInput();
m_NewBatch = true;
m_FirstBatchDone = true;
return (numPendingOutput() != 0);
}
/**
* The procedure implementing the SMOTE algorithm. The output
* instances are pushed onto the output queue for collection.
*
* @exception Exception if provided options cannot be executed
* on input instances
*/
public void doSMOTE() throws Exception {
int minIndex = 0;
int min = Integer.MAX_VALUE;
int[] classCounts = getInputFormat().attributeStats( getInputFormat().classIndex() ).nominalCounts;
if( m_DetectMinorityClass ) {
// find minority class
for( int i = 0; i < classCounts.length; i++ ) {
if( classCounts[i] != 0 && classCounts[i] < min ) {
min = classCounts[i];
minIndex = i;
}
}
} else {
String classVal = getClassValue();
if( classVal.equalsIgnoreCase( "first" ) ) {
minIndex = 1;
} else if( classVal.equalsIgnoreCase( "last" ) ) {
minIndex = getInputFormat().numClasses();
} else {
minIndex = Integer.parseInt( classVal );
}
if( minIndex > getInputFormat().numClasses() ) {
throw new Exception( "value index must be <= the number of classes" );
}
minIndex--; // make it<SUF>
min = classCounts[minIndex];
}
int nearestNeighbors = Math.min( getNearestNeighbors(), min - 1 );
// compose minority class dataset
// also push all dataset instances
Instances sample = getInputFormat().stringFreeStructure();
Enumeration instanceEnum = getInputFormat().enumerateInstances();
while( instanceEnum.hasMoreElements() ) {
Instance instance = (Instance) instanceEnum.nextElement();
push( (Instance) instance.copy() );
if( (int) instance.classValue() == minIndex ) {
sample.add( instance );
}
}
// compute Value Distance Metric matrices for nominal features
Map vdmMap = new HashMap();
Enumeration attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
if( attr.isNominal() || attr.isString() ) {
double[][] vdm = new double[attr.numValues()][attr.numValues()];
vdmMap.put( attr, vdm );
int[] featureValueCounts = new int[attr.numValues()];
int[][] featureValueCountsByClass = new int[getInputFormat().classAttribute().numValues()][attr.numValues()];
instanceEnum = getInputFormat().enumerateInstances();
while( instanceEnum.hasMoreElements() ) {
Instance instance = (Instance) instanceEnum.nextElement();
int value = (int) instance.value( attr );
int classValue = (int) instance.classValue();
featureValueCounts[value]++;
featureValueCountsByClass[classValue][value]++;
}
for( int valueIndex1 = 0; valueIndex1 < attr.numValues(); valueIndex1++ ) {
for( int valueIndex2 = 0; valueIndex2 < attr.numValues(); valueIndex2++ ) {
double sum = 0;
for( int classValueIndex = 0; classValueIndex < getInputFormat().numClasses(); classValueIndex++ ) {
double c1i = (double) featureValueCountsByClass[classValueIndex][valueIndex1];
double c2i = (double) featureValueCountsByClass[classValueIndex][valueIndex2];
double c1 = (double) featureValueCounts[valueIndex1];
double c2 = (double) featureValueCounts[valueIndex2];
double term1 = c1i / c1;
double term2 = c2i / c2;
sum += Math.abs( term1 - term2 );
}
vdm[valueIndex1][valueIndex2] = sum;
}
}
}
}
}
// use this random source for all required randomness
Random rand = new Random( getRandomSeed() );
// find the set of extra indices to use if the percentage is not evenly divisible by 100
List extraIndices = new LinkedList();
double percentageRemainder = (getPercentage() / 100) - Math.floor( getPercentage() / 100.0 );
int extraIndicesCount = (int) (percentageRemainder * sample.numInstances());
if( extraIndicesCount >= 1 ) {
for( int i = 0; i < sample.numInstances(); i++ ) {
extraIndices.add( i );
}
}
Collections.shuffle( extraIndices, rand );
extraIndices = extraIndices.subList( 0, extraIndicesCount );
Set extraIndexSet = new HashSet( extraIndices );
// the main loop to handle computing nearest neighbors and generating SMOTE
// examples from each instance in the original minority class data
Instance[] nnArray = new Instance[nearestNeighbors];
for( int i = 0; i < sample.numInstances(); i++ ) {
Instance instanceI = sample.instance( i );
// find k nearest neighbors for each instance
List distanceToInstance = new LinkedList();
for( int j = 0; j < sample.numInstances(); j++ ) {
Instance instanceJ = sample.instance( j );
if( i != j ) {
double distance = 0;
attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
double iVal = instanceI.value( attr );
double jVal = instanceJ.value( attr );
if( attr.isNumeric() ) {
distance += Math.pow( iVal - jVal, 2 );
} else {
distance += ((double[][]) vdmMap.get( attr ))[(int) iVal][(int) jVal];
}
}
}
distance = Math.pow( distance, .5 );
distanceToInstance.add( new Object[]{distance, instanceJ} );
}
}
// sort the neighbors according to distance
Collections.sort( distanceToInstance, new Comparator() {
public int compare( Object o1, Object o2 ) {
double distance1 = (Double) ((Object[]) o1)[0];
double distance2 = (Double) ((Object[]) o2)[0];
return (int) Math.ceil( distance1 - distance2 );
}
} );
// populate the actual nearest neighbor instance array
Iterator entryIterator = distanceToInstance.iterator();
int j = 0;
while( entryIterator.hasNext() && j < nearestNeighbors ) {
nnArray[j] = (Instance) ((Object[]) entryIterator.next())[1];
j++;
}
// create synthetic examples
if( nearestNeighbors == 0 ) {
return;
}
int n = (int) Math.floor( getPercentage() / 100 );
while( n > 0 || extraIndexSet.remove( i ) ) {
double[] values = new double[sample.numAttributes()];
int nn = rand.nextInt( nearestNeighbors );
attrEnum = getInputFormat().enumerateAttributes();
while( attrEnum.hasMoreElements() ) {
Attribute attr = (Attribute) attrEnum.nextElement();
if( !attr.equals( getInputFormat().classAttribute() ) ) {
if( attr.isNumeric() ) {
double dif = nnArray[nn].value( attr ) - instanceI.value( attr );
double gap = rand.nextDouble();
values[attr.index()] = (double) (instanceI.value( attr ) + gap * dif);
} else if( attr.isDate() ) {
double dif = nnArray[nn].value( attr ) - instanceI.value( attr );
double gap = rand.nextDouble();
values[attr.index()] = (long) (instanceI.value( attr ) + gap * dif);
} else {
int[] valueCounts = new int[attr.numValues()];
int iVal = (int) instanceI.value( attr );
valueCounts[iVal]++;
for( int nnEx = 0; nnEx < nearestNeighbors; nnEx++ ) {
int val = (int) nnArray[nnEx].value( attr );
valueCounts[val]++;
}
int maxIndex = 0;
int max = Integer.MIN_VALUE;
for( int index = 0; index < attr.numValues(); index++ ) {
if( valueCounts[index] > max ) {
max = valueCounts[index];
maxIndex = index;
}
}
values[attr.index()] = maxIndex;
}
}
}
values[sample.classIndex()] = minIndex;
Instance synthetic = new Instance( 1.0, values );
push( synthetic );
n--;
}
}
}
/**
* Main method for testing this class.
*
* @param argv should contain arguments to the filter:
* use -h for help
*/
public static void main( String[] argv ) {
try {
if( Utils.getFlag( 'b', argv ) ) {
Filter.batchFilterFile( new SMOTE(), argv );
} else {
Filter.filterFile( new SMOTE(), argv );
}
} catch( Exception ex ) {
ex.printStackTrace();
System.out.println( ex.getMessage() );
}
}
}
|
22211_0 | package nl.designpatterns.builder;
import java.util.Date;
public class VacationBuilder {
private static VacationBuilder builder = new VacationBuilder();
private VacationBuilder() {}
public static VacationBuilder getInstance() {
return builder;
}
private Vacation vacation = new Vacation();
public void addPersoon(String voornaam, String achternaam) {
Persoon p = new Persoon(achternaam, voornaam, new Date());
this.vacation.addPersoon(p);
}
public void setHotel(String name) {
this.vacation.setHotel(new Hotel(name));
}
public void setReservation(String in, String uit) {
// test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java.
Date inDate = new Date();
Date outDate = new Date(new Date().getTime()-10000);
Reservation reservation = new Reservation(inDate, outDate);
this.vacation.setReservation(reservation);
}
public void addActivity(Activity activity) {
this.vacation.addActivity(activity);
}
public Vacation getVacation() {
return this.vacation;
}
}
| rloman/design-patterns | src/main/java/nl/designpatterns/builder/VacationBuilder.java | 356 | // test normaliter zou ik datum moeten parsen maar dat vind ik nog steeds zuigen in Java. | line_comment | nl | package nl.designpatterns.builder;
import java.util.Date;
public class VacationBuilder {
private static VacationBuilder builder = new VacationBuilder();
private VacationBuilder() {}
public static VacationBuilder getInstance() {
return builder;
}
private Vacation vacation = new Vacation();
public void addPersoon(String voornaam, String achternaam) {
Persoon p = new Persoon(achternaam, voornaam, new Date());
this.vacation.addPersoon(p);
}
public void setHotel(String name) {
this.vacation.setHotel(new Hotel(name));
}
public void setReservation(String in, String uit) {
// test normaliter<SUF>
Date inDate = new Date();
Date outDate = new Date(new Date().getTime()-10000);
Reservation reservation = new Reservation(inDate, outDate);
this.vacation.setReservation(reservation);
}
public void addActivity(Activity activity) {
this.vacation.addActivity(activity);
}
public Vacation getVacation() {
return this.vacation;
}
}
|
41822_0 | package nl.music.model;
import nl.music.behaviour.PlayWithStrings;
public class GuitarFactory extends InstrumentFactory {
@Override
public Guitar getInstrument() {
Guitar guitar = new Guitar("Brandless", 6); // moeilijker kan ik het niet maken, wel makkelijker
guitar.setPlayBehaviour(new PlayWithStrings());
return guitar;
}
}
| rloman/music-design-patterns | src/nl/music/model/GuitarFactory.java | 113 | // moeilijker kan ik het niet maken, wel makkelijker | line_comment | nl | package nl.music.model;
import nl.music.behaviour.PlayWithStrings;
public class GuitarFactory extends InstrumentFactory {
@Override
public Guitar getInstrument() {
Guitar guitar = new Guitar("Brandless", 6); // moeilijker kan<SUF>
guitar.setPlayBehaviour(new PlayWithStrings());
return guitar;
}
}
|
127839_0 | import java.util.*;
import gegevens.*;
import oplossing.*;
import LokaalZoeken.*;
public class Main {
private static ArrayList<Reservatie> reservaties = new ArrayList<Reservatie>();;
private static ArrayList<Voertuig> voertuigen = new ArrayList<Voertuig>();
private static ArrayList<Zone> zones = new ArrayList<Zone>();
private static ArrayList<AReservatie> areservaties = new ArrayList<AReservatie>();
private static ArrayList<AVoertuig> avoertuigen = new ArrayList<AVoertuig>();
private static Readcsv lees;
private static Writecsv schrijf;
private static Tijdschema tijdschema;
public static void main(String[] args) {
//argumenten inlezen
String inputfile = args[0];
String outputfile = args[1];
long tijdslimiet = Long.parseLong(args[2]); //tijd in seconden
long randomseed = Long.parseLong(args[3]);
int numThreads = Integer.parseInt(args[4]);
tijdslimiet = tijdslimiet * 1000; //van seconden naar miliseconden omzetten
//INLEZEN
lees = new Readcsv(inputfile);
reservaties = lees.LeesReservaties();
int kost;
//testprint van reservaties
for(int i = 0; i< reservaties.size(); i++)
{
System.out.println(reservaties.get(i).getVoertuigID());
}
zones = lees.LeesZones();
//testprint van zones
for(int i = 0; i< zones.size(); i++)
{
System.out.println(zones.get(i).getAanliggendId());
}
voertuigen = lees.LeesVoertuigen();
//testprint van zones
for(int i = 0; i< voertuigen.size(); i++)
{
System.out.println(voertuigen.get(i).getId());
}
lees.closeLees();
//dagen ook uitlezen, laatste lijn csv?
//Initiele oplossing genereren
avoertuigen = InitieleOplossing.genereerVoertuig(voertuigen, zones);
areservaties = InitieleOplossing.genereerReservatie(reservaties);
//Kost berekenen
kost = BerekenKost.bereken(avoertuigen, areservaties);
//Kost initiele oplossing
System.out.println("Kost: " + Integer.toString(kost));
AOplossing oplossing = new AOplossing(areservaties, avoertuigen);
//Tijdschema genereren
tijdschema = new Tijdschema(reservaties);
//Lokaal zoeken
Zoeken zoek = new Zoeken();
oplossing = zoek.zoeken(oplossing, zones, reservaties, tijdschema, tijdslimiet, randomseed);
//Kost berekenen
kost = BerekenKost.bereken(oplossing.getVoertuig(), oplossing.getReservatie());
System.out.println("Bestkost (In main)= "+ kost);
// wegschrijven naar file
schrijf = new Writecsv(outputfile);
schrijf.writeTocsv(kost, oplossing.getReservatie(), oplossing.getVoertuig());
}
}
| robbe000/Artificiele-Intelligentie-Project-Cambio | src/Main.java | 961 | //tijd in seconden | line_comment | nl | import java.util.*;
import gegevens.*;
import oplossing.*;
import LokaalZoeken.*;
public class Main {
private static ArrayList<Reservatie> reservaties = new ArrayList<Reservatie>();;
private static ArrayList<Voertuig> voertuigen = new ArrayList<Voertuig>();
private static ArrayList<Zone> zones = new ArrayList<Zone>();
private static ArrayList<AReservatie> areservaties = new ArrayList<AReservatie>();
private static ArrayList<AVoertuig> avoertuigen = new ArrayList<AVoertuig>();
private static Readcsv lees;
private static Writecsv schrijf;
private static Tijdschema tijdschema;
public static void main(String[] args) {
//argumenten inlezen
String inputfile = args[0];
String outputfile = args[1];
long tijdslimiet = Long.parseLong(args[2]); //tijd in<SUF>
long randomseed = Long.parseLong(args[3]);
int numThreads = Integer.parseInt(args[4]);
tijdslimiet = tijdslimiet * 1000; //van seconden naar miliseconden omzetten
//INLEZEN
lees = new Readcsv(inputfile);
reservaties = lees.LeesReservaties();
int kost;
//testprint van reservaties
for(int i = 0; i< reservaties.size(); i++)
{
System.out.println(reservaties.get(i).getVoertuigID());
}
zones = lees.LeesZones();
//testprint van zones
for(int i = 0; i< zones.size(); i++)
{
System.out.println(zones.get(i).getAanliggendId());
}
voertuigen = lees.LeesVoertuigen();
//testprint van zones
for(int i = 0; i< voertuigen.size(); i++)
{
System.out.println(voertuigen.get(i).getId());
}
lees.closeLees();
//dagen ook uitlezen, laatste lijn csv?
//Initiele oplossing genereren
avoertuigen = InitieleOplossing.genereerVoertuig(voertuigen, zones);
areservaties = InitieleOplossing.genereerReservatie(reservaties);
//Kost berekenen
kost = BerekenKost.bereken(avoertuigen, areservaties);
//Kost initiele oplossing
System.out.println("Kost: " + Integer.toString(kost));
AOplossing oplossing = new AOplossing(areservaties, avoertuigen);
//Tijdschema genereren
tijdschema = new Tijdschema(reservaties);
//Lokaal zoeken
Zoeken zoek = new Zoeken();
oplossing = zoek.zoeken(oplossing, zones, reservaties, tijdschema, tijdslimiet, randomseed);
//Kost berekenen
kost = BerekenKost.bereken(oplossing.getVoertuig(), oplossing.getReservatie());
System.out.println("Bestkost (In main)= "+ kost);
// wegschrijven naar file
schrijf = new Writecsv(outputfile);
schrijf.writeTocsv(kost, oplossing.getReservatie(), oplossing.getVoertuig());
}
}
|
58276_0 | import com.bitvavo.api.Bitvavo;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class AutoBuy {
private static final DecimalFormat DECIMAL_FORMAT = getDecimalFormat();
private static final double SPARE_EUROS = 1;
private static final double MINIMUM_EUROS_AVAILABLE = 10;
private final Bitvavo bitvavo;
public static void main(String[] args){
String apiKey = System.getenv("BITVAVO_API_KEY");
String secret = System.getenv("BITVAVO_SECRET");
if (apiKey==null) fail("BITVAVO_API_KEY env is not set");
if (secret==null) fail("BITVAVO_SECRET env is not set");
Bitvavo bitvavo = new Bitvavo(new JSONObject("{" +
"APIKEY: '"+apiKey+"', " +
"APISECRET: '"+secret+"', " +
"RESTURL: 'https://api.bitvavo.com/v2'," +
"WSURL: 'wss://ws.bitvavo.com/v2/'," +
"ACCESSWINDOW: 10000, " +
"DEBUGGING: false }"));
new AutoBuy(bitvavo).start();
}
public AutoBuy(Bitvavo bitvavo) {
this.bitvavo = bitvavo;
}
private void start() {
try {
double euroBalance = getEuroBalance();
double btcBalance = getBtcBalance();
System.out.println("Current euro balance:" + euroBalance);
System.out.println("Current btc balance:" + btcBalance);
if (euroBalance > MINIMUM_EUROS_AVAILABLE) {
double btcPriceD = getBtcPriceD();
String toBuyString = calculateAmountToBuy(euroBalance, btcPriceD);
System.out.println("Buying " + toBuyString + " bitcoin, for a price of : " + btcPriceD);
String buyResult = buyBtc(toBuyString);
double newEuroBalance = getEuroBalance();
double newBtcBalance = getBtcBalance();
System.out.println("New euro balance:" + newEuroBalance);
System.out.println("New btc balance:" + newBtcBalance);
System.out.println("\n\nBuy result:" + buyResult);
} else {
System.out.println("Minimal " + MINIMUM_EUROS_AVAILABLE + " euro is needed for an automatic buy");
System.exit(1);
}
System.exit(0);
}
catch (Exception e){
e.printStackTrace();
System.exit(50);
}
}
private double getEuroBalance() {
JSONArray response = bitvavo.balance(new JSONObject());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("symbol").equals("EUR")) {
String euros = jsonObject.get("available").toString();
return Double.parseDouble(euros);
}
}
throw new RuntimeException("Euro balance could not be found");
}
private double getBtcBalance() {
JSONArray response = bitvavo.balance(new JSONObject());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("symbol").equals("BTC")) {
String euros = jsonObject.get("available").toString();
return Double.parseDouble(euros);
}
}
throw new RuntimeException("Euro balance could not be found");
}
private double getBtcPriceD() {
JSONArray response = bitvavo.tickerPrice(new JSONObject("{ market: BTC-EUR }"));
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("market").equals("BTC-EUR")) {
String btcPrice = jsonObject.get("price").toString();
return Double.parseDouble(btcPrice);
}
}
throw new RuntimeException("BTC price could not be found");
}
private String buyBtc(String toBuyString) {
return bitvavo.placeOrder("BTC-EUR", "buy", "market", new JSONObject("{ amount: " + toBuyString + " }")).toString(2);
}
private String calculateAmountToBuy(double euroAvail, double btcPrice) {
return DECIMAL_FORMAT.format((euroAvail-SPARE_EUROS)/ btcPrice);
}
private static DecimalFormat getDecimalFormat() {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator('.');
return new DecimalFormat("#.######",otherSymbols); // 1 miljoenste : bij 1 miljoen: 1 euro
}
private static void fail(String s) {
System.out.println(s);
System.exit(-1);
}
}
| robbertvdzon/bitvavo-autobuy | src/main/java/AutoBuy.java | 1,427 | // 1 miljoenste : bij 1 miljoen: 1 euro | line_comment | nl | import com.bitvavo.api.Bitvavo;
import org.json.JSONArray;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class AutoBuy {
private static final DecimalFormat DECIMAL_FORMAT = getDecimalFormat();
private static final double SPARE_EUROS = 1;
private static final double MINIMUM_EUROS_AVAILABLE = 10;
private final Bitvavo bitvavo;
public static void main(String[] args){
String apiKey = System.getenv("BITVAVO_API_KEY");
String secret = System.getenv("BITVAVO_SECRET");
if (apiKey==null) fail("BITVAVO_API_KEY env is not set");
if (secret==null) fail("BITVAVO_SECRET env is not set");
Bitvavo bitvavo = new Bitvavo(new JSONObject("{" +
"APIKEY: '"+apiKey+"', " +
"APISECRET: '"+secret+"', " +
"RESTURL: 'https://api.bitvavo.com/v2'," +
"WSURL: 'wss://ws.bitvavo.com/v2/'," +
"ACCESSWINDOW: 10000, " +
"DEBUGGING: false }"));
new AutoBuy(bitvavo).start();
}
public AutoBuy(Bitvavo bitvavo) {
this.bitvavo = bitvavo;
}
private void start() {
try {
double euroBalance = getEuroBalance();
double btcBalance = getBtcBalance();
System.out.println("Current euro balance:" + euroBalance);
System.out.println("Current btc balance:" + btcBalance);
if (euroBalance > MINIMUM_EUROS_AVAILABLE) {
double btcPriceD = getBtcPriceD();
String toBuyString = calculateAmountToBuy(euroBalance, btcPriceD);
System.out.println("Buying " + toBuyString + " bitcoin, for a price of : " + btcPriceD);
String buyResult = buyBtc(toBuyString);
double newEuroBalance = getEuroBalance();
double newBtcBalance = getBtcBalance();
System.out.println("New euro balance:" + newEuroBalance);
System.out.println("New btc balance:" + newBtcBalance);
System.out.println("\n\nBuy result:" + buyResult);
} else {
System.out.println("Minimal " + MINIMUM_EUROS_AVAILABLE + " euro is needed for an automatic buy");
System.exit(1);
}
System.exit(0);
}
catch (Exception e){
e.printStackTrace();
System.exit(50);
}
}
private double getEuroBalance() {
JSONArray response = bitvavo.balance(new JSONObject());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("symbol").equals("EUR")) {
String euros = jsonObject.get("available").toString();
return Double.parseDouble(euros);
}
}
throw new RuntimeException("Euro balance could not be found");
}
private double getBtcBalance() {
JSONArray response = bitvavo.balance(new JSONObject());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("symbol").equals("BTC")) {
String euros = jsonObject.get("available").toString();
return Double.parseDouble(euros);
}
}
throw new RuntimeException("Euro balance could not be found");
}
private double getBtcPriceD() {
JSONArray response = bitvavo.tickerPrice(new JSONObject("{ market: BTC-EUR }"));
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
if (jsonObject.get("market").equals("BTC-EUR")) {
String btcPrice = jsonObject.get("price").toString();
return Double.parseDouble(btcPrice);
}
}
throw new RuntimeException("BTC price could not be found");
}
private String buyBtc(String toBuyString) {
return bitvavo.placeOrder("BTC-EUR", "buy", "market", new JSONObject("{ amount: " + toBuyString + " }")).toString(2);
}
private String calculateAmountToBuy(double euroAvail, double btcPrice) {
return DECIMAL_FORMAT.format((euroAvail-SPARE_EUROS)/ btcPrice);
}
private static DecimalFormat getDecimalFormat() {
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.getDefault());
otherSymbols.setDecimalSeparator('.');
return new DecimalFormat("#.######",otherSymbols); // 1 miljoenste<SUF>
}
private static void fail(String s) {
System.out.println(s);
System.exit(-1);
}
}
|
101014_12 | package nl.hva.robertmark.sortingsearching.practicum1;
import nl.hva.dmci.ict.inf.ads.lib.StdRandom;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author Robert
*/
public class ResultList {
private Student[] studentList;
private int pos = 0;
private int totalGroups;
private int N = 0;
private int swaps = 0;
private int compares = 0;
public int getSwaps() {
return swaps;
}
public int getCompares() {
return compares;
}
public ResultList(int s, int totalGroups) {
studentList = new Student[s];
this.totalGroups = totalGroups;
N = studentList.length;
}
public void add(Student item) {
studentList[pos++] = item;
}
public Student[] getList() {
return studentList;
}
public void shuffle() {
StdRandom.shuffle(studentList);
}
public void sort() {
swaps = 0;
compares = 0;
quicksort(studentList, 0, studentList.length - 1);
}
public void median3sort() {
swaps = 0;
compares = 0;
median3sort(studentList, 0, studentList.length - 1);
}
private int median3(Comparable[] list, int a, int b, int c) {
if (list[a].compareTo(list[b]) <= 0) {
compares++;
if (list[b].compareTo(list[c]) <= 0) {
compares++;
return b;
}
else if (list[a].compareTo(list[c]) <= 0) {
compares++;
return c;
}
else
return a;
} else {
if (list[a].compareTo(list[c]) <= 0) {
compares++;
return a;
}
else if (list[b].compareTo(list[c]) <= 0) {
compares++;
return c;
}
else
return b;
}
}
private int median3(Comparable[] list, int left, int right) {
int center = (left + right) / 2;
if(list[center].compareTo(list[left]) < 0)
swap(list,left, center);
if(list[right].compareTo(list[left]) < 0)
swap(list, left, right);
if(list[right].compareTo(list[center]) < 0)
swap(list, center, right);
swap(list, center, right - 1);
return center;
}
private void median3sort(Comparable[] list, int low, int high) {
int i = low, j = high;
int n = high - low + 1;
int mid = (low + high) / 2;
// Bepaal de spil nu door middel van een steekproefgrootte van 3 en de middelste
// daarvan blijkt het meest efficient te zin
int m = median3(list, low, mid, high);
Comparable pivot = list[m];
// swap(list, m, low);
while (i <= j) {
// Wanneer object vanaf links kleiner is dan de spil
// Verschuif naar de volgende in de linkerlijst
while (list[i].compareTo(pivot) < 0) {
i++;
compares++;
}
// Wanneer object vanaf rechts groter is dan de spil
// Verschuif naar de volgende in de rechterlijst
while (list[j].compareTo(pivot) > 0) {
j--;
compares++;
}
// Als er een index van de linkerlijst is gevonden, met een waarde
// die groter is dan de spil, en een index in de rechterlijst met
// een waarde die kleiner is dan de spil, moeten de 2 waarden
// worden omgedraaid
if (i <= j) {
swap(list, i, j);
i++;
j--;
}
}
// Hetzelfde de rest van de linkerlijst
if (low < j) {
median3sort(list, low, j);
}
// en voor de rechterlijst
if (high > i) {
median3sort(list, i, high);
}
}
private void swap(Comparable[] list, int i, int j) {
swaps++;
Comparable temp = list[i];
list[i] = list[j];
list[j] = temp;
}
private static boolean less(Comparable v, Comparable w) {
int compare = v.compareTo(w);
// Geef een boolean terug a.d.h.v. de vergelijking met de compare, - 1
// in de compare betekend a < b
return compare == 1;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
// De quicksort accepteert een lijst van objecten met een comparable
// interface, het beginpunt van links, en het beginpunt van rechts
private void quicksort(Comparable[] list, int low, int high) {
// Neem het middelpunt van de array als spil (draaipunt)
Comparable pivot = list[low + (high - low) / 2];
int i = low; // linkerkant
int j = high; // rechterkant
while (i < j) {
// Wanneer object vanaf links kleiner is dan de spil
// Verschuif naar de volgende in de linkerlijst
while (list[i].compareTo(pivot) < 0) {
i++;
compares++;
}
// Wanneer object vanaf rechts groter is dan de spil
// Verschuif naar de volgende in de rechterlijst
while (list[j].compareTo(pivot) > 0) {
j--;
compares++;
}
// Als er een index van de linkerlijst is gevonden, met een waarde
// die groter is dan de spil, en een index in de rechterlijst met
// een waarde die kleiner is dan de spil, moeten de 2 waarden
// worden omgedraaid
if (i <= j) {
swap(list, i, j);
i++;
j--;
}
}
// Hetzelfde de rest van de linkerlijst
if (low < j) {
quicksort(list, low, j);
}
// en voor de rechterlijst
if (high > i) {
quicksort(list, i, high);
}
}
@Override
public String toString() {
String output = "ResultList{" + "results=\n";
for (Student item : studentList) {
output += item + "\n";
}
output += '}';
return output;
}
}
| robertbakker/Sorting_Searching_Assignments | src/nl/hva/robertmark/sortingsearching/practicum1/ResultList.java | 2,047 | // Hetzelfde de rest van de linkerlijst
| line_comment | nl | package nl.hva.robertmark.sortingsearching.practicum1;
import nl.hva.dmci.ict.inf.ads.lib.StdRandom;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* @author Robert
*/
public class ResultList {
private Student[] studentList;
private int pos = 0;
private int totalGroups;
private int N = 0;
private int swaps = 0;
private int compares = 0;
public int getSwaps() {
return swaps;
}
public int getCompares() {
return compares;
}
public ResultList(int s, int totalGroups) {
studentList = new Student[s];
this.totalGroups = totalGroups;
N = studentList.length;
}
public void add(Student item) {
studentList[pos++] = item;
}
public Student[] getList() {
return studentList;
}
public void shuffle() {
StdRandom.shuffle(studentList);
}
public void sort() {
swaps = 0;
compares = 0;
quicksort(studentList, 0, studentList.length - 1);
}
public void median3sort() {
swaps = 0;
compares = 0;
median3sort(studentList, 0, studentList.length - 1);
}
private int median3(Comparable[] list, int a, int b, int c) {
if (list[a].compareTo(list[b]) <= 0) {
compares++;
if (list[b].compareTo(list[c]) <= 0) {
compares++;
return b;
}
else if (list[a].compareTo(list[c]) <= 0) {
compares++;
return c;
}
else
return a;
} else {
if (list[a].compareTo(list[c]) <= 0) {
compares++;
return a;
}
else if (list[b].compareTo(list[c]) <= 0) {
compares++;
return c;
}
else
return b;
}
}
private int median3(Comparable[] list, int left, int right) {
int center = (left + right) / 2;
if(list[center].compareTo(list[left]) < 0)
swap(list,left, center);
if(list[right].compareTo(list[left]) < 0)
swap(list, left, right);
if(list[right].compareTo(list[center]) < 0)
swap(list, center, right);
swap(list, center, right - 1);
return center;
}
private void median3sort(Comparable[] list, int low, int high) {
int i = low, j = high;
int n = high - low + 1;
int mid = (low + high) / 2;
// Bepaal de spil nu door middel van een steekproefgrootte van 3 en de middelste
// daarvan blijkt het meest efficient te zin
int m = median3(list, low, mid, high);
Comparable pivot = list[m];
// swap(list, m, low);
while (i <= j) {
// Wanneer object vanaf links kleiner is dan de spil
// Verschuif naar de volgende in de linkerlijst
while (list[i].compareTo(pivot) < 0) {
i++;
compares++;
}
// Wanneer object vanaf rechts groter is dan de spil
// Verschuif naar de volgende in de rechterlijst
while (list[j].compareTo(pivot) > 0) {
j--;
compares++;
}
// Als er een index van de linkerlijst is gevonden, met een waarde
// die groter is dan de spil, en een index in de rechterlijst met
// een waarde die kleiner is dan de spil, moeten de 2 waarden
// worden omgedraaid
if (i <= j) {
swap(list, i, j);
i++;
j--;
}
}
// Hetzelfde de<SUF>
if (low < j) {
median3sort(list, low, j);
}
// en voor de rechterlijst
if (high > i) {
median3sort(list, i, high);
}
}
private void swap(Comparable[] list, int i, int j) {
swaps++;
Comparable temp = list[i];
list[i] = list[j];
list[j] = temp;
}
private static boolean less(Comparable v, Comparable w) {
int compare = v.compareTo(w);
// Geef een boolean terug a.d.h.v. de vergelijking met de compare, - 1
// in de compare betekend a < b
return compare == 1;
}
private static void exch(Comparable[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
// De quicksort accepteert een lijst van objecten met een comparable
// interface, het beginpunt van links, en het beginpunt van rechts
private void quicksort(Comparable[] list, int low, int high) {
// Neem het middelpunt van de array als spil (draaipunt)
Comparable pivot = list[low + (high - low) / 2];
int i = low; // linkerkant
int j = high; // rechterkant
while (i < j) {
// Wanneer object vanaf links kleiner is dan de spil
// Verschuif naar de volgende in de linkerlijst
while (list[i].compareTo(pivot) < 0) {
i++;
compares++;
}
// Wanneer object vanaf rechts groter is dan de spil
// Verschuif naar de volgende in de rechterlijst
while (list[j].compareTo(pivot) > 0) {
j--;
compares++;
}
// Als er een index van de linkerlijst is gevonden, met een waarde
// die groter is dan de spil, en een index in de rechterlijst met
// een waarde die kleiner is dan de spil, moeten de 2 waarden
// worden omgedraaid
if (i <= j) {
swap(list, i, j);
i++;
j--;
}
}
// Hetzelfde de rest van de linkerlijst
if (low < j) {
quicksort(list, low, j);
}
// en voor de rechterlijst
if (high > i) {
quicksort(list, i, high);
}
}
@Override
public String toString() {
String output = "ResultList{" + "results=\n";
for (Student item : studentList) {
output += item + "\n";
}
output += '}';
return output;
}
}
|
41344_28 | package containing.Road;
import containing.Container.TransportType;
import containing.ParkingSpot.ParkingSpot;
import containing.Platform.Platform;
import static containing.Platform.Platform.Positie.LINKS;
import static containing.Platform.Platform.Positie.ONDER;
import static containing.Platform.Platform.Positie.RECHTS;
import containing.Platform.StoragePlatform;
import containing.Platform.StoragePlatformOrientation;
import containing.Vector3f;
import containing.Vehicle.AGV;
import containing.Vehicle.Crane;
import containing.Vehicle.ExternVehicle;
import containing.Vehicle.Vehicle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Road implements Serializable
{
float roadWidth = AGV.width + AGV.width * 0.25f;
volatile List<Vector3f> track = new ArrayList<>();
public Road(List<Vector3f> roadPoints){ //vaste punten voor main road = 4, voor platform road = 2
for (Vector3f v : roadPoints){
track.add(v);
}
//Collections.sort(track); //links onder links boven rechts boven rechtsonder
//for (Vector3f v : entryPoints){this.createCorrespondingWaypoint(v);}
}
private synchronized Vector3f createCorrespondingWaypoint(Vector3f point){
System.out.println("NR WAYPOINT: " + this.track.size());
System.out.println("CW_BEFORE: " + point);
if (track.size() == 4){ //function only relevant for mainroad/rectangle road
//linksboven
if (point.x <= track.get(0).x){ System.out.println("CW_AFTER0: " + new Vector3f(track.get(0).x, point.y, point.z)); return new Vector3f(track.get(0).x, point.y, point.z); }
//rechtsonder
if (point.x >= track.get(2).x) {System.out.println("CW_AFTER1: " + new Vector3f(track.get(2).x, point.y, point.z)); return new Vector3f(track.get(2).x, point.y, point.z); }
//linksonder
if (point.z >= track.get(1).z){System.out.println("CW_AFTER2: " + new Vector3f(point.x, point.y, track.get(1).z)); return new Vector3f(point.x, point.y, track.get(1).z); }
//was1
if (point.z <= track.get(0).z){System.out.println("CW_AFTER3: " + new Vector3f(point.x, point.y, track.get(0).z)); return new Vector3f(point.x, point.y, track.get(0).z);}
//if (point.z < track.get(1).z){System.out.println("CW_AFTER4: " + new Vector3f(point.x, point.y, track.get(1).z)); return new Vector3f(point.x, point.y, track.get(1).z);}
if (Math.abs(track.get(0).z - point.z) < Math.abs(track.get(1).z - point.z)){System.out.println("CW_AFTER4: return closest z: "+ new Vector3f(point.x,point.y, track.get(0).z)); return new Vector3f(point.x,point.y, track.get(0).z);} //0}
System.out.println("CW_AFTER4: return closest z: "+ new Vector3f(point.x,point.y, track.get(1).z));
return new Vector3f(point.x,point.y, track.get(1).z); //0
}
System.out.println("TRACK1: " + track.get(0));
System.out.println("TRACK2: " + track.get(1));
if (track.get(0).x == track.get(1).x){return new Vector3f(track.get(0).x, point.y, point.z);}
else return new Vector3f(point.x, point.y, track.get(0).z);
}
public static float getPathLength(List<Vector3f> weg){
if (weg.size() > 1){
if (weg.get(0).x != weg.get(1).x){ return Math.abs(weg.get(1).x - weg.get(0).x) + getPathLength(weg.subList(1, weg.size()));}
return Math.abs(weg.get(1).z - weg.get(0).z) + getPathLength(weg.subList(1, weg.size()));
}
else return 0;
}
//allinclusive
public Route getPathAllIn(Vehicle vehicle, ParkingSpot source, ParkingSpot destinationParkingSpot, Platform destinationPlatform, Road mainroad)
{
//source.UnparkVehicle();
System.out.println("In function getPathAllIn");
Route deel1 = vehicle.getCurrentPlatform().getRoad().getPathFromParkingSpotToPlatform(vehicle, source, vehicle.getCurrentPlatform().getExitpoint());
Route deel2 = mainroad.getPathFromExitPointPlatformToEntryPointPlatform(vehicle, vehicle.getCurrentPlatform().getExitpoint(), destinationPlatform, mainroad);
Route deel3 = destinationPlatform.getRoad().getPathFromEntryPointPlatformToParkingSpot(vehicle, destinationParkingSpot);
List<Vector3f> track2 = new ArrayList<>();
for (Vector3f v : deel1.getWeg()) { track2.add(v); }
for (Vector3f v : deel2.getWeg()) { track2.add(v); }
for (Vector3f v : deel3.getWeg()) { track2.add(v); }
if (vehicle.getID() == 201 || vehicle.getID() == 103)
{
System.out.println("----------------------");
System.out.println("Route nr: " + vehicle.routecounter);
for (Vector3f v : deel1.getWeg() ) {
System.out.println("Deel 1: " + v);}
for (Vector3f v : deel2.getWeg() ) {
System.out.println("Deel 2: " + v);}
for (Vector3f v : deel3.getWeg() ) {
System.out.println("Deel 3: " + v);}
System.out.println("----------------------");
}
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = destinationPlatform;
route.destinationParkingSpot = destinationParkingSpot;
if (destinationParkingSpot == null){
System.out.println("NULL");}
return route;
}
public Route getPathAllInVector(Vehicle vehicle, ParkingSpot source, Vector3f destinationVector, Platform destinationPlatform, Road mainroad)
{
System.out.println("In function getPathAllInVector");
Route deel1 = vehicle.getCurrentPlatform().getRoad().getPathFromParkingSpotToPlatform(vehicle, source, vehicle.getCurrentPlatform().getExitpoint());
Route deel2 = mainroad.getPathFromExitPointPlatformToEntryPointPlatform(vehicle, vehicle.getCurrentPlatform().getExitpoint(), destinationPlatform, mainroad);
Route deel3 = destinationPlatform.getRoad().getPathFromEntryPointPlatformToVector(vehicle, destinationVector);
List<Vector3f> track2 = new ArrayList<>();
for (Vector3f v : deel1.getWeg()) { track2.add(v);}
for (Vector3f v : deel2.getWeg()) { track2.add(v);}
for (Vector3f v : deel3.getWeg()) { track2.add(v);}
if (vehicle.getID() == 201 || vehicle.getID() == 103)
{
System.out.println("----------------------");
System.out.println("Route nr: " + vehicle.routecounter);
for (Vector3f v : deel1.getWeg() ) {
System.out.println("Deel 1: " + v);}
for (Vector3f v : deel2.getWeg() ) {
System.out.println("Deel 2: " + v);}
for (Vector3f v : deel3.getWeg() ) {
System.out.println("Deel 3: " + v);}
System.out.println("----------------------");
}
return new Route(track2, getPathLength(track2));
}
//van parkeerplaats op platform naar einde platform
public Route getPathFromParkingSpotToPlatform(Vehicle vehicle, ParkingSpot source, Vector3f exitwayPlatform)
{
System.out.println("In function getPathFromParkingSpotToPlatform");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(exitwayPlatform));
track2.add(exitwayPlatform);
try
{
if(vehicle.getCurrentPlatform() instanceof StoragePlatform || vehicle.getCurrentPlatform() instanceof StoragePlatformOrientation)
source.UnparkVehicle();
}
catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
//source.UnparkVehicle();
vehicle.setPosition(exitwayPlatform);
Route route = new Route(track2, getPathLength(track2));
route.destinationParkingSpot = null;
route.destinationPlatform = null;
return route;
}
public Route moveToContainer(ExternVehicle ev, int column, Crane crane)
{
System.out.println("In function moveToContainer");
//System.out.println("column : " + column);
List<Vector3f> route = new ArrayList<>();
route.add(crane.getPosition());
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
//System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (ev.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, crane.getPosition().y, crane.getPosition().z);
route.add(haha); //??
//System.out.println("route x: " + haha.toString());
break;
case Z:
if(ev.getCurrentPlatform().getTransportType() == TransportType.Train){
// hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f + 0.70f);
route.add(hihi); //??
//System.out.println("route z: " + hihi.toString());
}
else if(ev.getCurrentPlatform().getTransportType() == TransportType.Barge){
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column+1.5f +1f);
route.add(hihi); //??
}
break;
//caseY?
}
return new Route(route, getPathLength(route));
}
//van uitgang platform naar ingang andere platform
public Route getPathFromExitPointPlatformToEntryPointPlatform(Vehicle vehicle, Vector3f sourcePlatformExitPoint,Platform destination, Road mainroad)
{
System.out.println("In function getPathFromExitPointPlatformToEntryPointPlatform");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(sourcePlatformExitPoint);
//System.out.println("sourcePlatformExitPoint: " + sourcePlatformExitPoint);
track2.add(this.createCorrespondingWaypoint(sourcePlatformExitPoint));
//System.out.println("sourcePlatformExitPointCW: " + this.createCorrespondingWaypoint(sourcePlatformExitPoint));
track2.add(this.createCorrespondingWaypoint(destination.getEntrypoint()));
//System.out.println("destinationEntryPointCW: " + this.createCorrespondingWaypoint(destination.getEntrypoint()));
track2.add(destination.getEntrypoint());
//System.out.println("destinationEntryPoint: " + destination.getEntrypoint());
if (vehicle.getID() == 201 && vehicle.routecounter == 3)
{
System.out.println("Before deel 2");
for (Vector3f v : track2)
{
System.out.println("Deel 2 V: " + v);
}
}
track2 = this.setPathCorrectOrder(track2, vehicle.getCurrentPlatform(), destination, mainroad);
if (vehicle.getID() == 201 && vehicle.routecounter == 3)
{
System.out.println("After deel 2");
for (Vector3f v : track2)
{
System.out.println("Deel 2 V: " + v);
}
}
vehicle.setCurrentPlatform(destination);
vehicle.setPosition(destination.getEntrypoint());
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = destination;
route.destinationParkingSpot = null;
return route;
}
//van ingang platform naar parkeerplaats
public Route getPathFromEntryPointPlatformToParkingSpot(Vehicle vehicle, ParkingSpot ps)
{
System.out.println("In function getPathFromEntryPointPlatformToParkingSpot");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(this.createCorrespondingWaypoint(ps.getPosition())));
track2.add(ps.getPosition());
/*
try
{
ps.ParkVehicle(vehicle);
vehicle.setPosition(ps.getPosition());
}
catch(Exception e){
Settings.messageLog.AddMessage(e.getMessage());
}
*/
return new Route(track2, getPathLength(track2));
}
public Route getPathToParkingsSpot(Vehicle vehicle, ParkingSpot ps)
{
System.out.println("In function getPathToParkingsSpot");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(ps.getPosition()));
//track2.add(ps.getPosition());
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = null;
route.destinationParkingSpot = ps;
return route;
}
public Route getPathFromEntryPointPlatformToVector(Vehicle vehicle, Vector3f destinationVector)
{
System.out.println("In function getPathFromEntryPointPlatformToVector");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(this.createCorrespondingWaypoint(destinationVector)));
track2.add(destinationVector);
vehicle.setPosition(destinationVector);
return new Route(track2, getPathLength(track2));
}
public Route getPathExternVehicleExit(ParkingSpot ps, Vector3f v )
{
System.out.println("In function getPathExternVehicleExit");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(ps.getPosition());
track2.add(v);
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = null;
ps.UnparkVehicle();
return route;
}
public Route getPathExternVehicleEntry(ExternVehicle ev, ParkingSpot ps )
{
System.out.println("In function getPathExternVehicleEntry");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(ev.getPosition());
track2.add(ps.getPosition());
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = ps;
return route;
}
public Route getPathMoveContainer(ExternVehicle ev, int column, Crane crane) {
System.out.println("In function getPathMoveContainer");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(crane.getPosition());
//track2.add(ev.getPosition());
//System.out.println("column : " + column);
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
//System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (crane.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, crane.getPosition().y, crane.getPosition().z);
track2.add(haha); //??
break;
case Z:
// hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f);
track2.add(hihi); //??
break;
//caseY?
}
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = null;
return route;
}
/*
* Calculates distance from current platform of agv to desination platform.
* There are two possible roads for agv, the function selects the road with minimum distance (=shortest).
* The shortest way is converted into a Route.
*/
/*
public Route calculateShortestPath(Vehicle vehicle, Vector3f destination){ //only for mainroad
List<Vector3f> outsidetrack = new ArrayList<Vector3f>(this.track);
outsidetrack.add(destination);
Vector3f positionvehicle = this.createCorrespondingWaypoint(vehicle.getCurrentPlatform().getExitpoint());
outsidetrack.add(positionvehicle);
Collections.sort(outsidetrack);
List<Vector3f> insidetrack = new ArrayList<>(outsidetrack);
Collections.reverse(outsidetrack);
insidetrack = this.setPathCorrectOrder(insidetrack, positionvehicle, destination);
outsidetrack = this.setPathCorrectOrder(outsidetrack,positionvehicle, destination);
float length_insidetrack = getPathLength(insidetrack);
float length_outsidetrack = getPathLength(outsidetrack);
if (length_insidetrack < length_outsidetrack){return new Route(insidetrack, length_insidetrack);}
else return new Route(outsidetrack, length_outsidetrack);
}*/
public synchronized List<Vector3f> setPathCorrectOrder(List<Vector3f> path, Platform source, Platform destination, Road mainroad){
//path size altijd 4
System.out.println("In function setPathCorrectOrder");
List<Vector3f> correctPath = new ArrayList<>();
correctPath.add(path.get(0)); //exitpoint
correctPath.add(path.get(1)); //exitpoint op weg
System.out.println("POSITIES: " + source.positie); //=rechts
System.out.println("POSITIED: " + destination.positie); //=links
//if (destination.positie == Platform.Positie.)
boolean right = true;
//bepalen aan hand van platform of rechts of links: nu altijd rechtsom
if (source instanceof StoragePlatform)
{
//System.out.println("RIGHT IS THE GOOD SIDE");
right = false; //
}
//if (typeOrInterface.isInstance(someObject);)
//rechtsom
if (right)
{
switch(source.positie)
{
case RECHTS:
if (destination.positie == Platform.Positie.LINKS)
{ //rechtsonder linksonder
correctPath.add(mainroad.track.get(2));
correctPath.add(mainroad.track.get(1));
break;
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
break;
case LINKS:
if (destination.positie == Platform.Positie.RECHTS)
{
System.out.println("Not in else");
correctPath.add(mainroad.track.get(1)); //linksboven
System.out.println("0: "+ mainroad.track.get(1));
System.out.println("2: "+mainroad.track.get(2));
correctPath.add(mainroad.track.get(2)); //rechtsboven
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(0)); //linksboven
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
break;
case ONDER:
if (destination.positie == Platform.Positie.RECHTS)
{
//linksonder
//linksboven
//rechtsboven
correctPath.add(mainroad.track.get(1));
correctPath.add(mainroad.track.get(0));
correctPath.add(mainroad.track.get(3));
}
if (destination.positie == Platform.Positie.LINKS)
{
correctPath.add(mainroad.track.get(1)); //linksonder
}
break;
}
}
//linksom <=
else //linksom
{//moet nog
//correctPath.add(path.get(3));
//correctPath.add(path.get(2));
switch(source.positie)
{
case RECHTS:
if (destination.positie == Platform.Positie.LINKS)
{ //rechtsboven
//linksboven
correctPath.add(mainroad.track.get(3));
correctPath.add(mainroad.track.get(0));
break;
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(0)); //linksboven
correctPath.add(mainroad.track.get(1)); //linksonder
break;
}
break;
case LINKS:
if (destination.positie == Platform.Positie.RECHTS)
{
System.out.println("In else");
//linksonder
//rechtsonder
System.out.println("1: " + mainroad.track.get(1));
System.out.println("2: " + mainroad.track.get(2));
correctPath.add(mainroad.track.get(1));
correctPath.add(mainroad.track.get(2));
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(1));
}
break;
case ONDER:
if (destination.positie == Platform.Positie.RECHTS)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
if (destination.positie == Platform.Positie.LINKS)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(0)); //linksboven
}
break;
}
}
correctPath.add(path.get(2));
correctPath.add(path.get(3));
for (Vector3f v : path)
{
//System.out.println("VectorPath: " + v);
}
return correctPath;
}
}
| robertdj20/Containing | Containing/src/containing/Road/Road.java | 7,180 | //bepalen aan hand van platform of rechts of links: nu altijd rechtsom | line_comment | nl | package containing.Road;
import containing.Container.TransportType;
import containing.ParkingSpot.ParkingSpot;
import containing.Platform.Platform;
import static containing.Platform.Platform.Positie.LINKS;
import static containing.Platform.Platform.Positie.ONDER;
import static containing.Platform.Platform.Positie.RECHTS;
import containing.Platform.StoragePlatform;
import containing.Platform.StoragePlatformOrientation;
import containing.Vector3f;
import containing.Vehicle.AGV;
import containing.Vehicle.Crane;
import containing.Vehicle.ExternVehicle;
import containing.Vehicle.Vehicle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Road implements Serializable
{
float roadWidth = AGV.width + AGV.width * 0.25f;
volatile List<Vector3f> track = new ArrayList<>();
public Road(List<Vector3f> roadPoints){ //vaste punten voor main road = 4, voor platform road = 2
for (Vector3f v : roadPoints){
track.add(v);
}
//Collections.sort(track); //links onder links boven rechts boven rechtsonder
//for (Vector3f v : entryPoints){this.createCorrespondingWaypoint(v);}
}
private synchronized Vector3f createCorrespondingWaypoint(Vector3f point){
System.out.println("NR WAYPOINT: " + this.track.size());
System.out.println("CW_BEFORE: " + point);
if (track.size() == 4){ //function only relevant for mainroad/rectangle road
//linksboven
if (point.x <= track.get(0).x){ System.out.println("CW_AFTER0: " + new Vector3f(track.get(0).x, point.y, point.z)); return new Vector3f(track.get(0).x, point.y, point.z); }
//rechtsonder
if (point.x >= track.get(2).x) {System.out.println("CW_AFTER1: " + new Vector3f(track.get(2).x, point.y, point.z)); return new Vector3f(track.get(2).x, point.y, point.z); }
//linksonder
if (point.z >= track.get(1).z){System.out.println("CW_AFTER2: " + new Vector3f(point.x, point.y, track.get(1).z)); return new Vector3f(point.x, point.y, track.get(1).z); }
//was1
if (point.z <= track.get(0).z){System.out.println("CW_AFTER3: " + new Vector3f(point.x, point.y, track.get(0).z)); return new Vector3f(point.x, point.y, track.get(0).z);}
//if (point.z < track.get(1).z){System.out.println("CW_AFTER4: " + new Vector3f(point.x, point.y, track.get(1).z)); return new Vector3f(point.x, point.y, track.get(1).z);}
if (Math.abs(track.get(0).z - point.z) < Math.abs(track.get(1).z - point.z)){System.out.println("CW_AFTER4: return closest z: "+ new Vector3f(point.x,point.y, track.get(0).z)); return new Vector3f(point.x,point.y, track.get(0).z);} //0}
System.out.println("CW_AFTER4: return closest z: "+ new Vector3f(point.x,point.y, track.get(1).z));
return new Vector3f(point.x,point.y, track.get(1).z); //0
}
System.out.println("TRACK1: " + track.get(0));
System.out.println("TRACK2: " + track.get(1));
if (track.get(0).x == track.get(1).x){return new Vector3f(track.get(0).x, point.y, point.z);}
else return new Vector3f(point.x, point.y, track.get(0).z);
}
public static float getPathLength(List<Vector3f> weg){
if (weg.size() > 1){
if (weg.get(0).x != weg.get(1).x){ return Math.abs(weg.get(1).x - weg.get(0).x) + getPathLength(weg.subList(1, weg.size()));}
return Math.abs(weg.get(1).z - weg.get(0).z) + getPathLength(weg.subList(1, weg.size()));
}
else return 0;
}
//allinclusive
public Route getPathAllIn(Vehicle vehicle, ParkingSpot source, ParkingSpot destinationParkingSpot, Platform destinationPlatform, Road mainroad)
{
//source.UnparkVehicle();
System.out.println("In function getPathAllIn");
Route deel1 = vehicle.getCurrentPlatform().getRoad().getPathFromParkingSpotToPlatform(vehicle, source, vehicle.getCurrentPlatform().getExitpoint());
Route deel2 = mainroad.getPathFromExitPointPlatformToEntryPointPlatform(vehicle, vehicle.getCurrentPlatform().getExitpoint(), destinationPlatform, mainroad);
Route deel3 = destinationPlatform.getRoad().getPathFromEntryPointPlatformToParkingSpot(vehicle, destinationParkingSpot);
List<Vector3f> track2 = new ArrayList<>();
for (Vector3f v : deel1.getWeg()) { track2.add(v); }
for (Vector3f v : deel2.getWeg()) { track2.add(v); }
for (Vector3f v : deel3.getWeg()) { track2.add(v); }
if (vehicle.getID() == 201 || vehicle.getID() == 103)
{
System.out.println("----------------------");
System.out.println("Route nr: " + vehicle.routecounter);
for (Vector3f v : deel1.getWeg() ) {
System.out.println("Deel 1: " + v);}
for (Vector3f v : deel2.getWeg() ) {
System.out.println("Deel 2: " + v);}
for (Vector3f v : deel3.getWeg() ) {
System.out.println("Deel 3: " + v);}
System.out.println("----------------------");
}
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = destinationPlatform;
route.destinationParkingSpot = destinationParkingSpot;
if (destinationParkingSpot == null){
System.out.println("NULL");}
return route;
}
public Route getPathAllInVector(Vehicle vehicle, ParkingSpot source, Vector3f destinationVector, Platform destinationPlatform, Road mainroad)
{
System.out.println("In function getPathAllInVector");
Route deel1 = vehicle.getCurrentPlatform().getRoad().getPathFromParkingSpotToPlatform(vehicle, source, vehicle.getCurrentPlatform().getExitpoint());
Route deel2 = mainroad.getPathFromExitPointPlatformToEntryPointPlatform(vehicle, vehicle.getCurrentPlatform().getExitpoint(), destinationPlatform, mainroad);
Route deel3 = destinationPlatform.getRoad().getPathFromEntryPointPlatformToVector(vehicle, destinationVector);
List<Vector3f> track2 = new ArrayList<>();
for (Vector3f v : deel1.getWeg()) { track2.add(v);}
for (Vector3f v : deel2.getWeg()) { track2.add(v);}
for (Vector3f v : deel3.getWeg()) { track2.add(v);}
if (vehicle.getID() == 201 || vehicle.getID() == 103)
{
System.out.println("----------------------");
System.out.println("Route nr: " + vehicle.routecounter);
for (Vector3f v : deel1.getWeg() ) {
System.out.println("Deel 1: " + v);}
for (Vector3f v : deel2.getWeg() ) {
System.out.println("Deel 2: " + v);}
for (Vector3f v : deel3.getWeg() ) {
System.out.println("Deel 3: " + v);}
System.out.println("----------------------");
}
return new Route(track2, getPathLength(track2));
}
//van parkeerplaats op platform naar einde platform
public Route getPathFromParkingSpotToPlatform(Vehicle vehicle, ParkingSpot source, Vector3f exitwayPlatform)
{
System.out.println("In function getPathFromParkingSpotToPlatform");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(exitwayPlatform));
track2.add(exitwayPlatform);
try
{
if(vehicle.getCurrentPlatform() instanceof StoragePlatform || vehicle.getCurrentPlatform() instanceof StoragePlatformOrientation)
source.UnparkVehicle();
}
catch(Exception e)
{
System.out.println("Error: " + e.getMessage());
}
//source.UnparkVehicle();
vehicle.setPosition(exitwayPlatform);
Route route = new Route(track2, getPathLength(track2));
route.destinationParkingSpot = null;
route.destinationPlatform = null;
return route;
}
public Route moveToContainer(ExternVehicle ev, int column, Crane crane)
{
System.out.println("In function moveToContainer");
//System.out.println("column : " + column);
List<Vector3f> route = new ArrayList<>();
route.add(crane.getPosition());
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
//System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (ev.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, crane.getPosition().y, crane.getPosition().z);
route.add(haha); //??
//System.out.println("route x: " + haha.toString());
break;
case Z:
if(ev.getCurrentPlatform().getTransportType() == TransportType.Train){
// hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f + 0.70f);
route.add(hihi); //??
//System.out.println("route z: " + hihi.toString());
}
else if(ev.getCurrentPlatform().getTransportType() == TransportType.Barge){
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column+1.5f +1f);
route.add(hihi); //??
}
break;
//caseY?
}
return new Route(route, getPathLength(route));
}
//van uitgang platform naar ingang andere platform
public Route getPathFromExitPointPlatformToEntryPointPlatform(Vehicle vehicle, Vector3f sourcePlatformExitPoint,Platform destination, Road mainroad)
{
System.out.println("In function getPathFromExitPointPlatformToEntryPointPlatform");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(sourcePlatformExitPoint);
//System.out.println("sourcePlatformExitPoint: " + sourcePlatformExitPoint);
track2.add(this.createCorrespondingWaypoint(sourcePlatformExitPoint));
//System.out.println("sourcePlatformExitPointCW: " + this.createCorrespondingWaypoint(sourcePlatformExitPoint));
track2.add(this.createCorrespondingWaypoint(destination.getEntrypoint()));
//System.out.println("destinationEntryPointCW: " + this.createCorrespondingWaypoint(destination.getEntrypoint()));
track2.add(destination.getEntrypoint());
//System.out.println("destinationEntryPoint: " + destination.getEntrypoint());
if (vehicle.getID() == 201 && vehicle.routecounter == 3)
{
System.out.println("Before deel 2");
for (Vector3f v : track2)
{
System.out.println("Deel 2 V: " + v);
}
}
track2 = this.setPathCorrectOrder(track2, vehicle.getCurrentPlatform(), destination, mainroad);
if (vehicle.getID() == 201 && vehicle.routecounter == 3)
{
System.out.println("After deel 2");
for (Vector3f v : track2)
{
System.out.println("Deel 2 V: " + v);
}
}
vehicle.setCurrentPlatform(destination);
vehicle.setPosition(destination.getEntrypoint());
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = destination;
route.destinationParkingSpot = null;
return route;
}
//van ingang platform naar parkeerplaats
public Route getPathFromEntryPointPlatformToParkingSpot(Vehicle vehicle, ParkingSpot ps)
{
System.out.println("In function getPathFromEntryPointPlatformToParkingSpot");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(this.createCorrespondingWaypoint(ps.getPosition())));
track2.add(ps.getPosition());
/*
try
{
ps.ParkVehicle(vehicle);
vehicle.setPosition(ps.getPosition());
}
catch(Exception e){
Settings.messageLog.AddMessage(e.getMessage());
}
*/
return new Route(track2, getPathLength(track2));
}
public Route getPathToParkingsSpot(Vehicle vehicle, ParkingSpot ps)
{
System.out.println("In function getPathToParkingsSpot");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(ps.getPosition()));
//track2.add(ps.getPosition());
Route route = new Route(track2, getPathLength(track2));
route.destinationPlatform = null;
route.destinationParkingSpot = ps;
return route;
}
public Route getPathFromEntryPointPlatformToVector(Vehicle vehicle, Vector3f destinationVector)
{
System.out.println("In function getPathFromEntryPointPlatformToVector");
List<Vector3f> track2 = new ArrayList<Vector3f>();//this.track
track2.add(vehicle.getPosition());
track2.add(this.createCorrespondingWaypoint(vehicle.getPosition()));
track2.add(this.createCorrespondingWaypoint(this.createCorrespondingWaypoint(destinationVector)));
track2.add(destinationVector);
vehicle.setPosition(destinationVector);
return new Route(track2, getPathLength(track2));
}
public Route getPathExternVehicleExit(ParkingSpot ps, Vector3f v )
{
System.out.println("In function getPathExternVehicleExit");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(ps.getPosition());
track2.add(v);
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = null;
ps.UnparkVehicle();
return route;
}
public Route getPathExternVehicleEntry(ExternVehicle ev, ParkingSpot ps )
{
System.out.println("In function getPathExternVehicleEntry");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(ev.getPosition());
track2.add(ps.getPosition());
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = ps;
return route;
}
public Route getPathMoveContainer(ExternVehicle ev, int column, Crane crane) {
System.out.println("In function getPathMoveContainer");
List<Vector3f> track2 = new ArrayList<Vector3f>();
track2.add(crane.getPosition());
//track2.add(ev.getPosition());
//System.out.println("column : " + column);
Vector3f container = ev.getGrid()[column][0][0].getArrivalPosition();
//System.out.println("ev.getPosition = " + ev.getPosition().toString());
switch (crane.getCurrentPlatform().getAxis())
{
case X:
Vector3f haha = new Vector3f(ev.getPosition().x - column*1.5f, crane.getPosition().y, crane.getPosition().z);
track2.add(haha); //??
break;
case Z:
// hardcoded voor de trein nu ;( wagon is 1.5f en trein zelf ook
Vector3f hihi = new Vector3f(crane.getPosition().x, crane.getPosition().y, ev.getPosition().z - column*1.5f - 1.5f);
track2.add(hihi); //??
break;
//caseY?
}
float length = this.getPathLength(track2);
Route route = new Route(track2, length);
route.destinationPlatform = null;
route.destinationParkingSpot = null;
return route;
}
/*
* Calculates distance from current platform of agv to desination platform.
* There are two possible roads for agv, the function selects the road with minimum distance (=shortest).
* The shortest way is converted into a Route.
*/
/*
public Route calculateShortestPath(Vehicle vehicle, Vector3f destination){ //only for mainroad
List<Vector3f> outsidetrack = new ArrayList<Vector3f>(this.track);
outsidetrack.add(destination);
Vector3f positionvehicle = this.createCorrespondingWaypoint(vehicle.getCurrentPlatform().getExitpoint());
outsidetrack.add(positionvehicle);
Collections.sort(outsidetrack);
List<Vector3f> insidetrack = new ArrayList<>(outsidetrack);
Collections.reverse(outsidetrack);
insidetrack = this.setPathCorrectOrder(insidetrack, positionvehicle, destination);
outsidetrack = this.setPathCorrectOrder(outsidetrack,positionvehicle, destination);
float length_insidetrack = getPathLength(insidetrack);
float length_outsidetrack = getPathLength(outsidetrack);
if (length_insidetrack < length_outsidetrack){return new Route(insidetrack, length_insidetrack);}
else return new Route(outsidetrack, length_outsidetrack);
}*/
public synchronized List<Vector3f> setPathCorrectOrder(List<Vector3f> path, Platform source, Platform destination, Road mainroad){
//path size altijd 4
System.out.println("In function setPathCorrectOrder");
List<Vector3f> correctPath = new ArrayList<>();
correctPath.add(path.get(0)); //exitpoint
correctPath.add(path.get(1)); //exitpoint op weg
System.out.println("POSITIES: " + source.positie); //=rechts
System.out.println("POSITIED: " + destination.positie); //=links
//if (destination.positie == Platform.Positie.)
boolean right = true;
//bepalen aan<SUF>
if (source instanceof StoragePlatform)
{
//System.out.println("RIGHT IS THE GOOD SIDE");
right = false; //
}
//if (typeOrInterface.isInstance(someObject);)
//rechtsom
if (right)
{
switch(source.positie)
{
case RECHTS:
if (destination.positie == Platform.Positie.LINKS)
{ //rechtsonder linksonder
correctPath.add(mainroad.track.get(2));
correctPath.add(mainroad.track.get(1));
break;
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
break;
case LINKS:
if (destination.positie == Platform.Positie.RECHTS)
{
System.out.println("Not in else");
correctPath.add(mainroad.track.get(1)); //linksboven
System.out.println("0: "+ mainroad.track.get(1));
System.out.println("2: "+mainroad.track.get(2));
correctPath.add(mainroad.track.get(2)); //rechtsboven
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(0)); //linksboven
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
break;
case ONDER:
if (destination.positie == Platform.Positie.RECHTS)
{
//linksonder
//linksboven
//rechtsboven
correctPath.add(mainroad.track.get(1));
correctPath.add(mainroad.track.get(0));
correctPath.add(mainroad.track.get(3));
}
if (destination.positie == Platform.Positie.LINKS)
{
correctPath.add(mainroad.track.get(1)); //linksonder
}
break;
}
}
//linksom <=
else //linksom
{//moet nog
//correctPath.add(path.get(3));
//correctPath.add(path.get(2));
switch(source.positie)
{
case RECHTS:
if (destination.positie == Platform.Positie.LINKS)
{ //rechtsboven
//linksboven
correctPath.add(mainroad.track.get(3));
correctPath.add(mainroad.track.get(0));
break;
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(0)); //linksboven
correctPath.add(mainroad.track.get(1)); //linksonder
break;
}
break;
case LINKS:
if (destination.positie == Platform.Positie.RECHTS)
{
System.out.println("In else");
//linksonder
//rechtsonder
System.out.println("1: " + mainroad.track.get(1));
System.out.println("2: " + mainroad.track.get(2));
correctPath.add(mainroad.track.get(1));
correctPath.add(mainroad.track.get(2));
}
if (destination.positie == Platform.Positie.ONDER)
{
correctPath.add(mainroad.track.get(1));
}
break;
case ONDER:
if (destination.positie == Platform.Positie.RECHTS)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
}
if (destination.positie == Platform.Positie.LINKS)
{
correctPath.add(mainroad.track.get(2)); //rechtsonder
correctPath.add(mainroad.track.get(3)); //rechtsboven
correctPath.add(mainroad.track.get(0)); //linksboven
}
break;
}
}
correctPath.add(path.get(2));
correctPath.add(path.get(3));
for (Vector3f v : path)
{
//System.out.println("VectorPath: " + v);
}
return correctPath;
}
}
|
106633_51 | /*
* This file is part of Mockey, a tool for testing application
* interactions over HTTP, with a focus on testing web services,
* specifically web applications that consume XML, JSON, and HTML.
*
* Copyright (C) 2009-2010 Authors:
*
* chad.lafontaine (chad.lafontaine AT gmail DOT com)
* neil.cronin (neil AT rackle DOT com)
* lorin.kobashigawa (lkb AT kgawa DOT com)
* rob.meyer (rob AT bigdis DOT 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package com.mockey.model;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;
import com.mockey.ClientExecuteProxy;
import com.mockey.ClientExecuteProxyException;
import com.mockey.OrderedMap;
import com.mockey.storage.IMockeyStorage;
import com.mockey.storage.StorageRegistry;
import com.mockey.ui.Util;
/**
* A Service is a remote url that can be called.
*
* @author chad.lafontaine
*
*/
public class Service extends StatusCheck implements PersistableItem, ExecutableService {
public final static int SERVICE_RESPONSE_TYPE_PROXY = 0;
public final static int SERVICE_RESPONSE_TYPE_STATIC_SCENARIO = 1;
public final static int SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO = 2;
private Long id;
private String serviceName;
private String description;
private Boolean transientState = new Boolean(false);
private Long defaultScenarioId;
private int defaultRealUrlIndex = 0;
private Long errorScenarioId;
private int hangTime = 0;
private String requestInspectorName;
private OrderedMap<Scenario> scenarios = new OrderedMap<Scenario>();
private int serviceResponseType = SERVICE_RESPONSE_TYPE_PROXY;
private String httpMethod = "GET";
private String url = "";
private List<FulfilledClientRequest> fulfilledRequests;
private List<Url> realServiceUrlList = new ArrayList<Url>();
private boolean allowRedirectFollow = true;
private static Log logger = LogFactory.getLog(Service.class);
private static IMockeyStorage store = StorageRegistry.MockeyStorage;
public List<FulfilledClientRequest> getFulfilledRequests() {
return fulfilledRequests;
}
public void setFulfilledRequests(List<FulfilledClientRequest> transactions) {
this.fulfilledRequests = transactions;
}
// default constructor for xml.
// DO NOT REMOVE. DO NOT CALL.
public Service() {
this.setServiceName("");
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public Long getDefaultScenarioId() {
return this.defaultScenarioId;
}
/**
*
* @return null if no default scenario defined, otherwise, returns name
*/
public String getDefaultScenarioName(){
Scenario s = this.getScenario(this.defaultScenarioId);
if(s!=null){
return s.getScenarioName();
}else {
return null;
}
}
public void setDefaultScenarioId(Long did) {
this.defaultScenarioId = did;
}
/**
* Finds a service scenario with matching name. If a match is found, then
* its ID is set as the default scenario id. If no match is found, then no
* change. Name matching is case insensitive, and leading and ending
* whitespace is trimmed.
*
* @param scenarioName
*/
public void setDefaultScenarioByName(String scenarioName) {
if (scenarioName != null) {
for (Scenario scenario : this.scenarios.getOrderedList()) {
if (scenarioName.trim().equalsIgnoreCase((scenario.getScenarioName().trim()))) {
this.setDefaultScenarioId(scenario.getId());
break;
}
}
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String name) {
this.serviceName = name;
}
public int getHangTime() {
return hangTime;
}
public void setHangTime(int hangTime) {
this.hangTime = hangTime;
}
public List<Scenario> getScenarios() {
return Util.orderAlphabeticallyByScenarioName(scenarios.getOrderedList());
}
public Scenario getScenario(Long scenarioId) {
return (Scenario) scenarios.get(scenarioId);
}
public void deleteScenario(Long scenarioId) {
this.scenarios.remove(scenarioId);
}
public Scenario saveOrUpdateScenario(Scenario scenario) {
scenario.setServiceId(this.id);
return (Scenario) this.scenarios.save(scenario);
}
/**
* DO NOT REMOVE. This is needed by XML reader and has a reference to the
* method signature via reflection. Thank Digester.
*
* @param realServiceUrl
* @deprecated - this method will call
* <code>saveOrUpdateRealServiceUrl(Url)</code>
* @see #saveOrUpdateRealServiceUrl(Url)
*/
public void setRealServiceUrlByString(String realServiceUrl) {
this.saveOrUpdateRealServiceUrl(new Url(realServiceUrl));
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Service name:").append(this.getServiceName()).append("\n");
sb.append("Real URL(s):\n");
if (this.realServiceUrlList != null && !this.realServiceUrlList.isEmpty()) {
Iterator<Url> iter = this.realServiceUrlList.iterator();
while (iter.hasNext()) {
sb.append(iter.next() + "\n");
}
} else {
sb.append("(no real urls defined for this service)\n");
}
sb.append("Default scenario ID:").append(this.getDefaultScenarioId()).append("\n");
sb.append("Hang time:");
sb.append(this.getHangTime());
sb.append("\n");
return sb.toString();
}
public void setId(Long id) {
this.id = id;
// Recursively set this ID to child Scenarios, if any exist.
for (Scenario scenario : getScenarios()) {
scenario.setServiceId(this.id);
this.saveOrUpdateScenario(scenario);
}
}
public Long getId() {
return id;
}
/**
*
* @deprecated
* @see #getRealServiceUrls()
*/
public String getRealServiceUrl() {
return "[DEPRECATED]";
}
/**
*
* @param serviceResponseType
* - 0 (proxy), 1 (static), or 2 (dynamic). Any other value will
* default to PROXY.
*/
public void setServiceResponseType(int serviceResponseType) {
if (serviceResponseType == 1 || serviceResponseType == 0 || serviceResponseType == 2) {
this.serviceResponseType = serviceResponseType;
} else {
this.serviceResponseType = SERVICE_RESPONSE_TYPE_PROXY;
}
validateDefaultScenarioId();
}
// HELPER method - let's validate the 'defaultScenarioId'. If
// defaultScenarioId doesn't equal any of the scenario IDs, then
// auto-set the defaultID to the 'first' scenario
private void validateDefaultScenarioId() {
boolean valid = false;
List<Scenario> orderedList = this.scenarios.getOrderedList();
for(Scenario s: orderedList){
if(s.getId().equals(this.getDefaultScenarioId()) ) {
valid = true;
break;
}
}
if(!valid){
if(this.scenarios.getOrderedList().size() > 0){
this.setDefaultScenarioId(orderedList.get(0).getId());
}else {
// Reset
this.setDefaultScenarioId(null);
}
}
}
/**
* Takes 'proxy', 'static', or 'dynamic' arguments and translates them to
* appropriate 'int' values and then calls
* <code>setServiceResponseType</code>
*
* @see #setServiceResponseType(int)
*/
public void setServiceResponseTypeByString(String arg) {
if (arg != null) {
if ("proxy".trim().equalsIgnoreCase(arg.trim()) || "0".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_PROXY);
} else if ("static".trim().equalsIgnoreCase(arg.trim()) || "1".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO);
} else if ("dynamic".trim().equalsIgnoreCase(arg.trim()) || "2".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO);
}
}
}
public int getServiceResponseType() {
// If no scenarios, then proxy is automatically on.
if (this.getScenarios().size() == 0) {
return SERVICE_RESPONSE_TYPE_PROXY;
} else {
return serviceResponseType;
}
}
public String getServiceResponseTypeAsString(){
int x = getServiceResponseType();
if(x == Service.SERVICE_RESPONSE_TYPE_PROXY){
return "proxy";
}else if(x == Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO){
return "static";
}else if(x == Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO){
return "dynamic";
}else {
return "";
}
}
public void setErrorScenarioId(Long errorScenarioId) {
this.errorScenarioId = errorScenarioId;
}
public Long getErrorScenarioId() {
return errorScenarioId;
}
public Scenario getErrorScenario() {
// FIND SERVICE ERROR, IF EXIST.
for (Scenario scenario : this.getScenarios()) {
if (scenario.getId().equals(this.getErrorScenarioId())) {
return scenario;
}
}
// No service error defined, therefore, let's use the universal
// error.
return StorageRegistry.MockeyStorage.getUniversalErrorScenario();
}
public Boolean isReferencedInAServicePlan() {
Boolean isReferenced = false;
for (ServicePlan plan : StorageRegistry.MockeyStorage.getServicePlans()) {
for (PlanItem planItem : plan.getPlanItemList()) {
if (planItem.getServiceId().equals(this.getId())) {
isReferenced = true;
break;
}
}
}
return isReferenced;
}
/**
* The core method to execute the request as either a Proxy, Dynamic, or
* Static Scenario.
*/
public ResponseFromService execute(RequestFromClient request, Url realServiceUrl) {
this.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis()));
ResponseFromService response = null;
if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_PROXY) {
response = proxyTheRequest(request, realServiceUrl);
} else if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO) {
response = executeDynamicScenario(request, realServiceUrl);
} else if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO) {
response = executeStaticScenario(realServiceUrl);
}
return response;
}
private ResponseFromService proxyTheRequest(RequestFromClient request, Url realServiceUrl) {
logger.debug("proxying a moxie.");
// If proxy on, then
// 1) Capture request message.
// 2) Set up a connection to the real service URL
// 3) Forward the request message to the real service URL
// 4) Read the reply from the real service URL.
// 5) Save request + response as a historical scenario.
// There are 2 proxy things going on here:
// 1. Using Mockey as a 'proxy' to a real service.
// 2. The proxy server between Mockey and the real service.
//
// For the proxy server between Mockey and the real service,
// we do the following:
ProxyServerModel proxyServer = store.getProxy();
ClientExecuteProxy clientExecuteProxy = ClientExecuteProxy.getClientExecuteProxyInstance();
ResponseFromService response = null;
// If Twisting is on, then
// 1)
try {
logger.debug("Initiating request through proxy");
TwistInfo twistInfo = store.getTwistInfoById(store.getUniversalTwistInfoId());
response = clientExecuteProxy.execute(twistInfo, proxyServer, realServiceUrl, allowRedirectFollow, request);
} catch (ClientExecuteProxyException e) {
// We're here for various reasons.
// 1) timeout from calling real service.
// 2) unable to parse real response.
// 3) magic!
// Before we throw an exception, check:
// (A) does this mock service have a default error response. If
// no, then
// (B) see if Mockey has a universal error response
// If neither, then throw the exception.
response = new ResponseFromService();
response.setRequestUrl(e.getRequestUrl());
Scenario error = this.getErrorScenario();
if (error != null) {
response.setBody(error.getResponseMessage());
} else {
StringBuffer msg = new StringBuffer();
JSONObject jsonResponseObject = new JSONObject();
try {
jsonResponseObject
.put("fail",
"We encountered an error. Here's some information to help point out what may have gone wrong.");
if (proxyServer != null && proxyServer.isProxyEnabled()) {
if (proxyServer.getProxyHost() != null && proxyServer.getProxyHost().trim().length() > 0) {
jsonResponseObject.put("proxyInfo", "Internet proxy settings are ENABLED pointing to -->"
+ proxyServer.getProxyHost() + "<-- ");
} else {
jsonResponseObject.put("proxyInfo",
"Internet proxy settings are ENABLED but Internet Proxy Server value is EMPTY.");
}
} else {
jsonResponseObject.put("proxyInfo", "Proxy settings are NOT ENABLED. ");
}
msg.append(jsonResponseObject.toString());
} catch (Exception ae) {
logger.error("Nothing is going right here.", ae);
msg.append("Experiencing some difficulties. ");
}
response.setBody(msg.toString());
}
}
return response;
}
private ResponseFromService executeStaticScenario(Url realServiceUrl) {
logger.debug("mockeying a static scenario");
// Proxy is NOT on. Therefore we use a scenario to figure out a reply.
// Either:
// 1) Based on matching the request message to one of the scenarios
// or
// 2) Based on scenario selected.
//
Scenario scenario = this.getScenario(this.getDefaultScenarioId());
ResponseFromService response = new ResponseFromService();
if (scenario != null) {
response.setBody(scenario.getResponseMessage());
response.setHttpResponseStatusCode(scenario.getHttpResponseStatusCode());
scenario.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis()));
Map<String,String> headerInfo = scenario.getHeaderInfoHelper();
List<Header> headerList = new ArrayList<Header>();
for(String k: headerInfo.keySet()){
headerList.add(new BasicHeader(k,headerInfo.get(k)));
}
response.setHeaders(headerList.toArray(new Header[headerList.size()]));
} else {
response.setBody("NO SCENARIO SELECTED");
}
response.setRequestUrl(realServiceUrl);
return response;
}
private ResponseFromService executeDynamicScenario(RequestFromClient request, Url realServiceUrl) {
logger.debug("mockeying a dynamic scenario.");
StringBuffer rawRequestDataBuffer = new StringBuffer();
try {
rawRequestDataBuffer.append(request.buildParameterRequest());
if (request.hasPostBody()) {
rawRequestDataBuffer.append(request.getBodyInfo());
}
} catch (UnsupportedEncodingException e) {
// uhm.
logger.debug("Unable to extract content from request", e);
}
String rawRequestData = rawRequestDataBuffer.toString();
ResponseFromService response = new ResponseFromService();
List<Scenario> scenarios = this.getScenarios();
Iterator<Scenario> iter = scenarios.iterator();
String messageMatchFound = null;
int httpResponseStatus = -1;
while (iter.hasNext()) {
Scenario scenario = iter.next();
logger.debug("Checking: '" + scenario.getMatchStringArg() + "' in Scenario message: \n" + rawRequestData);
int indexValue = -1;
if (scenario.hasMatchArgument()) {
indexValue = rawRequestData.indexOf(scenario.getMatchStringArg());
}
if ((indexValue > -1)) {
logger.debug("FOUND - matching '" + scenario.getMatchStringArg() + "' ");
messageMatchFound = scenario.getResponseMessage();
httpResponseStatus = scenario.getHttpResponseStatusCode();
// SET HEADERS
Map<String,String> headerInfo = scenario.getHeaderInfoHelper();
List<Header> headerList = new ArrayList<Header>();
for(String k: headerInfo.keySet()){
headerList.add(new BasicHeader(k,headerInfo.get(k)));
}
response.setHeaders(headerList.toArray(new Header[headerList.size()]));
break;
}
}
// OK, no matches. Error handling is as follows:
// 1) Does service have a default service error defined? If yes, return
// message. If no...
// 2) Does Mockey have a universal error message defined? If yes,
// return, otherwise...
// 3) Return a error message.
if (messageMatchFound == null) {
Scenario u = getErrorScenario();
if (u == null) {
u = store.getUniversalErrorScenario();
}
if (u != null) {
messageMatchFound = u.getResponseMessage();
} else {
messageMatchFound = "Ouch, no love for you! Why? Well, it could be that this service setting "
+ "is set to Dynamic but there is no found matching scenario, nor is there a default "
+ "service-scenario-error defined, nor is there a universal-scenario-error defined "
+ "for this incoming request. In otherwords, Mockey doesn't know what to do.";
}
}
response.setRequestUrl(realServiceUrl);
response.setBody(messageMatchFound);
response.setHttpResponseStatusCode(httpResponseStatus);
return response;
}
private String getNiceNameForService(String arg) {
String name = arg;
// Remove parameters
int index = arg.indexOf("?");
if (index > 0) {
arg = arg.substring(0, index);
}
StringTokenizer st = new StringTokenizer(arg, "/");
while (st.hasMoreTokens()) {
// Eventually, we get the last token, and
// we use it as the name.
name = st.nextToken();
}
name = name + " (auto generated)";
return name;
}
public List<Url> getRealServiceUrls() {
return realServiceUrlList;
}
/**
*
* @param url
*/
public void saveOrUpdateRealServiceUrl(Url url) {
if (url != null) {
boolean found = this.hasRealServiceUrl(url);
if (!found && !url.getFullUrl().trim().isEmpty()) {
this.realServiceUrlList.add(url);
}
// BONUS
// If this service name is undefined, then we try to determine
// an informative name based on the url
if (this.serviceName != null && this.serviceName.trim().isEmpty()) {
this.setServiceName(this.getNiceNameForService(url.getFullUrl()));
}
}
}
/**
*
* @param otherService
* @return non null if _this_ and otherService both have non-empty list of
* <code>Url</code> objects with a matching <code>Url</code> object.
* Otherwise, returns false;
*/
public Url getFirstMatchingRealServiceUrl(Service otherService) {
Url matchUrl = null;
if (this.realServiceUrlList != null && otherService != null && !otherService.getRealServiceUrls().isEmpty()) {
for (Url otherUrl : otherService.getRealServiceUrls()) {
if (this.hasRealServiceUrl(otherUrl)) {
matchUrl = otherUrl;
break;
}
}
}
return matchUrl;
}
public boolean hasRealServiceUrl(Url url) {
boolean has = false;
try {
for (Url urlTmp : this.realServiceUrlList) {
if (urlTmp.getFullUrl().trim().equalsIgnoreCase(url.getFullUrl())) {
has = true;
break;
}
}
} catch (Exception e) {
// do nothing
}
return has;
}
public static void main(String[] args) {
Service a = new Service();
Service b = new Service();
Url aUrl = new Url("http://www.google.com");
Url cUrl = new Url("http://www.cnn.com");
Url bUrl = new Url("http://www.cnn.com");
a.saveOrUpdateRealServiceUrl(aUrl);
a.saveOrUpdateRealServiceUrl(cUrl);
b.saveOrUpdateRealServiceUrl(bUrl);
System.out.print("Answer: " + a.getFirstMatchingRealServiceUrl(b));
}
/**
*
* @param url
* @see #getUrl()
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Mock URL. It's possible that this URL looks like one of the Real URLs.
* But, this value can be anything, but should be unique in the list of
* Services.
*
* @return
*/
public String getUrl() {
return url;
}
public int getDefaultRealUrlIndex() {
return this.defaultRealUrlIndex;
}
public void setDefaultRealUrlIndex(int i) {
this.defaultRealUrlIndex = i;
}
public Url getDefaultRealUrl() {
Url d = null;
try {
d = this.realServiceUrlList.get(this.defaultRealUrlIndex);
} catch (Exception e) {
// OK, let's try and be smart.
// Reset index.
this.defaultRealUrlIndex = 0;
if (!this.realServiceUrlList.isEmpty()) {
d = this.realServiceUrlList.get(0);
}
}
return d;
}
public void setTransientState(Boolean transientState) {
this.transientState = transientState;
}
public Boolean getTransientState() {
return transientState;
}
public boolean hasTag(String tag){
boolean has = super.hasTag(tag);
if(!has){
// Check scenarios...
for(Scenario s: this.getScenarios()){
has = s.hasTag(tag);
if(has){
break;
}
}
}
return has;
}
public String getRequestInspectorName() {
return requestInspectorName;
}
public void setRequestInspectorName(String requestInspectorName) {
this.requestInspectorName = requestInspectorName;
}
}
| robfromca/Mockey | src/java/com/mockey/model/Service.java | 6,822 | /**
*
* @param url
* @see #getUrl()
*/ | block_comment | nl | /*
* This file is part of Mockey, a tool for testing application
* interactions over HTTP, with a focus on testing web services,
* specifically web applications that consume XML, JSON, and HTML.
*
* Copyright (C) 2009-2010 Authors:
*
* chad.lafontaine (chad.lafontaine AT gmail DOT com)
* neil.cronin (neil AT rackle DOT com)
* lorin.kobashigawa (lkb AT kgawa DOT com)
* rob.meyer (rob AT bigdis DOT 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
package com.mockey.model;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.json.JSONObject;
import com.mockey.ClientExecuteProxy;
import com.mockey.ClientExecuteProxyException;
import com.mockey.OrderedMap;
import com.mockey.storage.IMockeyStorage;
import com.mockey.storage.StorageRegistry;
import com.mockey.ui.Util;
/**
* A Service is a remote url that can be called.
*
* @author chad.lafontaine
*
*/
public class Service extends StatusCheck implements PersistableItem, ExecutableService {
public final static int SERVICE_RESPONSE_TYPE_PROXY = 0;
public final static int SERVICE_RESPONSE_TYPE_STATIC_SCENARIO = 1;
public final static int SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO = 2;
private Long id;
private String serviceName;
private String description;
private Boolean transientState = new Boolean(false);
private Long defaultScenarioId;
private int defaultRealUrlIndex = 0;
private Long errorScenarioId;
private int hangTime = 0;
private String requestInspectorName;
private OrderedMap<Scenario> scenarios = new OrderedMap<Scenario>();
private int serviceResponseType = SERVICE_RESPONSE_TYPE_PROXY;
private String httpMethod = "GET";
private String url = "";
private List<FulfilledClientRequest> fulfilledRequests;
private List<Url> realServiceUrlList = new ArrayList<Url>();
private boolean allowRedirectFollow = true;
private static Log logger = LogFactory.getLog(Service.class);
private static IMockeyStorage store = StorageRegistry.MockeyStorage;
public List<FulfilledClientRequest> getFulfilledRequests() {
return fulfilledRequests;
}
public void setFulfilledRequests(List<FulfilledClientRequest> transactions) {
this.fulfilledRequests = transactions;
}
// default constructor for xml.
// DO NOT REMOVE. DO NOT CALL.
public Service() {
this.setServiceName("");
}
public String getHttpMethod() {
return httpMethod;
}
public void setHttpMethod(String httpMethod) {
this.httpMethod = httpMethod;
}
public Long getDefaultScenarioId() {
return this.defaultScenarioId;
}
/**
*
* @return null if no default scenario defined, otherwise, returns name
*/
public String getDefaultScenarioName(){
Scenario s = this.getScenario(this.defaultScenarioId);
if(s!=null){
return s.getScenarioName();
}else {
return null;
}
}
public void setDefaultScenarioId(Long did) {
this.defaultScenarioId = did;
}
/**
* Finds a service scenario with matching name. If a match is found, then
* its ID is set as the default scenario id. If no match is found, then no
* change. Name matching is case insensitive, and leading and ending
* whitespace is trimmed.
*
* @param scenarioName
*/
public void setDefaultScenarioByName(String scenarioName) {
if (scenarioName != null) {
for (Scenario scenario : this.scenarios.getOrderedList()) {
if (scenarioName.trim().equalsIgnoreCase((scenario.getScenarioName().trim()))) {
this.setDefaultScenarioId(scenario.getId());
break;
}
}
}
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String name) {
this.serviceName = name;
}
public int getHangTime() {
return hangTime;
}
public void setHangTime(int hangTime) {
this.hangTime = hangTime;
}
public List<Scenario> getScenarios() {
return Util.orderAlphabeticallyByScenarioName(scenarios.getOrderedList());
}
public Scenario getScenario(Long scenarioId) {
return (Scenario) scenarios.get(scenarioId);
}
public void deleteScenario(Long scenarioId) {
this.scenarios.remove(scenarioId);
}
public Scenario saveOrUpdateScenario(Scenario scenario) {
scenario.setServiceId(this.id);
return (Scenario) this.scenarios.save(scenario);
}
/**
* DO NOT REMOVE. This is needed by XML reader and has a reference to the
* method signature via reflection. Thank Digester.
*
* @param realServiceUrl
* @deprecated - this method will call
* <code>saveOrUpdateRealServiceUrl(Url)</code>
* @see #saveOrUpdateRealServiceUrl(Url)
*/
public void setRealServiceUrlByString(String realServiceUrl) {
this.saveOrUpdateRealServiceUrl(new Url(realServiceUrl));
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("Service name:").append(this.getServiceName()).append("\n");
sb.append("Real URL(s):\n");
if (this.realServiceUrlList != null && !this.realServiceUrlList.isEmpty()) {
Iterator<Url> iter = this.realServiceUrlList.iterator();
while (iter.hasNext()) {
sb.append(iter.next() + "\n");
}
} else {
sb.append("(no real urls defined for this service)\n");
}
sb.append("Default scenario ID:").append(this.getDefaultScenarioId()).append("\n");
sb.append("Hang time:");
sb.append(this.getHangTime());
sb.append("\n");
return sb.toString();
}
public void setId(Long id) {
this.id = id;
// Recursively set this ID to child Scenarios, if any exist.
for (Scenario scenario : getScenarios()) {
scenario.setServiceId(this.id);
this.saveOrUpdateScenario(scenario);
}
}
public Long getId() {
return id;
}
/**
*
* @deprecated
* @see #getRealServiceUrls()
*/
public String getRealServiceUrl() {
return "[DEPRECATED]";
}
/**
*
* @param serviceResponseType
* - 0 (proxy), 1 (static), or 2 (dynamic). Any other value will
* default to PROXY.
*/
public void setServiceResponseType(int serviceResponseType) {
if (serviceResponseType == 1 || serviceResponseType == 0 || serviceResponseType == 2) {
this.serviceResponseType = serviceResponseType;
} else {
this.serviceResponseType = SERVICE_RESPONSE_TYPE_PROXY;
}
validateDefaultScenarioId();
}
// HELPER method - let's validate the 'defaultScenarioId'. If
// defaultScenarioId doesn't equal any of the scenario IDs, then
// auto-set the defaultID to the 'first' scenario
private void validateDefaultScenarioId() {
boolean valid = false;
List<Scenario> orderedList = this.scenarios.getOrderedList();
for(Scenario s: orderedList){
if(s.getId().equals(this.getDefaultScenarioId()) ) {
valid = true;
break;
}
}
if(!valid){
if(this.scenarios.getOrderedList().size() > 0){
this.setDefaultScenarioId(orderedList.get(0).getId());
}else {
// Reset
this.setDefaultScenarioId(null);
}
}
}
/**
* Takes 'proxy', 'static', or 'dynamic' arguments and translates them to
* appropriate 'int' values and then calls
* <code>setServiceResponseType</code>
*
* @see #setServiceResponseType(int)
*/
public void setServiceResponseTypeByString(String arg) {
if (arg != null) {
if ("proxy".trim().equalsIgnoreCase(arg.trim()) || "0".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_PROXY);
} else if ("static".trim().equalsIgnoreCase(arg.trim()) || "1".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO);
} else if ("dynamic".trim().equalsIgnoreCase(arg.trim()) || "2".equalsIgnoreCase(arg.trim())) {
setServiceResponseType(Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO);
}
}
}
public int getServiceResponseType() {
// If no scenarios, then proxy is automatically on.
if (this.getScenarios().size() == 0) {
return SERVICE_RESPONSE_TYPE_PROXY;
} else {
return serviceResponseType;
}
}
public String getServiceResponseTypeAsString(){
int x = getServiceResponseType();
if(x == Service.SERVICE_RESPONSE_TYPE_PROXY){
return "proxy";
}else if(x == Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO){
return "static";
}else if(x == Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO){
return "dynamic";
}else {
return "";
}
}
public void setErrorScenarioId(Long errorScenarioId) {
this.errorScenarioId = errorScenarioId;
}
public Long getErrorScenarioId() {
return errorScenarioId;
}
public Scenario getErrorScenario() {
// FIND SERVICE ERROR, IF EXIST.
for (Scenario scenario : this.getScenarios()) {
if (scenario.getId().equals(this.getErrorScenarioId())) {
return scenario;
}
}
// No service error defined, therefore, let's use the universal
// error.
return StorageRegistry.MockeyStorage.getUniversalErrorScenario();
}
public Boolean isReferencedInAServicePlan() {
Boolean isReferenced = false;
for (ServicePlan plan : StorageRegistry.MockeyStorage.getServicePlans()) {
for (PlanItem planItem : plan.getPlanItemList()) {
if (planItem.getServiceId().equals(this.getId())) {
isReferenced = true;
break;
}
}
}
return isReferenced;
}
/**
* The core method to execute the request as either a Proxy, Dynamic, or
* Static Scenario.
*/
public ResponseFromService execute(RequestFromClient request, Url realServiceUrl) {
this.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis()));
ResponseFromService response = null;
if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_PROXY) {
response = proxyTheRequest(request, realServiceUrl);
} else if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_DYNAMIC_SCENARIO) {
response = executeDynamicScenario(request, realServiceUrl);
} else if (this.getServiceResponseType() == Service.SERVICE_RESPONSE_TYPE_STATIC_SCENARIO) {
response = executeStaticScenario(realServiceUrl);
}
return response;
}
private ResponseFromService proxyTheRequest(RequestFromClient request, Url realServiceUrl) {
logger.debug("proxying a moxie.");
// If proxy on, then
// 1) Capture request message.
// 2) Set up a connection to the real service URL
// 3) Forward the request message to the real service URL
// 4) Read the reply from the real service URL.
// 5) Save request + response as a historical scenario.
// There are 2 proxy things going on here:
// 1. Using Mockey as a 'proxy' to a real service.
// 2. The proxy server between Mockey and the real service.
//
// For the proxy server between Mockey and the real service,
// we do the following:
ProxyServerModel proxyServer = store.getProxy();
ClientExecuteProxy clientExecuteProxy = ClientExecuteProxy.getClientExecuteProxyInstance();
ResponseFromService response = null;
// If Twisting is on, then
// 1)
try {
logger.debug("Initiating request through proxy");
TwistInfo twistInfo = store.getTwistInfoById(store.getUniversalTwistInfoId());
response = clientExecuteProxy.execute(twistInfo, proxyServer, realServiceUrl, allowRedirectFollow, request);
} catch (ClientExecuteProxyException e) {
// We're here for various reasons.
// 1) timeout from calling real service.
// 2) unable to parse real response.
// 3) magic!
// Before we throw an exception, check:
// (A) does this mock service have a default error response. If
// no, then
// (B) see if Mockey has a universal error response
// If neither, then throw the exception.
response = new ResponseFromService();
response.setRequestUrl(e.getRequestUrl());
Scenario error = this.getErrorScenario();
if (error != null) {
response.setBody(error.getResponseMessage());
} else {
StringBuffer msg = new StringBuffer();
JSONObject jsonResponseObject = new JSONObject();
try {
jsonResponseObject
.put("fail",
"We encountered an error. Here's some information to help point out what may have gone wrong.");
if (proxyServer != null && proxyServer.isProxyEnabled()) {
if (proxyServer.getProxyHost() != null && proxyServer.getProxyHost().trim().length() > 0) {
jsonResponseObject.put("proxyInfo", "Internet proxy settings are ENABLED pointing to -->"
+ proxyServer.getProxyHost() + "<-- ");
} else {
jsonResponseObject.put("proxyInfo",
"Internet proxy settings are ENABLED but Internet Proxy Server value is EMPTY.");
}
} else {
jsonResponseObject.put("proxyInfo", "Proxy settings are NOT ENABLED. ");
}
msg.append(jsonResponseObject.toString());
} catch (Exception ae) {
logger.error("Nothing is going right here.", ae);
msg.append("Experiencing some difficulties. ");
}
response.setBody(msg.toString());
}
}
return response;
}
private ResponseFromService executeStaticScenario(Url realServiceUrl) {
logger.debug("mockeying a static scenario");
// Proxy is NOT on. Therefore we use a scenario to figure out a reply.
// Either:
// 1) Based on matching the request message to one of the scenarios
// or
// 2) Based on scenario selected.
//
Scenario scenario = this.getScenario(this.getDefaultScenarioId());
ResponseFromService response = new ResponseFromService();
if (scenario != null) {
response.setBody(scenario.getResponseMessage());
response.setHttpResponseStatusCode(scenario.getHttpResponseStatusCode());
scenario.setLastVisit(new Long(Calendar.getInstance().getTimeInMillis()));
Map<String,String> headerInfo = scenario.getHeaderInfoHelper();
List<Header> headerList = new ArrayList<Header>();
for(String k: headerInfo.keySet()){
headerList.add(new BasicHeader(k,headerInfo.get(k)));
}
response.setHeaders(headerList.toArray(new Header[headerList.size()]));
} else {
response.setBody("NO SCENARIO SELECTED");
}
response.setRequestUrl(realServiceUrl);
return response;
}
private ResponseFromService executeDynamicScenario(RequestFromClient request, Url realServiceUrl) {
logger.debug("mockeying a dynamic scenario.");
StringBuffer rawRequestDataBuffer = new StringBuffer();
try {
rawRequestDataBuffer.append(request.buildParameterRequest());
if (request.hasPostBody()) {
rawRequestDataBuffer.append(request.getBodyInfo());
}
} catch (UnsupportedEncodingException e) {
// uhm.
logger.debug("Unable to extract content from request", e);
}
String rawRequestData = rawRequestDataBuffer.toString();
ResponseFromService response = new ResponseFromService();
List<Scenario> scenarios = this.getScenarios();
Iterator<Scenario> iter = scenarios.iterator();
String messageMatchFound = null;
int httpResponseStatus = -1;
while (iter.hasNext()) {
Scenario scenario = iter.next();
logger.debug("Checking: '" + scenario.getMatchStringArg() + "' in Scenario message: \n" + rawRequestData);
int indexValue = -1;
if (scenario.hasMatchArgument()) {
indexValue = rawRequestData.indexOf(scenario.getMatchStringArg());
}
if ((indexValue > -1)) {
logger.debug("FOUND - matching '" + scenario.getMatchStringArg() + "' ");
messageMatchFound = scenario.getResponseMessage();
httpResponseStatus = scenario.getHttpResponseStatusCode();
// SET HEADERS
Map<String,String> headerInfo = scenario.getHeaderInfoHelper();
List<Header> headerList = new ArrayList<Header>();
for(String k: headerInfo.keySet()){
headerList.add(new BasicHeader(k,headerInfo.get(k)));
}
response.setHeaders(headerList.toArray(new Header[headerList.size()]));
break;
}
}
// OK, no matches. Error handling is as follows:
// 1) Does service have a default service error defined? If yes, return
// message. If no...
// 2) Does Mockey have a universal error message defined? If yes,
// return, otherwise...
// 3) Return a error message.
if (messageMatchFound == null) {
Scenario u = getErrorScenario();
if (u == null) {
u = store.getUniversalErrorScenario();
}
if (u != null) {
messageMatchFound = u.getResponseMessage();
} else {
messageMatchFound = "Ouch, no love for you! Why? Well, it could be that this service setting "
+ "is set to Dynamic but there is no found matching scenario, nor is there a default "
+ "service-scenario-error defined, nor is there a universal-scenario-error defined "
+ "for this incoming request. In otherwords, Mockey doesn't know what to do.";
}
}
response.setRequestUrl(realServiceUrl);
response.setBody(messageMatchFound);
response.setHttpResponseStatusCode(httpResponseStatus);
return response;
}
private String getNiceNameForService(String arg) {
String name = arg;
// Remove parameters
int index = arg.indexOf("?");
if (index > 0) {
arg = arg.substring(0, index);
}
StringTokenizer st = new StringTokenizer(arg, "/");
while (st.hasMoreTokens()) {
// Eventually, we get the last token, and
// we use it as the name.
name = st.nextToken();
}
name = name + " (auto generated)";
return name;
}
public List<Url> getRealServiceUrls() {
return realServiceUrlList;
}
/**
*
* @param url
*/
public void saveOrUpdateRealServiceUrl(Url url) {
if (url != null) {
boolean found = this.hasRealServiceUrl(url);
if (!found && !url.getFullUrl().trim().isEmpty()) {
this.realServiceUrlList.add(url);
}
// BONUS
// If this service name is undefined, then we try to determine
// an informative name based on the url
if (this.serviceName != null && this.serviceName.trim().isEmpty()) {
this.setServiceName(this.getNiceNameForService(url.getFullUrl()));
}
}
}
/**
*
* @param otherService
* @return non null if _this_ and otherService both have non-empty list of
* <code>Url</code> objects with a matching <code>Url</code> object.
* Otherwise, returns false;
*/
public Url getFirstMatchingRealServiceUrl(Service otherService) {
Url matchUrl = null;
if (this.realServiceUrlList != null && otherService != null && !otherService.getRealServiceUrls().isEmpty()) {
for (Url otherUrl : otherService.getRealServiceUrls()) {
if (this.hasRealServiceUrl(otherUrl)) {
matchUrl = otherUrl;
break;
}
}
}
return matchUrl;
}
public boolean hasRealServiceUrl(Url url) {
boolean has = false;
try {
for (Url urlTmp : this.realServiceUrlList) {
if (urlTmp.getFullUrl().trim().equalsIgnoreCase(url.getFullUrl())) {
has = true;
break;
}
}
} catch (Exception e) {
// do nothing
}
return has;
}
public static void main(String[] args) {
Service a = new Service();
Service b = new Service();
Url aUrl = new Url("http://www.google.com");
Url cUrl = new Url("http://www.cnn.com");
Url bUrl = new Url("http://www.cnn.com");
a.saveOrUpdateRealServiceUrl(aUrl);
a.saveOrUpdateRealServiceUrl(cUrl);
b.saveOrUpdateRealServiceUrl(bUrl);
System.out.print("Answer: " + a.getFirstMatchingRealServiceUrl(b));
}
/**
*
* @param url
<SUF>*/
public void setUrl(String url) {
this.url = url;
}
/**
* Mock URL. It's possible that this URL looks like one of the Real URLs.
* But, this value can be anything, but should be unique in the list of
* Services.
*
* @return
*/
public String getUrl() {
return url;
}
public int getDefaultRealUrlIndex() {
return this.defaultRealUrlIndex;
}
public void setDefaultRealUrlIndex(int i) {
this.defaultRealUrlIndex = i;
}
public Url getDefaultRealUrl() {
Url d = null;
try {
d = this.realServiceUrlList.get(this.defaultRealUrlIndex);
} catch (Exception e) {
// OK, let's try and be smart.
// Reset index.
this.defaultRealUrlIndex = 0;
if (!this.realServiceUrlList.isEmpty()) {
d = this.realServiceUrlList.get(0);
}
}
return d;
}
public void setTransientState(Boolean transientState) {
this.transientState = transientState;
}
public Boolean getTransientState() {
return transientState;
}
public boolean hasTag(String tag){
boolean has = super.hasTag(tag);
if(!has){
// Check scenarios...
for(Scenario s: this.getScenarios()){
has = s.hasTag(tag);
if(has){
break;
}
}
}
return has;
}
public String getRequestInspectorName() {
return requestInspectorName;
}
public void setRequestInspectorName(String requestInspectorName) {
this.requestInspectorName = requestInspectorName;
}
}
|
179554_0 | import javax.swing.*;
import javax.swing.*;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class Oui extends JFrame implements Runnable {
private Panneau p;
private Plateau pl;
private ArrayList<Perso> ap;
private Controler c;
private CardLayout cl;
private JPanel jp;
private Menu m;
private MenuPrincipal mp;
private PanneauEditeur edit;
private ControlerEditeur ce = null;
public Oui(Plateau pl, ArrayList<Perso> ap) {
this.ap = ap;
this.pl = pl;
c = new Controler(ap,this);
p = new Panneau(pl);
m = new Menu(this);
mp = new MenuPrincipal(this);
edit = new PanneauEditeur(pl.getSize(), this);
this.setTitle("BomBerMan");
/*Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int height = (int)dimension.getHeight()-40;
int width = (int)dimension.getWidth();
this.setSize(width, height);*/
this.setBackground(Color.black);
this.setLocation(150, 0);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(1015, 700));
this.setVisible(true);
this.addKeyListener(c);
this.setResizable(false);
this.cl = new CardLayout();
this.jp = new JPanel(cl);
this.setContentPane(jp);
jp.add(edit,"editeur de niveau");
jp.add(mp,"menuprincipal");
jp.add(p,"jeu");
jp.add(m, "menu");
cl.show(jp,"menuprincipal");
}
public void setP(ArrayList<Perso> ap, Plateau pl){
this.ap = ap;
this.pl=pl;
pl.setArrayList(ap);
this.p.setPlateau(pl);
c = new Controler(ap,this);
this.addKeyListener(c);
cl.show(jp,"jeu");
}
public void afficherJeu() {
this.setSize(new Dimension(1000,1026));
this.setFocusable(true);
cl.show(jp,"jeu");
}
public void restartJeu(){
c.restart();
}
public void afficherMenu() {
cl.show(jp,"menu");
}
public void afficherEditeurNiveau() {
if(ce == null) {
ce = new ControlerEditeur(edit);
this.addMouseListener(ce);
}
this.setSize(new Dimension(1000,1026));
cl.show(jp,"editeur de niveau");
}
public void enregistrerMap(){
//TODO: enregistrer comme dans zboob.txt
cl.show(jp, "enregistrer map");
}
public void run() {
try {
while (true) {
////System.out.println("affichage");
Thread.sleep(20);
p.repaint();
}
}catch (InterruptedException e){
System.err.println("Fin de la partie");
}
finally {
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
public void afficherMenuPrincipale() {
this.setBackground(Color.black);
this.setSize(new Dimension(1015, 700));
cl.show(jp,"menuprincipal");
}
} | robinbart/TrueBbm | src/Oui.java | 1,053 | /*Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int height = (int)dimension.getHeight()-40;
int width = (int)dimension.getWidth();
this.setSize(width, height);*/ | block_comment | nl | import javax.swing.*;
import javax.swing.*;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
public class Oui extends JFrame implements Runnable {
private Panneau p;
private Plateau pl;
private ArrayList<Perso> ap;
private Controler c;
private CardLayout cl;
private JPanel jp;
private Menu m;
private MenuPrincipal mp;
private PanneauEditeur edit;
private ControlerEditeur ce = null;
public Oui(Plateau pl, ArrayList<Perso> ap) {
this.ap = ap;
this.pl = pl;
c = new Controler(ap,this);
p = new Panneau(pl);
m = new Menu(this);
mp = new MenuPrincipal(this);
edit = new PanneauEditeur(pl.getSize(), this);
this.setTitle("BomBerMan");
/*Dimension dimension =<SUF>*/
this.setBackground(Color.black);
this.setLocation(150, 0);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(1015, 700));
this.setVisible(true);
this.addKeyListener(c);
this.setResizable(false);
this.cl = new CardLayout();
this.jp = new JPanel(cl);
this.setContentPane(jp);
jp.add(edit,"editeur de niveau");
jp.add(mp,"menuprincipal");
jp.add(p,"jeu");
jp.add(m, "menu");
cl.show(jp,"menuprincipal");
}
public void setP(ArrayList<Perso> ap, Plateau pl){
this.ap = ap;
this.pl=pl;
pl.setArrayList(ap);
this.p.setPlateau(pl);
c = new Controler(ap,this);
this.addKeyListener(c);
cl.show(jp,"jeu");
}
public void afficherJeu() {
this.setSize(new Dimension(1000,1026));
this.setFocusable(true);
cl.show(jp,"jeu");
}
public void restartJeu(){
c.restart();
}
public void afficherMenu() {
cl.show(jp,"menu");
}
public void afficherEditeurNiveau() {
if(ce == null) {
ce = new ControlerEditeur(edit);
this.addMouseListener(ce);
}
this.setSize(new Dimension(1000,1026));
cl.show(jp,"editeur de niveau");
}
public void enregistrerMap(){
//TODO: enregistrer comme dans zboob.txt
cl.show(jp, "enregistrer map");
}
public void run() {
try {
while (true) {
////System.out.println("affichage");
Thread.sleep(20);
p.repaint();
}
}catch (InterruptedException e){
System.err.println("Fin de la partie");
}
finally {
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
public void afficherMenuPrincipale() {
this.setBackground(Color.black);
this.setSize(new Dimension(1015, 700));
cl.show(jp,"menuprincipal");
}
} |
90919_0 | package h5;
import java.applet.Applet;
import java.awt.*;
public class opdracht5_1 extends Applet{
//declaratie.
Color opvulkleur;
Color lijnkleur;
int breedte;
int hoogte;
public void init() {
//initialisatie.
opvulkleur = Color.MAGENTA;
lijnkleur = Color.BLACK;
breedte = 200;
hoogte = 100;
}
public void paint(Graphics g) {
//teken lijn
g.drawLine( 100, 50, 297, 50);
//teken rechthoek
g.drawRect(100, 100, breedte, hoogte);
//teken afgeronde rechthoek
g.drawRoundRect(100, 225, breedte, hoogte, 30, 30);
//teken gevulde rechthoek
g.setColor(opvulkleur);
g.fillRect(315, 100, breedte, hoogte);
//teken ovaal
g.setColor(lijnkleur);
g.drawOval(315, 100, breedte, hoogte);
//teken gevulde ovaal
g.setColor(opvulkleur);
g.fillOval(315, 225, breedte, hoogte);
//begin Taartpunt met ovaal eromheen
g.setColor(lijnkleur);
g.drawArc(530, 102, breedte, hoogte, 90, 360);
g.setColor(opvulkleur);
g.fillArc(530,102,breedte,hoogte,0,45);
g.setColor(lijnkleur);
g.drawArc(570, 220, 120, 120, 720, 360);
}
} | robincreebsburg/inleiding-java | src/h5/opdracht5_1.java | 489 | //teken afgeronde rechthoek | line_comment | nl | package h5;
import java.applet.Applet;
import java.awt.*;
public class opdracht5_1 extends Applet{
//declaratie.
Color opvulkleur;
Color lijnkleur;
int breedte;
int hoogte;
public void init() {
//initialisatie.
opvulkleur = Color.MAGENTA;
lijnkleur = Color.BLACK;
breedte = 200;
hoogte = 100;
}
public void paint(Graphics g) {
//teken lijn
g.drawLine( 100, 50, 297, 50);
//teken rechthoek
g.drawRect(100, 100, breedte, hoogte);
//teken afgeronde<SUF>
g.drawRoundRect(100, 225, breedte, hoogte, 30, 30);
//teken gevulde rechthoek
g.setColor(opvulkleur);
g.fillRect(315, 100, breedte, hoogte);
//teken ovaal
g.setColor(lijnkleur);
g.drawOval(315, 100, breedte, hoogte);
//teken gevulde ovaal
g.setColor(opvulkleur);
g.fillOval(315, 225, breedte, hoogte);
//begin Taartpunt met ovaal eromheen
g.setColor(lijnkleur);
g.drawArc(530, 102, breedte, hoogte, 90, 360);
g.setColor(opvulkleur);
g.fillArc(530,102,breedte,hoogte,0,45);
g.setColor(lijnkleur);
g.drawArc(570, 220, 120, 120, 720, 360);
}
} |
29771_3 | // 1 Naam Enscapsulation
// 2 Probleem / Effect Een field kan een ongewenste waarde hebben
// 3 OOP onderdelen ingezet 1 acces modifier 2 parameters 3 returntype
// 4 Programmeren
// 5 Use Cases Bank, leeftijd, nummerbord, postcode
public class MyClass {
public static void main(String args[]) {
Overboeking ov = new Overboeking();
// ov.bedrag = -50;
ov.setBedrag(-50);
ov.overboeken();
System.out.println("Demo werkt");
}
}
class Overboeking{
private int bedrag;
void overboeken() {
System.out.println("Bij mij gaat er "+bedrag+" af");
System.out.println("Bij mij gaat er "+bedrag+" bij");
}
public void setBedrag(int amount) {
if(amount < 0) {
System.out.println("Dit is een illigale hoeveelheid");
}
else{
bedrag = amount;
}
}
} | rodivanrooijen/YCN_Public | 1. JAVA/MyClass (1).java | 305 | // 5 Use Cases Bank, leeftijd, nummerbord, postcode | line_comment | nl | // 1 Naam Enscapsulation
// 2 Probleem / Effect Een field kan een ongewenste waarde hebben
// 3 OOP onderdelen ingezet 1 acces modifier 2 parameters 3 returntype
// 4 Programmeren
// 5 Use<SUF>
public class MyClass {
public static void main(String args[]) {
Overboeking ov = new Overboeking();
// ov.bedrag = -50;
ov.setBedrag(-50);
ov.overboeken();
System.out.println("Demo werkt");
}
}
class Overboeking{
private int bedrag;
void overboeken() {
System.out.println("Bij mij gaat er "+bedrag+" af");
System.out.println("Bij mij gaat er "+bedrag+" bij");
}
public void setBedrag(int amount) {
if(amount < 0) {
System.out.println("Dit is een illigale hoeveelheid");
}
else{
bedrag = amount;
}
}
} |
161982_2 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package scenario01;
public class OrderManager {
public OrderManager(Order order) {
// Set order status to processing
System.out.println("is processing: "+ order.isProcessing());
order.setProcessing();
System.out.println("is processing: "+ order.isProcessing());
System.out.println("Order: " + order.getOrderID() + ", from client: " + order.getClientID() + " is processing");
// Zet de staat van de bestelling op “Compleet” als de huidige tijdstempel hoger dan de som van “start tijd” en “duur” is
order.setComplete();
System.out.println("Order is complete, duration: " + order.getDuration());
}
} | roelbaka/schoolcode-dev0-1-6-a | src/scenario01/OrderManager.java | 245 | // Zet de staat van de bestelling op “Compleet” als de huidige tijdstempel hoger dan de som van “start tijd” en “duur” is
| line_comment | nl | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package scenario01;
public class OrderManager {
public OrderManager(Order order) {
// Set order status to processing
System.out.println("is processing: "+ order.isProcessing());
order.setProcessing();
System.out.println("is processing: "+ order.isProcessing());
System.out.println("Order: " + order.getOrderID() + ", from client: " + order.getClientID() + " is processing");
// Zet de<SUF>
order.setComplete();
System.out.println("Order is complete, duration: " + order.getDuration());
}
} |
75967_0 | package NeuraalNetwerk;
import org.ejml.simple.SimpleMatrix;
import java.util.Random;
import java.util.function.DoubleFunction;
public class Layer {
private int nNodes;
private SimpleMatrix gewichten;
private SimpleMatrix biases;
private SimpleMatrix ongeactiveerd;
private SimpleMatrix uitkomst;
private SimpleMatrix delta;
private SimpleMatrix gradient_gewicht;
private SimpleMatrix gradient_bias;
private DoubleFunction<Double> activering;
private DoubleFunction<Double> activering_accent;
public Layer(int nNodes, int nNodes_vorige, DoubleFunction<Double> activering,
DoubleFunction<Double> activering_accent, double[] grenzen_gewichten, double[] grenzen_biases) {
this.nNodes = nNodes;
gewichten = SimpleMatrix.random_DDRM(nNodes_vorige, nNodes, grenzen_gewichten[0], grenzen_gewichten[1], new Random());
biases = SimpleMatrix.random_DDRM(1, nNodes, grenzen_biases[0], grenzen_biases[1], new Random());
this.activering = activering;
this.activering_accent = activering_accent;
}
public Layer(int nNodes) {
this.nNodes = nNodes;
}
// Het echte werk
public void predict(SimpleMatrix input) {
ongeactiveerd = input.mult(gewichten).copy();
Functies.rijgewijs_optellen(ongeactiveerd, biases);
uitkomst = ongeactiveerd.copy();
Functies.mapFunctie(uitkomst, activering);
}
// Setters
public void setUitkomst(SimpleMatrix uitkomst) throws IllegalArgumentException {
if(uitkomst.numCols() != nNodes)
throw new IllegalArgumentException("Onjuiste dimensie van uitkomstmatrix");
this.uitkomst = uitkomst.copy();
}
public void setGradient_gewicht(SimpleMatrix gradient_gewicht) {
this.gradient_gewicht = gradient_gewicht.copy();
}
public void setGradient_bias(SimpleMatrix gradient_bias) {
this.gradient_bias = gradient_bias.copy();
}
public void setDelta(SimpleMatrix delta){
if(delta.numCols() != nNodes)
throw new IllegalArgumentException("Onjuiste dimensie van uitkomstmatrix");
this.delta = delta.copy();
}
public void setGewichten(SimpleMatrix gw){
this.gewichten = gw.copy();
}
public void setBiases(SimpleMatrix bs){
this.biases = bs.copy();
}
// Getters
public SimpleMatrix getUitkomst(){
return uitkomst.copy();
}
public int getNNodes() {
return nNodes;
}
public SimpleMatrix getGewichten(){
return gewichten.copy();
}
public SimpleMatrix getBiases(){
return biases.copy();
}
public SimpleMatrix getDelta() {
return delta.copy();
}
public SimpleMatrix getOngeactiveerd() {
return ongeactiveerd.copy();
}
public SimpleMatrix getGradient_gewicht() {
return gradient_gewicht;
}
public SimpleMatrix getGradient_bias() {
return gradient_bias;
}
public DoubleFunction<Double> getActivering(){
return activering;
}
public DoubleFunction<Double> getActivering_accent(){
return activering_accent;
}
}
| roelofcoster/NeuraalNetwerk | src/NeuraalNetwerk/Layer.java | 954 | // Het echte werk | line_comment | nl | package NeuraalNetwerk;
import org.ejml.simple.SimpleMatrix;
import java.util.Random;
import java.util.function.DoubleFunction;
public class Layer {
private int nNodes;
private SimpleMatrix gewichten;
private SimpleMatrix biases;
private SimpleMatrix ongeactiveerd;
private SimpleMatrix uitkomst;
private SimpleMatrix delta;
private SimpleMatrix gradient_gewicht;
private SimpleMatrix gradient_bias;
private DoubleFunction<Double> activering;
private DoubleFunction<Double> activering_accent;
public Layer(int nNodes, int nNodes_vorige, DoubleFunction<Double> activering,
DoubleFunction<Double> activering_accent, double[] grenzen_gewichten, double[] grenzen_biases) {
this.nNodes = nNodes;
gewichten = SimpleMatrix.random_DDRM(nNodes_vorige, nNodes, grenzen_gewichten[0], grenzen_gewichten[1], new Random());
biases = SimpleMatrix.random_DDRM(1, nNodes, grenzen_biases[0], grenzen_biases[1], new Random());
this.activering = activering;
this.activering_accent = activering_accent;
}
public Layer(int nNodes) {
this.nNodes = nNodes;
}
// Het echte<SUF>
public void predict(SimpleMatrix input) {
ongeactiveerd = input.mult(gewichten).copy();
Functies.rijgewijs_optellen(ongeactiveerd, biases);
uitkomst = ongeactiveerd.copy();
Functies.mapFunctie(uitkomst, activering);
}
// Setters
public void setUitkomst(SimpleMatrix uitkomst) throws IllegalArgumentException {
if(uitkomst.numCols() != nNodes)
throw new IllegalArgumentException("Onjuiste dimensie van uitkomstmatrix");
this.uitkomst = uitkomst.copy();
}
public void setGradient_gewicht(SimpleMatrix gradient_gewicht) {
this.gradient_gewicht = gradient_gewicht.copy();
}
public void setGradient_bias(SimpleMatrix gradient_bias) {
this.gradient_bias = gradient_bias.copy();
}
public void setDelta(SimpleMatrix delta){
if(delta.numCols() != nNodes)
throw new IllegalArgumentException("Onjuiste dimensie van uitkomstmatrix");
this.delta = delta.copy();
}
public void setGewichten(SimpleMatrix gw){
this.gewichten = gw.copy();
}
public void setBiases(SimpleMatrix bs){
this.biases = bs.copy();
}
// Getters
public SimpleMatrix getUitkomst(){
return uitkomst.copy();
}
public int getNNodes() {
return nNodes;
}
public SimpleMatrix getGewichten(){
return gewichten.copy();
}
public SimpleMatrix getBiases(){
return biases.copy();
}
public SimpleMatrix getDelta() {
return delta.copy();
}
public SimpleMatrix getOngeactiveerd() {
return ongeactiveerd.copy();
}
public SimpleMatrix getGradient_gewicht() {
return gradient_gewicht;
}
public SimpleMatrix getGradient_bias() {
return gradient_bias;
}
public DoubleFunction<Double> getActivering(){
return activering;
}
public DoubleFunction<Double> getActivering_accent(){
return activering_accent;
}
}
|
34176_2 | package kta02.xml;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import kta02.domein.Bestelling;
import kta02.domein.Klant;
import kta02.gui.EmergencyPanel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XMLReader
{
private EmergencyPanel emPanel;
private static final int FILTER_NUM = 1;
private static final int FILTER_WORD = 2;
private static final int FILTER_ZIP = 3;
private static final int FILTER_DATE = 4;
int aantalArtikelen = 0;
private File file;
public XMLReader(String filename)
{
file = new File(filename);
}
/**
*
* @param string
* @param what
* @return
*/
public String makeMatchExpression(String string, int what)
{
String p;
if (what == FILTER_NUM)
{
p = "([^0-9]+)";
}
else if (what == FILTER_WORD)
{
p = "([^\\w ]+)";
}
else if (what == FILTER_ZIP)
{
p = "([^\\w]+)";
}
else if (what == FILTER_DATE)
{
p = "([^0-9\\-]+)";
}
else
{
return string;
}
return string.replaceAll(p, "");
}
private String getDataFromTag(Document doc, String keyName, int childNode) throws BadLocationException
{
NodeList nodeList = doc.getElementsByTagName(keyName);
if (nodeList.getLength() == 0)
{
throw new BadLocationException("Node not found", 0);
}
Element temporaryElement = (Element) nodeList.item(childNode);
NodeList temporaryElementNodes = temporaryElement.getChildNodes();
return (String) ((Node) temporaryElementNodes.item(0)).getNodeValue().trim();
}
private String getFilteredDataFromTag(Document doc, String keyname, int childNode, int filter) throws BadLocationException
{
String keyValue = getDataFromTag(doc, keyname, childNode);
keyValue = makeMatchExpression(keyValue, filter);
return keyValue;
}
private String getFilteredDataFromTag(Document doc, String keyname, int filter) throws BadLocationException
{
return getFilteredDataFromTag(doc, keyname, 0, filter);
}
public Bestelling readFromXml()
{
Bestelling bestelling = new Bestelling();
Klant klant = new Klant();
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); //nieuw DocumentBuilderFactory Instance
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); //nieuw DocumentBuilderFactory
Document doc = docBuilder.parse(file); //bestandnaam
doc.getDocumentElement().normalize(); //Normaliseer tekst.
String ordernummer = getFilteredDataFromTag(doc, "ordernummer", FILTER_NUM);
bestelling.setBestelNummer(Integer.decode(ordernummer));
String voornaam = getFilteredDataFromTag(doc, "voornaam", FILTER_WORD);
klant.setVoornaam(voornaam);
String achternaam = getFilteredDataFromTag(doc, "achternaam", FILTER_WORD);
klant.setAchternaam(achternaam);
String adres = getFilteredDataFromTag(doc, "adres", FILTER_WORD);
klant.setAdres(adres);
String postcode = getFilteredDataFromTag(doc, "postcode", FILTER_ZIP).toUpperCase();
klant.setPostcode(postcode);
String plaats = getFilteredDataFromTag(doc, "plaats", FILTER_WORD);
klant.setPlaats(plaats);
bestelling.setKlant(klant);
//Datum ophalen
String datum = getFilteredDataFromTag(doc, "datum", FILTER_DATE);
bestelling.setDatum(datum);
//Artikelnummers ophalen
NodeList artikelnrNodeList = doc.getElementsByTagName("artikelnr"); //Zoek naar element met de "" tekst.
for (int i = 0; i < artikelnrNodeList.getLength(); i++)
{
String artikelnr = getFilteredDataFromTag(doc, "artikelnr", i, FILTER_NUM);
bestelling.voegToeArtikel(Integer.decode(artikelnr));
}
}
catch (BadLocationException b){
JOptionPane.showMessageDialog(emPanel, "De lay-out van uw bestelling klopt niet. Gebruik deze lay-out: http://pastebin.com/5DFCrQN1", "Lay-out Error", JOptionPane.ERROR_MESSAGE);
}
catch (SAXParseException err)
{
System.out.println("** Parsing error" + ", line "
+ err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
}
catch (SAXException e)
{
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}
catch (Throwable t)
{
t.printStackTrace();
}
return bestelling;
}
public int getAantalArtikelen()
{
return aantalArtikelen;
}
}
| roelofr/binpack-robot | src/kta02/xml/XMLReader.java | 1,590 | //Zoek naar element met de "" tekst. | line_comment | nl | package kta02.xml;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.text.BadLocationException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import kta02.domein.Bestelling;
import kta02.domein.Klant;
import kta02.gui.EmergencyPanel;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class XMLReader
{
private EmergencyPanel emPanel;
private static final int FILTER_NUM = 1;
private static final int FILTER_WORD = 2;
private static final int FILTER_ZIP = 3;
private static final int FILTER_DATE = 4;
int aantalArtikelen = 0;
private File file;
public XMLReader(String filename)
{
file = new File(filename);
}
/**
*
* @param string
* @param what
* @return
*/
public String makeMatchExpression(String string, int what)
{
String p;
if (what == FILTER_NUM)
{
p = "([^0-9]+)";
}
else if (what == FILTER_WORD)
{
p = "([^\\w ]+)";
}
else if (what == FILTER_ZIP)
{
p = "([^\\w]+)";
}
else if (what == FILTER_DATE)
{
p = "([^0-9\\-]+)";
}
else
{
return string;
}
return string.replaceAll(p, "");
}
private String getDataFromTag(Document doc, String keyName, int childNode) throws BadLocationException
{
NodeList nodeList = doc.getElementsByTagName(keyName);
if (nodeList.getLength() == 0)
{
throw new BadLocationException("Node not found", 0);
}
Element temporaryElement = (Element) nodeList.item(childNode);
NodeList temporaryElementNodes = temporaryElement.getChildNodes();
return (String) ((Node) temporaryElementNodes.item(0)).getNodeValue().trim();
}
private String getFilteredDataFromTag(Document doc, String keyname, int childNode, int filter) throws BadLocationException
{
String keyValue = getDataFromTag(doc, keyname, childNode);
keyValue = makeMatchExpression(keyValue, filter);
return keyValue;
}
private String getFilteredDataFromTag(Document doc, String keyname, int filter) throws BadLocationException
{
return getFilteredDataFromTag(doc, keyname, 0, filter);
}
public Bestelling readFromXml()
{
Bestelling bestelling = new Bestelling();
Klant klant = new Klant();
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); //nieuw DocumentBuilderFactory Instance
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); //nieuw DocumentBuilderFactory
Document doc = docBuilder.parse(file); //bestandnaam
doc.getDocumentElement().normalize(); //Normaliseer tekst.
String ordernummer = getFilteredDataFromTag(doc, "ordernummer", FILTER_NUM);
bestelling.setBestelNummer(Integer.decode(ordernummer));
String voornaam = getFilteredDataFromTag(doc, "voornaam", FILTER_WORD);
klant.setVoornaam(voornaam);
String achternaam = getFilteredDataFromTag(doc, "achternaam", FILTER_WORD);
klant.setAchternaam(achternaam);
String adres = getFilteredDataFromTag(doc, "adres", FILTER_WORD);
klant.setAdres(adres);
String postcode = getFilteredDataFromTag(doc, "postcode", FILTER_ZIP).toUpperCase();
klant.setPostcode(postcode);
String plaats = getFilteredDataFromTag(doc, "plaats", FILTER_WORD);
klant.setPlaats(plaats);
bestelling.setKlant(klant);
//Datum ophalen
String datum = getFilteredDataFromTag(doc, "datum", FILTER_DATE);
bestelling.setDatum(datum);
//Artikelnummers ophalen
NodeList artikelnrNodeList = doc.getElementsByTagName("artikelnr"); //Zoek naar<SUF>
for (int i = 0; i < artikelnrNodeList.getLength(); i++)
{
String artikelnr = getFilteredDataFromTag(doc, "artikelnr", i, FILTER_NUM);
bestelling.voegToeArtikel(Integer.decode(artikelnr));
}
}
catch (BadLocationException b){
JOptionPane.showMessageDialog(emPanel, "De lay-out van uw bestelling klopt niet. Gebruik deze lay-out: http://pastebin.com/5DFCrQN1", "Lay-out Error", JOptionPane.ERROR_MESSAGE);
}
catch (SAXParseException err)
{
System.out.println("** Parsing error" + ", line "
+ err.getLineNumber() + ", uri " + err.getSystemId());
System.out.println(" " + err.getMessage());
}
catch (SAXException e)
{
Exception x = e.getException();
((x == null) ? e : x).printStackTrace();
}
catch (Throwable t)
{
t.printStackTrace();
}
return bestelling;
}
public int getAantalArtikelen()
{
return aantalArtikelen;
}
}
|
18167_8 | import java.util.*;
/**
* Klasse: KassaRij
* Maakt een rij voor een kassa aan
*
* @author Patrick Swijgman & Rutger Roffel
* @version 0.1
*/
public class KassaRij {
private LinkedList<Persoon> rij;
/**
* Constructor
*/
public KassaRij() {
// Nieuwe rij maken
rij = new LinkedList<Persoon>();
}
/**
* Persoon sluit achter in de rij aan
* @param persoon
*/
public void sluitAchteraan(Persoon persoon) {
//Zet persoon achter in de ArrayList
rij.add(persoon);
}
/**
* Indien er een rij bestaat, de eerste Persoon uit
* de rij verwijderen en retourneren.
* Als er niemand in de rij staat geeft deze null terug.
* @return Eerste persoon in de rij of null
*/
public Persoon eerstePersoonInRij() {
if(rij.size() == 0)
{
return null;
}
else
{
// Eerste in de rij in een extra variabele zetten
Persoon eerste = rij.get(0);
// Verwijderen uit de rij
rij.remove(0);
// Variabele die eerste stond verwijderen;
return eerste;
}
}
/**
* Methode kijkt of er personen in de rij staan.
* Of er wel of geen rij bestaat
* @return boolean
*/
public boolean erIsEenRij() {
//method body omitted
return(rij.size() > 0);
}
}
| roffel/kantine | KassaRij.java | 460 | // Variabele die eerste stond verwijderen; | line_comment | nl | import java.util.*;
/**
* Klasse: KassaRij
* Maakt een rij voor een kassa aan
*
* @author Patrick Swijgman & Rutger Roffel
* @version 0.1
*/
public class KassaRij {
private LinkedList<Persoon> rij;
/**
* Constructor
*/
public KassaRij() {
// Nieuwe rij maken
rij = new LinkedList<Persoon>();
}
/**
* Persoon sluit achter in de rij aan
* @param persoon
*/
public void sluitAchteraan(Persoon persoon) {
//Zet persoon achter in de ArrayList
rij.add(persoon);
}
/**
* Indien er een rij bestaat, de eerste Persoon uit
* de rij verwijderen en retourneren.
* Als er niemand in de rij staat geeft deze null terug.
* @return Eerste persoon in de rij of null
*/
public Persoon eerstePersoonInRij() {
if(rij.size() == 0)
{
return null;
}
else
{
// Eerste in de rij in een extra variabele zetten
Persoon eerste = rij.get(0);
// Verwijderen uit de rij
rij.remove(0);
// Variabele die<SUF>
return eerste;
}
}
/**
* Methode kijkt of er personen in de rij staan.
* Of er wel of geen rij bestaat
* @return boolean
*/
public boolean erIsEenRij() {
//method body omitted
return(rij.size() > 0);
}
}
|
174774_5 | // ============================================================================
//
// Copyright (C) 2006-2021 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() {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
return ((WSView) inputElement).getWhereConditions().toArray();
}
});
wcListViewer.setLabelProvider(new ILabelProvider() {
@Override
public Image getImage(Object element) {
return null;
}
@Override
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_SENTENCE)) {
text += "contains the sentence";//$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.EMPTY_NULL)) {
text += "Is Empty Or Null";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.FULLTEXTSEARCH)) {
text += "whole content contains";//$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.NONE)) {
text += "";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) {
text += "[or]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) {
text += "[not]";//$NON-NLS-1$
}
return text;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
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() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
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() {
@Override
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() {
@Override
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);
if (path.contains("/")) { //$NON-NLS-1$
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() {
@Override
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() {
@Override
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 {
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
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;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
}
/*********************************
* IXObjectModelListener interface
*/
@Override
public void handleEvent(int type, TreeObject parent, TreeObject child) {
refreshData();
}
}
| rohankumardubey/tmdm-studio-se | main/plugins/org.talend.mdm.workbench/src/com/amalto/workbench/editors/ViewBrowserMainPage.java | 7,984 | // listen to events | line_comment | nl | // ============================================================================
//
// Copyright (C) 2006-2021 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() {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
return ((WSView) inputElement).getWhereConditions().toArray();
}
});
wcListViewer.setLabelProvider(new ILabelProvider() {
@Override
public Image getImage(Object element) {
return null;
}
@Override
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_SENTENCE)) {
text += "contains the sentence";//$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.EMPTY_NULL)) {
text += "Is Empty Or Null";//$NON-NLS-1$
} else if (wc.getOperator().equals(WSWhereOperator.FULLTEXTSEARCH)) {
text += "whole content contains";//$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.NONE)) {
text += "";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.OR)) {
text += "[or]";//$NON-NLS-1$
} else if (wc.getStringPredicate().equals(WSStringPredicate.NOT)) {
text += "[not]";//$NON-NLS-1$
}
return text;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
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() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
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() {
@Override
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() {
@Override
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);
if (path.contains("/")) { //$NON-NLS-1$
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() {
@Override
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() {
@Override
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 {
@Override
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
@Override
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;
}
@Override
public void addListener(ILabelProviderListener listener) {
}
@Override
public void dispose() {
}
@Override
public boolean isLabelProperty(Object element, String property) {
return false;
}
@Override
public void removeListener(ILabelProviderListener listener) {
}
}
/*********************************
* IXObjectModelListener interface
*/
@Override
public void handleEvent(int type, TreeObject parent, TreeObject child) {
refreshData();
}
}
|
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);
}
}
|