text stringlengths 10 2.72M |
|---|
package org.juxtasoftware.resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.juxtasoftware.dao.AlignmentDao;
import org.juxtasoftware.dao.ComparisonSetDao;
import org.juxtasoftware.dao.UserAnnotationDao;
import org.juxtasoftware.dao.WitnessDao;
import org.juxtasoftware.model.Alignment;
import org.juxtasoftware.model.Alignment.AlignedAnnotation;
import org.juxtasoftware.model.AlignmentConstraint;
import org.juxtasoftware.model.ComparisonSet;
import org.juxtasoftware.model.UserAnnotation;
import org.juxtasoftware.model.UserAnnotation.Data;
import org.juxtasoftware.model.Witness;
import org.juxtasoftware.util.QNameFilters;
import org.juxtasoftware.util.RangedTextReader;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ResourceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import eu.interedition.text.Range;
/**
* Resource used to manage user annotations on comparison set witness pairs
*
* @author loufoster
*
*/
@Service
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class UserAnnotationResource extends BaseResource {
@Autowired private ComparisonSetDao comparionSetDao;
@Autowired private WitnessDao witnessDao;
@Autowired private UserAnnotationDao userNotesDao;
@Autowired private QNameFilters filters;
@Autowired private AlignmentDao alignmentDao;
private ComparisonSet set;
private Range range;
private Long baseId;
private Long witnessId;
@Override
protected void doInit() throws ResourceException {
super.doInit();
Long setId = getIdFromAttributes("id");
if (setId == null) {
return;
}
this.set = this.comparionSetDao.find(setId);
if (validateModel(this.set) == false) {
return;
}
// was a base specified?
if ( getQuery().getValuesMap().containsKey("base") ) {
String strVal = getQuery().getValues("base");
try {
this.baseId = Long.parseLong(strVal);
} catch (NumberFormatException e) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid base identifier specified");
}
}
// was a witness specified?
if ( getQuery().getValuesMap().containsKey("witness") ) {
String strVal = getQuery().getValues("witness");
try {
this.witnessId = Long.parseLong(strVal);
} catch (NumberFormatException e) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid base identifier specified");
}
}
// was a range requested?
if (getQuery().getValuesMap().containsKey("range")) {
String rangeInfo = getQuery().getValues("range");
String ranges[] = rangeInfo.split(",");
if (ranges.length == 2) {
this.range = new Range(Integer.parseInt(ranges[0]), Integer.parseInt(ranges[1]));
} else {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Invalid Range specified");
}
}
}
@Post("json")
public Representation create( final String jsonData ) {
UserAnnotation newAnno = parseRequest(jsonData);
if ( newAnno == null ) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return toTextRepresentation("Malformed json payload");
}
newAnno.setSetId(this.set.getId());
if ( newAnno.getBaseId() == null || newAnno.getNotes().size() == 0 || newAnno.getBaseRange() == null ) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return toTextRepresentation("Missing required data in json payload");
}
// Handle updates and additions to existing user annotation
UserAnnotation prior = this.userNotesDao.find(this.set, newAnno.getBaseId(), newAnno.getBaseRange());
if ( prior != null ) {
// newly added group annos have to skip this bit and be added as new at the
// bottom of this function
boolean newAddition = (prior.hasGroupAnnotation() != newAnno.hasGroupAnnotation() &&
prior.hasWitnessAnnotation() != newAnno.hasWitnessAnnotation() );
if ( !newAddition ) {
boolean handled = false;
Data newNote = (Data) newAnno.getNotes().toArray()[0];
for ( Data n : prior.getNotes() ) {
if ( n.getWitnessId().equals(newNote.getWitnessId())) {
n.setText(newNote.getText());
handled = true;
if (n.isGroup()) {
Long groupId = this.userNotesDao.findGroupId(this.set, newAnno.getBaseId(), newAnno.getBaseRange());
this.userNotesDao.updateGroupNote(groupId, newAnno.getGroupNoteContent());
} else {
this.userNotesDao.updateWitnessNote(n.getId(), newNote.getText());
}
}
}
// if the above loop didn't catch the new data
// add it as a separate note
if ( handled == false ) {
this.userNotesDao.addWitnessNote(prior, newNote.getWitnessId(), newNote.getText());
}
return toTextRepresentation("OK");
}
}
// a wholly new user annotation
Long id = this.userNotesDao.create(newAnno);
if ( newAnno.hasGroupAnnotation() ) {
newAnno.setId(id);
newAnno.setGroupId(id);
this.userNotesDao.updateGroupId(newAnno, id);
createReciprocalAnnotations( newAnno );
}
return toTextRepresentation("OK");
}
private UserAnnotation parseRequest(String jsonData) {
JsonParser p = new JsonParser();
JsonObject obj = p.parse(jsonData).getAsJsonObject();
UserAnnotation anno = new UserAnnotation();
anno.setBaseId( obj.get("baseId").getAsLong() );
JsonObject rngObj = obj.get("baseRange").getAsJsonObject();
anno.setBaseRange( new Range( rngObj.get("start").getAsLong(), rngObj.get("end").getAsLong() ));
Data note = UserAnnotation.createNote(obj.get("witnessId").getAsLong(), obj.get("note").getAsString());
note.setGroup(obj.get("isGroup").getAsBoolean());
anno.addNote( note );
return anno;
}
private void createReciprocalAnnotations( UserAnnotation groupAnno ) {
// get all of the diff alignments in the specified range
AlignmentConstraint constraint = new AlignmentConstraint( this.set, groupAnno.getBaseId() );
constraint.setFilter( this.filters.getDifferencesFilter() );
constraint.setRange( groupAnno.getBaseRange() );
List<Alignment> aligns = this.alignmentDao.list( constraint );
// consolidate ranges
Map<Long, Range > witRangeMap = new HashMap<Long, Range>();
for (Alignment align : aligns ) {
AlignedAnnotation witnessAnno = null;
for ( AlignedAnnotation a : align.getAnnotations()) {
if ( a.getWitnessId().equals(groupAnno.getBaseId()) == false) {
witnessAnno = a;
break;
}
}
Range range = witRangeMap.get(witnessAnno.getWitnessId());
if ( range == null ) {
witRangeMap.put(witnessAnno.getWitnessId(), witnessAnno.getRange());
} else {
witRangeMap.put(witnessAnno.getWitnessId(), new Range(
Math.min(range.getStart(), witnessAnno.getRange().getStart()),
Math.max(range.getEnd(), witnessAnno.getRange().getEnd())) );
}
}
for ( Entry<Long, Range> ent : witRangeMap.entrySet() ) {
UserAnnotation a = new UserAnnotation();
Data note = UserAnnotation.createNote(ent.getKey(), groupAnno.getGroupNoteContent() );
note.setGroup(true);
a.addNote( note );
a.setBaseId(ent.getKey());
a.setSetId(this.set.getId());
a.setBaseRange(ent.getValue());
a.setGroupId( groupAnno.getGroupId() );
this.userNotesDao.create(a);
}
}
@Get("html")
public Representation getHtml() {
List<UserAnnotation> ua = getUserAnnotations();
// replace the name of any group notes with the names of
// all witnesses that ahve been annotated
List<Witness> wits = this.comparionSetDao.getWitnesses(this.set);
for (UserAnnotation a : ua ) {
if ( a.hasGroupAnnotation() ) {
for (Data n : a.getNotes() ) {
if ( n.isGroup() ) {
StringBuilder newTitle = new StringBuilder();
for (Long witId : this.userNotesDao.getGroupWitnesses(a.getGroupId()) ) {
for ( Witness w : wits ) {
if ( w.getId().equals(witId)) {
if ( newTitle.length() != 0) {
newTitle.append("<br/>");
}
newTitle.append(w.getName());
break;
}
}
}
n.setWitnessName(newTitle.toString());
}
}
}
}
Map<String,Object> map = new HashMap<String,Object>();
map.put("annotations", ua);
return toHtmlRepresentation("user_annotations.ftl", map,false);
}
@Get("json")
public Representation getJson() {
List<UserAnnotation> ua = getUserAnnotations();
Gson gson = new Gson();
String out = gson.toJson(ua);
return toJsonRepresentation( out );
}
private List<UserAnnotation> getUserAnnotations() {
List<UserAnnotation> ua = this.userNotesDao.list(this.set, this.baseId);
List<Witness> witnesses = this.comparionSetDao.getWitnesses(this.set);
for ( UserAnnotation a : ua ) {
a.setBaseFragment( getBaseFragment(a.getBaseId(), a.getBaseRange()) );
for (Iterator<UserAnnotation.Data> itr = a.getNotes().iterator(); itr.hasNext(); ) {
UserAnnotation.Data note = itr.next();
if ( this.witnessId != null ) {
if ( note.getWitnessId().equals(this.witnessId) == false) {
itr.remove();
continue;
}
}
note.setWitnessName(findName(witnesses, note.getWitnessId()));
}
}
return ua;
}
private String getBaseFragment(Long baseId, Range baseRange) {
final int contextSize=20;
Witness base = this.witnessDao.find(baseId);
Range tgtRange = new Range(
Math.max(0, baseRange.getStart()-contextSize),
Math.min(base.getText().getLength(), baseRange.getEnd()+contextSize));
try {
// read the full fragment
final RangedTextReader reader = new RangedTextReader();
reader.read( this.witnessDao.getContentStream(base), tgtRange );
String frag = reader.toString().trim();
int pos = frag.indexOf(' ');
if ( pos > -1 ) {
frag = "..."+frag.substring(pos+1);
}
pos = frag.lastIndexOf(' ');
if ( pos > -1 ) {
frag = frag.substring(0,pos)+"...";
}
frag = frag.replaceAll("\\n+", " / ").replaceAll("\\s+", " ").trim();
return frag;
} catch (IOException e) {
// couldn't get fragment. skip it for now
return "";
}
}
private String findName(List<Witness> wl, Long id) {
for ( Witness w : wl ) {
if (w.getId().equals(id) ) {
return w.getJsonName();
}
}
return "";
}
@Delete("json")
public Representation deleteUserAnnotation( ) {
// make sure someting exists to be deleted
UserAnnotation tgtAnno = this.userNotesDao.find( this.set, this.baseId, this.range );
if ( tgtAnno == null ) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return toTextRepresentation("No matching user annotation found");
}
// blanket delete of all?
if (this.witnessId == null) {
this.userNotesDao.delete( this.set, this.baseId, this.range );
return toTextRepresentation(""+this.userNotesDao.count(this.set, baseId));
}
// Group annotation delete
if ( this.witnessId == 0 ) {
// Flag attempt to delete group anno where none exist
if (tgtAnno.hasGroupAnnotation() == false ) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
return toTextRepresentation("No matching user annotation found");
}
this.userNotesDao.deleteGroupNote(this.set, tgtAnno.getGroupId());
return toTextRepresentation(""+this.userNotesDao.count(this.set, baseId));
}
// single delete
// Just remove the specified note from the base range.
for (Iterator<UserAnnotation.Data> itr = tgtAnno.getNotes().iterator(); itr.hasNext();) {
UserAnnotation.Data note = itr.next();
if (this.witnessId.equals(note.getWitnessId())) {
itr.remove();
this.userNotesDao.deleteWitnessNote(note.getId());
}
}
return toTextRepresentation(""+this.userNotesDao.count(this.set, baseId));
}
public static class FragmentInfo {
private final String frag;
private final Range r;
public FragmentInfo(Range r, String f) {
this.frag = f;
this.r = new Range(r.getStart(), r.getEnd());
}
public Range getRange() {
return this.r;
}
public String getFragment() {
return this.frag;
}
}
}
|
package com.suntf.pkm.util;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.HttpRequest;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
public class AsyncHttpClient {
private static DefaultHttpClient httpClient;
public static int CONNECTION_TIMEOUT = 2*60*1000;
public static int SOCKET_TIMEOUT = 2*60*1000;
private static ConcurrentHashMap<Activity,AsyncHttpSender> tasks = new ConcurrentHashMap<Activity,AsyncHttpSender>();
public static void sendRequest(
final Activity currentActitity,
final HttpRequest request,
AsyncResponseListener callback) {
sendRequest(currentActitity, request, callback, CONNECTION_TIMEOUT, SOCKET_TIMEOUT);
}
public static void sendRequest(
final Activity currentActitity,
final HttpRequest request,
AsyncResponseListener callback,
int timeoutConnection,
int timeoutSocket) {
InputHolder input = new InputHolder(request, callback);
AsyncHttpSender sender = new AsyncHttpSender();
sender.execute(input);
tasks.put(currentActitity, sender);
}
public static void cancelRequest(final Activity currentActitity){
if(tasks==null || tasks.size()==0) return;
for (Activity key : tasks.keySet()) {
if(currentActitity == key){
AsyncTask<?,?,?> task = tasks.get(key);
if(task.getStatus()!=null && task.getStatus()!=AsyncTask.Status.FINISHED){
Log.i("HTTPTAG", "AsyncTask of " + task + " cancelled.");
task.cancel(true);
}
tasks.remove(key);
}
}
}
public static synchronized HttpClient getClient() {
if (httpClient == null){
//use following code to solve Adapter is detached error
//refer: http://stackoverflow.com/questions/5317882/android-handling-back-button-during-asynctask
BasicHttpParams params = new BasicHttpParams();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
httpClient = new DefaultHttpClient(cm, params);
}
return httpClient;
}
}
|
package moe.tristan.easyfxml.util;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;
/**
* Small DOM-related utils for JavaFX nodes.
*/
public final class Nodes {
private Nodes() {
}
/**
* Centers a node that is inside an enclosing {@link AnchorPane}.
*
* @param node The node to center
* @param marginSize The margins to keep on the sides
*/
public static void centerNode(final Node node, final Double marginSize) {
AnchorPane.setTopAnchor(node, marginSize);
AnchorPane.setBottomAnchor(node, marginSize);
AnchorPane.setLeftAnchor(node, marginSize);
AnchorPane.setRightAnchor(node, marginSize);
}
public static void hideAndResizeParentIf(
final Node node,
final ObservableValue<? extends Boolean> condition
) {
autoresizeContainerOn(node, condition);
bindContentBiasCalculationTo(node, condition);
}
public static void autoresizeContainerOn(
final Node node,
final ObservableValue<?> observableValue
) {
observableValue.addListener((observable, oldValue, newValue) -> node.autosize());
}
public static void bindContentBiasCalculationTo(
final Node node,
final ObservableValue<? extends Boolean> observableValue
) {
node.visibleProperty().bind(observableValue);
node.managedProperty().bind(node.visibleProperty());
}
}
|
/**
*
*/
package solo;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import it.unimi.dsi.fastutil.objects.ObjectList;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import com.graphbuilder.geom.Geom;
/**
* @author kokichi3000
*
*/
public class SteerDriver extends BaseStateDriver<NewCarState,CarControl> {
/**
*
*/
private static final long serialVersionUID = 2390261840257478234L;
private BufferedWriter writer;
/**
*
*/
double brake = 1.0d;
double targetSpeed = 360;
double targetSteer = -0.011;
double maxSpeed = 0;
double smaxSpeed = 0;
double x1,y1,x2,y2,x3,y3;
double avgSpeed = 0;
double savgSpeed = 0;
double savgSteer = 0;
double savgAngle = 0;
double avgSteer = 0;
double avgAngle = 0;
double savgRadius = 0;
double avgRadius = 0;
double distanceRaced = 0;
double speedAtChange = 0;
int no = 0;
double maxDist =0;
double maxAtChange;
double maxRPM;
double px = -10000;
double py = -10000;
int currentGear = 2;
public static final int n = 1;
// public static double[] gearUp = {0,8657-2000,8746,8902,8736,8427,10000};
// public static double[] gearDown = {0,2094,6300,6350,6300,6300,6300};
// public static double[] gearUp = {0,8780,8730,8000,8900,8900,10000};//3117.03
public static double[] gearUp = new double[]{0,7000,8400,7800,7800,9000,10000};//3117.03
// public static double[] gearUp = {0,8910,8840,8810,8610,8460,10000};//3117.03
// public static double[] gearUp = new double[]{0,8800,8800,8600,8600,8900,10000};//3117.03
public static double[] minRPM = {9000,9000,9000,9000,9000,9000,9000};
public static double[] maxRPMAtGear = {0,0,0,0,0,0,0};
public static double[] speedChange = {0,0,0,0,0,0,0};
public static double[] gearDown = {0,0,0,0,0,0,0};
public SteerDriver() {
// TODO Auto-generated constructor stub
File file = new File("rpm-results-1st.txt");
boolean exists = file.exists();
ignoredExisting = true;
storeNewState = false;
setRepeatNum(n);
try{
writer = new BufferedWriter(new FileWriter(file,true));
if (!exists) {
// writer.write("Speed\t\tAngle\t\tSteer\t\tRadius");
writer.write("Steer\t\tGear\t\tRPM\t\tSpeed\t\tDistance\t\tMin RPM\t\tMax speed\t\tRadius");
writer.newLine();
}
writer.flush();
} catch (Exception e){
e.printStackTrace();
}//*/
}
/**
* @param name
*/
public SteerDriver(String name) {
super(name);
ignoredExisting = true;
storeNewState = false;
// TODO Auto-generated constructor stub
File file = new File(name+"-brake-results.txt");
boolean exists = file.exists();
ignoredExisting = true;
storeNewState = false;
setRepeatNum(n);
try{
writer = new BufferedWriter(new FileWriter(file,true));
if (!exists) {
writer.write("Gear\t\tSpeed\t\tAngle\t\tSteer\t\tRadius");
writer.newLine();
}
writer.flush();
} catch (Exception e){
e.printStackTrace();
}//*/
}
@Override
public void init() {
// TODO Auto-generated method stub
avgSteer = 0;
avgSpeed = 0;
avgAngle = 0;
avgRadius = 0;
no = 0;
}
boolean ok =false;
@Override
public ObjectList<CarControl> drive(State<NewCarState, CarControl> state) {
// TODO Auto-generated method stub
double steer = state.state.getAngleToTrackAxis()/SimpleDriver.steerLock-state.state.getTrackPos();
double speed = state.state.getSpeed();
ObjectList<CarControl> ol = new ObjectArrayList<CarControl>();
int gear = state.state.getGear();
double brake = 0.0d;
// double dist = state.state.getDistanceRaced();
double rpm = state.state.getRpm();
steer = targetSteer;
if (minRPM[gear]>rpm) minRPM[gear] = rpm;
if (maxRPMAtGear[gear]<rpm) maxRPMAtGear[gear] = rpm;
if (rpm>gearUp[gear] && gear<=currentGear){
gear++;
if (gear==currentGear+1) {
speedAtChange = speed;
}
} else if (rpm<=gearDown[gear])
gear--;
if (maxSpeed<speed) maxSpeed = speed;
// System.out.println(rpm+" "+maxSpeed+" "+gear);
/*if (state.state.getSpeed()>=296.8 || (state.state.gear==6 && speed>=291)){
gear = 6;
System.out.println(rpm+" "+speed+" "+gear);
} else if (state.state.getSpeed()>=225 || (state.state.gear==5 && speed>=221)){
gear = 5;
System.out.println(rpm+" "+speed+" "+gear);
} else if (state.state.getSpeed()>=176 || (state.state.gear==4 && speed>=174)){
gear = 4;
System.out.println(rpm+" "+speed+" "+gear);
} else if (state.state.getSpeed()>=126 || (state.state.gear==3 && speed>=125)){
gear = 3;
System.out.println(rpm+" "+speed+" "+gear);
} else if (state.state.getSpeed()>=83 || (state.state.gear==2 && speed>=82)){
gear = 2;
System.out.println(rpm+" "+speed+" "+gear);
} else {
gear = 1;
System.out.println(rpm+" "+speed+" "+gear);
}//*/
double acc = 0;
acc = 1;
// distanceRaced = dist;
if (px!=-10000 || py!=-10000)
distanceRaced += Geom.distance(px, py, state.state.posX, state.state.posY);
px = state.state.posX;
py = state.state.posY;
// System.out.println(distanceRaced+" "+dist);
// if (speed<targetSpeed)
// acc = 1.0d;
// else acc = 2/(1+Math.exp(speed - targetSpeed-1)) - 1;
double time = state.state.getLastLapTime();
if (time>=45 && time<=45.05){
x1 = state.state.posX;
y1 = state.state.posY;
}
// if (dist>=700)
// steer = targetSteer;
if (time>=50 && time<=50.05){
x2 = state.state.posX;
y2 = state.state.posY;
}
if (time>53){
x3 = state.state.posX;
y3 = state.state.posY;
double[] r = new double[3];
Geom.getCircle(x1, y1, x2, y2, x3, y3, r);
no++;
avgSpeed += speed;
avgAngle += state.state.angle;
avgSteer += steer;
avgRadius += Math.sqrt(r[2]);
}
// if (speed>=110) gear = 3;
// steer = targetSteer;
CarControl cc = new CarControl(acc,brake,gear,steer,0);
ol.add(cc);
return ol;
}
public void reset(){
currentGear=2;
targetSteer += (targetSpeed>=-0.025) ? 0.0005 : (targetSteer>=-0.1) ? 0.005 : 0.05;
maxDist = 0;
distanceRaced = 0;
for (int i=0;i<minRPM.length;++i){
minRPM[i] = 9000;
maxRPMAtGear[i] = 0;
}
maxSpeed = 0;
avgSpeed = 0;
gearUp = new double[]{0,7000,8400,7800,7800,9000,10000};//3117.03
TurnDriver.radius = round(savgRadius/no);
}
@Override
public CarControl restart() {
// TODO Auto-generated method stub
// targetSpeed += 0;
// targetSteer += 0.09;
// System.out.println(currentGear+"\t\t"+gearUp[currentGear]+"\t\t"+speedAtChange+"\t\t"+distanceRaced);
px = -10000;
py = -10000;
if (maxDist<distanceRaced){
maxDist = distanceRaced;
maxAtChange = speedAtChange;
maxRPM = gearUp[currentGear];
speedChange[currentGear] = speedAtChange;
smaxSpeed = avgSpeed;
savgSpeed = avgSpeed;
// savgSteer = savgSteer;
savgRadius = avgRadius;
savgAngle = avgAngle;
if (currentGear>2 && Math.abs(speedAtChange-speedChange[currentGear-1])==0){
reset();
return new CarControl(0,0,0,0,1);
}
}
// System.out.println(new DoubleArrayList(gearUp));
// System.out.println(new DoubleArrayList(maxRPMAtGear));
// System.out.println();
// if (maxRPMAtGear[currentGear]<gearUp[currentGear]){
// try{
// System.out.println(targetSteer+"\t\t"+currentGear+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+round(maxDist)+"\t\t"+minRPM[currentGear]+"\t\t"+round(savgSpeed/no)+"\t\t"+round(savgRadius/no));
// writer.write(targetSteer+"\t\t"+currentGear+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+round(maxDist)+"\t\t"+minRPM[currentGear]+"\t\t"+round(savgSpeed/no)+"\t\t"+round(savgRadius/no));
// writer.newLine();
// writer.flush();//*/
// } catch (Exception e){
// e.printStackTrace();
// }
// reset();
// return new CarControl(0,0,0,0,1);
// }
if (gearUp[currentGear]>8900 ){
try{
// System.out.println(round(avgSpeed/no)+"\t\t"+round(avgAngle/no)+"\t\t"+round(avgSteer/no)+"\t\t"+round(avgRadius/no)+"\t\t"+distanceRaced);
// writer.write(round(avgSpeed/no)+"\t\t"+round(avgAngle/no)+"\t\t"+round(avgSteer/no)+"\t\t"+round(avgRadius/no)+"\t\t"+distanceRaced);
// System.out.println(gearUp[1]+"\t\t"+speedAtChange+"\t\t"+distanceRaced);
// writer.write(gearUp[1]+"\t\t"+speedAtChange+"\t\t"+distanceRaced);
System.out.println(targetSteer+"\t\t"+currentGear+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+round(maxDist)+"\t\t"+minRPM[currentGear]+"\t\t"+round(savgSpeed/3.6/no)+"\t\t"+round(savgRadius/no));
writer.write(targetSteer+"\t\t"+currentGear+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+round(maxDist)+"\t\t"+minRPM[currentGear]+"\t\t"+round(savgSpeed/3.6/no)+"\t\t"+round(savgRadius/no));
writer.newLine();
writer.flush();//*/
pathToTarget = null;
current = null;
action = null;
gearUp[currentGear] = maxRPM;
currentGear++;
if (currentGear>6) {
reset();
}
distanceRaced = 0;
} catch (Exception e){
e.printStackTrace();
}
maxDist = 0;
maxSpeed = 0;
// gearUp[currentGear] = 8300;
return new CarControl(0,0,0,0,1);
}
gearUp[currentGear] += 200;
distanceRaced = 0;
maxSpeed = 0; //
return new CarControl(0,0,0,0,1);
}
@Override
public CarControl shutdown() {
// TODO Auto-generated method stubrt
try{
// System.out.println(round(avgSpeed/no)+"\t\t"+round(avgAngle/no)+"\t\t"+round(avgSteer/no)+"\t\t"+round(avgRadius/no)+"\t\t"+distanceRaced);
// writer.write(round(avgSpeed/no)+"\t\t"+round(avgAngle/no)+"\t\t"+round(avgSteer/no)+"\t\t"+round(avgRadius/no)+"\t\t"+distanceRaced);
// System.out.println(gearUp[1]+"\t\t"+speedAtChange+"\t\t"+distanceRaced);
// writer.write(gearUp[1]+"\t\t"+speedAtChange+"\t\t"+distanceRaced);
// for (int i=0;i<6;++i)
// System.out.println(gearUp[i]);
// System.out.println(targetSteer+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+maxDist);
// writer.write(targetSteer+"\t\t"+maxRPM+"\t\t"+maxAtChange+"\t\t"+maxDist);
// writer.newLine();
writer.close();
// System.out.println((current.state.getDistanceRaced()-start.state.getDistanceRaced())+" "+current.state.getDistanceRaced()+" "+current.state.getCurLapTime());
//save("all-speed.txt");
/*ObjectSortedSet<CarRpmState> ss = map.keySet();
for (CarRpmState st:ss){
if (st.getSpeed()<=285) map.remove(st);
}
//
save("speed-fifth-init.txt");
// System.out.println(current.num);
// save("rpm.txt",current);
/*RPMDriver msd = new RPMDriver("speed-snd-init.txt");
ObjectSortedSet<CarRpmState> s = msd.map.keySet();
for (CarRpmState st:s){
System.out.println(st.getSpeed());
}
System.out.println();//*/
} catch (Exception e){
e.printStackTrace();
}
return new CarControl(0,0,0,0,2);
}
@Override
public boolean shutdownCondition(State<NewCarState, CarControl> state){
return (targetSteer>=-0.005 && stopCondition(state));
}
@Override
public boolean stopCondition(State<NewCarState, CarControl> state) {
// TODO Auto-generated method stub
//System.out.println(state.state.getLastLapTime());
//System.out.println(Runtime.getRuntime().freeMemory());
//System.out.println(state.state.getLastLapTime());
return (state.state.getLastLapTime()>=60);
// return (state.num>=target.num+1);
// return (start!=null) ? (state.num>=start.num+50): (state.num>=3);
// return (state.num>start.num && state.state.getSpeed()<0.5);
// return (state.state.getDistanceRaced()>2000);
}
public static double round(double v){
return ((int)(v*1000))/1000.0d;
}
@Override
public void storeSingleAction(NewCarState input, CarControl action,
NewCarState output) {
// TODO Auto-generated method stub
System.out.println(input+" "+action+" "+output);
try{
if (input!=null && action!=null && output!=null){
double[] wheels = input.getWheelSpinVel();
double inputAvg = 0;
for (int i=0;i<wheels.length;++i)
inputAvg+=wheels[i];
inputAvg /=wheels.length;
wheels = output.getWheelSpinVel();
double outputAvg = 0;
for (int i=0;i<wheels.length;++i)
outputAvg+=wheels[i];
outputAvg /=wheels.length;
System.out.println(input.getSpeed()+"\t\t"+new DoubleArrayList(input.getWheelSpinVel())+"\t\t"+round(action.getBrake())+"\t\t"+output.getSpeed()+"\t\t"+new DoubleArrayList(output.getWheelSpinVel())+"\t\t"+output.getDistanceRaced());
writer.write(round(input.getSpeed())+"\t\t"+round(action.getBrake())+"\t\t"+round(output.getSpeed()));
writer.newLine();
writer.flush();
}
} catch (Exception e){
e.printStackTrace();
}//*/
}
}
|
package com.gxtc.huchuan.ui.circle.home;
import android.util.Log;
import android.view.View;
import com.gxtc.commlibrary.utils.ErrorCodeUtil;
import com.gxtc.huchuan.bean.CircleCommentBean;
import com.gxtc.huchuan.bean.CircleHomeBean;
import com.gxtc.huchuan.bean.CommentConfig;
import com.gxtc.huchuan.bean.ThumbsupVosBean;
import com.gxtc.huchuan.data.EssenceDymicListRepository;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.http.ApiCallBack;
import java.util.HashMap;
import java.util.List;
/**
* Describe:
* Created by ALing on 2017/6/8 .
*/
public class EssenceDymicListPresenter implements EssenceDymicListContract.Presenter {
private EssenceDymicListContract.Source mData;
private EssenceDymicListContract.View mView;
private int start = 0;
private int groupId;
public EssenceDymicListPresenter(int groupId,EssenceDymicListContract.View mView) {
this.mView = mView;
this.mView.setPresenter(this);
this.groupId = groupId;
mData = new EssenceDymicListRepository();
}
@Override
public void start() {
}
@Override
public void destroy() {
mData.destroy();
mView = null;
}
@Override
public void getEssenceList(final boolean isRefresh) {
if (isRefresh) {
start = 0;
if (UserManager.getInstance().isLogin()) {
}
} else {
mView.showLoad();
}
mData.getEssenceList(groupId, start, new ApiCallBack<List<CircleHomeBean>>() {
@Override
public void onSuccess(List<CircleHomeBean> data) {
if(mView == null) return;
mView.showLoadFinish();
if (data == null || data.size() == 0) {
mView.showEmpty();
return;
}
if (isRefresh) {
mView.showRefreshFinish(data);
} else {
mView.showEssenceList(data);
}
}
@Override
public void onError(String errorCode, String message) {
ErrorCodeUtil.handleErr(mView, errorCode, message);
}
});
}
@Override
public void loadMrore() {
start += 15;
mData.getEssenceList(groupId, start, new ApiCallBack<List<CircleHomeBean>>() {
@Override
public void onSuccess(List<CircleHomeBean> data) {
if(mView == null) return;
if (data == null || data.size() == 0) {
mView.showNoMore();
return;
}
mView.showLoadMore(data);
}
@Override
public void onError(String errorCode, String message) {
mView.showError(message);
}
});
}
@Override
public void addComment(String content, final CommentConfig commentConfig,int groupId) {
mData.addComment(content, commentConfig.groupInfoId,groupId, new ApiCallBack<CircleCommentBean>() {
@Override
public void onSuccess(CircleCommentBean data) {
if(mView == null) return;
if (data != null) {
mView.update2AddComment(commentConfig.circlePosition, data);
}
}
@Override
public void onError(String errorCode, String message) {
}
});
}
@Override
public void addCommentReply(String comment, final CommentConfig commentConfig) {
HashMap<String, String> map = new HashMap<>();
map.put("token", UserManager.getInstance().getToken());
map.put("groupInfoId", "" + commentConfig.groupInfoId);
map.put("comment", comment);
map.put("userCode", commentConfig.targetUserCode);
mData.addCommentReply(map, new ApiCallBack<CircleCommentBean>() {
@Override
public void onSuccess(CircleCommentBean data) {
if(mView == null) return;
mView.update2AddComment(commentConfig.circlePosition, data);
}
@Override
public void onError(String errorCode, String message) {
}
});
}
@Override
public void support(String token, final CommentConfig comomentConfig) {
mData.support(token, comomentConfig.groupInfoId, new ApiCallBack<ThumbsupVosBean>() {
@Override
public void onSuccess(ThumbsupVosBean data) {
if(mView == null) return;
if (data.getUserCode() == null) {
//删除点赞
mView.update2DeleteFavort(comomentConfig.circlePosition, null);
} else {
//添加点赞
mView.update2AddFavorite(comomentConfig.circlePosition, data);
}
}
@Override
public void onError(String errorCode, String message) {
}
});
}
@Override
public void showEditTextBody(CommentConfig commentConfig) {
if (mView != null) {
mView.updateEditTextBodyVisible(View.VISIBLE, commentConfig);
}
}
@Override
public void getMoreComment(final CommentConfig commentConfig) {
mData.getMoreComment(commentConfig.commentCount, commentConfig.groupInfoId,
new ApiCallBack<List<CircleCommentBean>>() {
@Override
public void onSuccess(List<CircleCommentBean> data) {
if(mView == null) return;
mView.update2AddComment(commentConfig.circlePosition, data);
}
@Override
public void onError(String errorCode, String message) {
}
});
}
@Override
public void removeComment(final CommentConfig commentConfig) {
if (UserManager.getInstance().isLogin()) {
mData.removeComment(UserManager.getInstance().getToken(), commentConfig.groupInfoId,
new ApiCallBack<Void>() {
@Override
public void onSuccess(Void data) {
if(mView == null) return;
mView.update2DeleteCircle(commentConfig.groupInfoId);
}
@Override
public void onError(String errorCode, String message) {}
});
}
}
@Override
public void removeCommentItem(final CommentConfig commentConfig) {
if (UserManager.getInstance().isLogin()) {
mData.removeCommentItem(UserManager.getInstance().getToken(), commentConfig.commentId,
new ApiCallBack<Void>() {
@Override
public void onSuccess(Void data) {
if(mView == null) return;
mView.update2DeleteComment(commentConfig.circlePosition, commentConfig.commentId);
}
@Override
public void onError(String errorCode, String message) {}
});
}
}
}
|
package enshud.s4.ilgenerator;
import java.util.LinkedList;
import enshud.interlanguage.ilstatement.AbstractILStatement;
import enshud.symboltable.SymbolTableStack;
public class ILCodeBlock extends LinkedList<AbstractILStatement> {
// 3番地コードの環境
public SymbolTableStack symbolTableStack;
public ILCodeBlock(SymbolTableStack symbolTableStack) {
this.symbolTableStack = symbolTableStack;
}
@Override
public String toString() {
String res = "";
for (var statement : this)
res += statement.toString() + "\n";
return res;
}
}
|
/**
* Write a description of class Simulator here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Simulator
{
public static void main(String [] args)
{
Randomizer tester = new Randomizer();
final int TRIES = 100;
for (int i = 1; i <= TRIES; i++)
{
int n = tester.cast();
System.out.print(n + " ");
tester.add(n);
}
System.out.println();
System.out.println("The Average of the values is " + tester.getAverage());
System.out.println("The Maximum of the values is " + tester.getMaximum());
}
}
|
package com.dream.net.request;
import org.json.JSONObject;
public abstract class BaseRequest {
public abstract String getTag();
public abstract String getUrl();
public abstract JSONObject getJsonParam();
}
|
package com.subversions.process;
import java.util.ArrayList;
public class Commit implements Comparable<Commit> {
public String commitID;
public String developerName;
public String commitDate;
public String commitText;
public ArrayList<CommitFiles> filePath = new ArrayList<CommitFiles>();
public Commit(String commitID, String developerName, String commitDate, String commitText,
ArrayList<CommitFiles> filePath) {
this.commitID = commitID;
this.developerName = developerName;
this.commitDate = commitDate;
this.commitText = commitText;
this.filePath.addAll(filePath);
}
public int compareTo(Commit o) {
return o.filePath.size() - this.filePath.size();
}
// Get prev commit info by current commit ID
public Commit prevCommit(ArrayList<Commit> commitList) {
Commit previousCommitID = null;
for (int i = 0; i < commitList.size(); i++) {
if (commitList.get(i).commitID.contains(this.commitID)) {
return previousCommitID;
}
previousCommitID = commitList.get(i);
}
return previousCommitID;
}
// Get commit info by ID
public Commit commitFullInfo(ArrayList<Commit> commitList) {
Commit previousCommitID = null;
for (int i = 0; i < commitList.size(); i++) {
if (commitList.get(i).commitID.contains(this.commitID)) {
return commitList.get(i);
}
}
return previousCommitID;
}
public void print() {
System.out.println("---------");
System.out.println("commitID: " + commitID);
System.out.println("commitID: " + developerName);
System.out.println("commitID: " + commitDate);
System.out.println("commitID: " + commitText);
for (CommitFiles file : filePath) {
System.out.println(file.firstFile);
}
}
}
|
/**
*
*/
/**
* @author Aloy A Sen
*
*/
package layouts_JAVA; |
/**
* Copyright (C) 2016 - 2030 youtongluan.
*
* 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.yx.http;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Objects;
import java.util.Set;
import org.yx.conf.AppInfo;
public final class HttpSettings {
public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
private static int errorHttpStatus;
private static Set<String> fusing = Collections.emptySet();
private static long httpSessionTimeoutInMs;
private static boolean cookieEnable;
public static int getErrorHttpStatus() {
return errorHttpStatus;
}
public static void setErrorHttpStatus(int errorHttpStatus) {
HttpSettings.errorHttpStatus = errorHttpStatus;
}
public static Set<String> getFusing() {
return fusing;
}
public static long getHttpSessionTimeoutInMs() {
return httpSessionTimeoutInMs;
}
public static boolean isCookieEnable() {
return cookieEnable;
}
public static boolean isUploadEnable() {
return AppInfo.getBoolean("sumk.http.upload.enable", true);
}
public static void setCookieEnable(boolean cookieEnable) {
HttpSettings.cookieEnable = cookieEnable;
}
public static void setFusing(Set<String> fusing) {
HttpSettings.fusing = Objects.requireNonNull(fusing);
}
public static void setHttpSessionTimeoutInMs(long httpSessionTimeoutInMs) {
HttpSettings.httpSessionTimeoutInMs = httpSessionTimeoutInMs;
}
}
|
package com.infohold.els.web.rest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.infohold.bdrp.Constants;
import com.infohold.bdrp.org.model.Org;
import com.infohold.bdrp.tools.security.SecurityUtil;
import com.infohold.bdrp.tools.security.impl.SecurityConstants;
import com.infohold.core.exception.BaseException;
import com.infohold.core.manager.GenericManager;
import com.infohold.core.utils.DateUtils;
import com.infohold.core.utils.JSONUtils;
import com.infohold.core.utils.StringUtils;
import com.infohold.core.web.MediaTypes;
import com.infohold.core.web.rest.BaseRestController;
import com.infohold.core.web.utils.Result;
import com.infohold.core.web.utils.ResultUtils;
import com.infohold.el.base.model.Notice;
import com.infohold.el.base.model.User;
import com.infohold.el.base.service.NoticeService;
import com.infohold.el.base.utils.excel.PoiCallback;
import com.infohold.el.base.utils.excel.PoiReader;
import com.infohold.el.base.utils.excel.PoiWriter;
import com.infohold.els.model.PerMng;
import com.infohold.els.model.StubBatch;
import com.infohold.els.model.StubBatchinfo;
import com.infohold.els.model.StubPreview;
import com.infohold.els.model.StubTemplateinfo;
@RestController
@RequestMapping("/els/stubbatch")
public class StubBatchRestController extends BaseRestController {
@Autowired
private GenericManager<StubBatch, String> stubBatchManager;
@Autowired
private GenericManager<StubBatchinfo, String> stubBatchinfoManager;
@Autowired
private GenericManager<StubPreview, String> stubPreviewManager;
@Autowired
private GenericManager<PerMng, String> perMngManager;
@Autowired
private GenericManager<StubTemplateinfo, String> stubTemplateinfoManager;
@Autowired
private GenericManager<User, String> userManager;
@Autowired
private GenericManager<Notice, String> noticeManager;
@Autowired
private NoticeService noticeService;
/**
* 5.3.8 新增工资明细批次【ELS_STUB_008】
*
* @param data
* @return
*/
@RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forCreate(@RequestBody String data) {
log.info("新增工资批次,输入数据为:【" + data + "】");
if (StringUtils.isEmpty(data)) {
throw new BaseException("输入数据为空!");
}
StubBatch in = JSONUtils.deserialize(data, StubBatch.class);
if (null == in) {
throw new BaseException("输入数据为空!");
}
String orgId = ((Org) this.getSession().getAttribute(Constants.ORG_KEY)).getId();
in.setOrgId(orgId);
in.setBatchNo( genBatchNo(in.getMonth(),in.getOrgId()));
in.setState(StubBatch.STATUS_NOTYET);
in.setAmount(new BigDecimal(0));
in.setNum(0);
in = this.stubBatchManager.save(in);
return ResultUtils.renderSuccessResult(in);
}
/**
* 5.3.4 提交工资批次【ELS_STUB_004】
*
* @param data
* @return
*/
@RequestMapping(value = "/update", method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8)
public Result forUpdate(@RequestBody String data) {
log.info("保存/提交批次,输入数据为:【" + data + "】");
if (StringUtils.isEmpty(data)) {
throw new BaseException("输入数据为空!");
}
StubBatch tin = JSONUtils.deserialize(data, StubBatch.class);
if (null == tin) {
throw new BaseException("输入数据为空!");
}
String orgId = ((Org) this.getSession().getAttribute(Constants.ORG_KEY)).getId();
tin.setOrgId(orgId);
if (!StubBatch.hasStatus(tin.getState())) {
throw new BaseException("状态值不存在!");
}
log.info("tin.getId"+tin.getTemplateId());
//计算总金额,总人次
String vldJql = "from StubBatchinfo where batchId = ?";
List<StubBatchinfo> lsout= this.stubBatchinfoManager.find(vldJql, tin.getId());
float sumAmount=(float) 0.00;
int seqNo = getPayItemSeqnoByTemplate(tin.getTemplateId());
if( seqNo < 0 ) throw new BaseException("获取实发工资序号失败!");
for( StubBatchinfo item:lsout ){
try {
sumAmount += Float.parseFloat(StubBatchinfo.class.getMethod("getItem"+seqNo).invoke(item).toString());
} catch (Exception e) {
e.printStackTrace();
}
}
tin.setAmount(BigDecimal.valueOf(sumAmount));
tin.setNum(lsout.size());
if( StringUtils.equals(tin.getState(), "1") ) {
tin.setSubmitTime(DateUtils.getCurrentDateTimeStr());
sendStubMsg(tin.getId());
}
this.stubBatchManager.save(tin);
return ResultUtils.renderSuccessResult(tin);
}
/**
* 5.3.3 删除工资批次【ELS_STUB_003】
*
* @param data
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8)
public Result forDelete(@PathVariable("id") String id) {
log.info("删除工资批次,输入数据为:" + id);
if (StringUtils.isEmpty(id)) {
throw new BaseException("批次ID不可为空!");
}
StubBatch tin = this.stubBatchManager.get(id);
if (null == tin) {
throw new BaseException("删除批次不存在!");
}
String vldJql = "delete from ELS_STUB_BATCHINFO where batch_Id=?";
this.stubBatchinfoManager.executeSql(vldJql, id);
this.stubBatchManager.delete(id);
return ResultUtils.renderSuccessResult();
}
/**
* ELS_STUB_001 查询工资批次列表
* ELS_STUB_009 查询工资明细批次信息
* ELS_STUB_002 导出所选年工资批次列表
*
* @param data
* @return
*/
@RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forList(@RequestParam(value="year") String year ) {
log.info("根据年份查询工资批次列表,输入年为:【" + year + "】");
String orgId = ((Org) this.getSession().getAttribute(Constants.ORG_KEY)).getId();
if (StringUtils.isEmpty(orgId)) {
throw new BaseException("机构号不可为空!");
}
if (StringUtils.isEmpty(year)) {
throw new BaseException("年份不可为空!");
}
String vldJql = "from StubBatch where month like ? and orgId = ? order by month desc,batchNo+0 desc";
List<StubBatch> lstout = this.stubBatchManager.find(vldJql, year + "%", orgId);
return ResultUtils.renderSuccessResult(lstout);
}
/**
* ELS_STUB_005 工资明细文件导入
*
* @param data
* @return
*/
@RequestMapping(value = "/import", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Result forStubFileImport(
@RequestParam("note") String note,
@RequestParam("month") String month,
@RequestParam("templateId") String templateId,
@RequestParam("template") String template,
@RequestParam("file") MultipartFile file) {
String orgId = ((Org) this.getSession().getAttribute(Constants.ORG_KEY)).getId();
log.info("工资明细文件导入,输入参数:【" + orgId + month + "】");
//新增批次
StubBatch in = new StubBatch();
in.setBatchNo( genBatchNo(month, orgId) );
in.setState(StubBatch.STATUS_NOTYET);
in.setOrgId(orgId);
in.setTemplateId(templateId);
in.setTemplate(template);
in.setMonth(month);
in.setNote(note);
in = this.stubBatchManager.save(in);
//读取文件
if (file.isEmpty()){
this.stubBatchManager.delete(in.getId());
throw new BaseException("输入数据为空!");
}
try {
PoiReader pr = new PoiReader();
//验证templateId是否相符
if( !pr.checkData(file.getOriginalFilename(), file.getInputStream(), 1, in.getTemplateId()) ){
this.stubBatchManager.delete(in.getId());
throw new BaseException("导入文件模板ID不符!");
}
pr.setCallback(new PoiCallback(){
@Override
public boolean HandleDataRow(Row row, Object obj)throws Exception{
if (row == null) {
return false;
}
StubPreview model = new StubPreview();
StubBatch in = (StubBatch)obj;
try {
PoiReader pr = new PoiReader();
model.setBatchId(in.getId());
model.setBatchNo(in.getBatchNo());
model.setMonth(in.getMonth());
model.setTemplateId(in.getTemplateId());
model.setTemplate(in.getTemplate());
model.setName(pr.getCellValue(row, 2).toString());
model.setIdNo(pr.getCellValue(row, 1).toString());
model.setNote(pr.getCellValue(row, 3).toString());
String idNoEnc = SecurityUtil.encryptData(SecurityConstants.DATA_TYPE_ID, Constants.APP_SUPER_ID, model.getIdNo(), SecurityConstants.KEY_MASTER_KEY_NAME, null).split(SecurityConstants.ARRAY_TOSTRING_SEP)[0];
PerMng pm = perMngManager.findOne("from PerMng where idNoEnc=? and name=?", idNoEnc,model.getName());
if(pm==null)
throw new BaseException("人员表不存在该人员<"+model.getName()+"-"+model.getIdNo()+">!");
model.setPerId(pm.getId());
//30个工资项
model.setItem1 (pr.getCellValue(row, 4 ).toString());
model.setItem2 (pr.getCellValue(row, 5 ).toString());
model.setItem3 (pr.getCellValue(row, 6 ).toString());
model.setItem4 (pr.getCellValue(row, 7 ).toString());
model.setItem5 (pr.getCellValue(row, 8 ).toString());
model.setItem6 (pr.getCellValue(row, 9 ).toString());
model.setItem7 (pr.getCellValue(row, 10 ).toString());
model.setItem8 (pr.getCellValue(row, 11 ).toString());
model.setItem9 (pr.getCellValue(row, 12 ).toString());
model.setItem10 (pr.getCellValue(row, 13 ).toString());
model.setItem11 (pr.getCellValue(row, 14 ).toString());
model.setItem12 (pr.getCellValue(row, 15 ).toString());
model.setItem13 (pr.getCellValue(row, 16 ).toString());
model.setItem14 (pr.getCellValue(row, 17 ).toString());
model.setItem15 (pr.getCellValue(row, 18 ).toString());
model.setItem16 (pr.getCellValue(row, 19 ).toString());
model.setItem17 (pr.getCellValue(row, 20 ).toString());
model.setItem18 (pr.getCellValue(row, 21 ).toString());
model.setItem19 (pr.getCellValue(row, 22 ).toString());
model.setItem20 (pr.getCellValue(row, 23 ).toString());
model.setItem21 (pr.getCellValue(row, 24 ).toString());
model.setItem22 (pr.getCellValue(row, 25 ).toString());
model.setItem23 (pr.getCellValue(row, 26 ).toString());
model.setItem24 (pr.getCellValue(row, 27 ).toString());
model.setItem25 (pr.getCellValue(row, 28 ).toString());
model.setItem26 (pr.getCellValue(row, 29 ).toString());
model.setItem27 (pr.getCellValue(row, 30 ).toString());
model.setItem28 (pr.getCellValue(row, 31 ).toString());
model.setItem29 (pr.getCellValue(row, 32 ).toString());
model.setItem30 (pr.getCellValue(row, 33 ).toString());
stubPreviewManager.save(model);
System.out.println(model.toString());
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
});
String ret = pr.importFile(file.getOriginalFilename(), file.getInputStream(), true, in);
log.info(ret);
} catch (IOException e) {
e.printStackTrace();
}
return ResultUtils.renderSuccessResult(in);
}
@RequestMapping(value = "/export/{orgId}/{year}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
public Result forStubFileExport(HttpServletRequest request,
HttpServletResponse response,
@PathVariable("year") String year) {
String orgId = ((Org) this.getSession().getAttribute(Constants.ORG_KEY)).getId();
if (StringUtils.isEmpty(orgId)) {
throw new BaseException("组织ID为空!");
}
if (StringUtils.isEmpty(year)) {
throw new BaseException("导出年份为空!");
}
try {
String jql = "from StubBatch where substring(month,1,4) = ? and orgId = ? order by month asc ";
List<StubBatch> list = stubBatchManager.find(jql, year, orgId);
byte[] fileNameByte = (year+"年工资批次信息.xls").getBytes("GBK");
String filename = new String(fileNameByte, "ISO8859-1");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="+ filename);
exportStubBatch(response.getOutputStream(), list, year);
} catch (Exception e) {
e.printStackTrace();
}
return ResultUtils.renderSuccessResult();
}
@SuppressWarnings("unchecked")
private String genBatchNo(String month, String orgId){
//查询批次编号
String sql = "SELECT MAX(BATCH_NO + 0) FROM ELS_STUB_BATCH WHERE MONTH = ? AND ORG_ID = ? ";
List<Double> maxBacthNo = (List<Double>) stubBatchManager.findBySql(sql, month, orgId);
int batchNo = 1;//初始化默认批次号
Double bacthNoDouble = 0.0;
if(maxBacthNo != null && maxBacthNo.size() > 0){
log.info(maxBacthNo.get(0));
bacthNoDouble = maxBacthNo.get(0)==null?0:maxBacthNo.get(0);
}
batchNo = (int) (bacthNoDouble+1);
return batchNo+"";
}
private int getPayItemSeqnoByTemplate(String id) {
int seqNo=-1;
String vldJql = "from StubTemplateinfo where templateId = ? order by seqNo desc";
List<StubTemplateinfo> out = this.stubTemplateinfoManager.find(vldJql, id);
if(out.size()>0)
seqNo = out.get(0).getSeqNo();
log.info("seqno:"+seqNo);
return seqNo;
}
private void sendStubMsg(String batchId) {
try {
String hql = "from StubBatchinfo where batchId = ?";
List<StubBatchinfo> lsbi = this.stubBatchinfoManager.find(hql, batchId);
if(lsbi.size() == 0) return;
log.info("发送工资条消息:"+batchId);
Notice notice = null;
for( StubBatchinfo sbi : lsbi ){
User user = this.userManager.findOne("from User where idCardNo = ?", sbi.getIdNo());
if( user == null )
break;
notice = new Notice();
notice.setMode(Notice.NOT_MODE_APP);
notice.setType(Notice.NOT_TYPE_APP_SAL);
notice.setApps("8a8c7db154ebe90c0154ebfdd1270004");
notice.setReceiverType("1");
notice.setReceiverValue(user.getId());
notice.setTitle(sbi.getMonth().substring(4)+"月工资条");
notice.setContent(sbi.getMonth().substring(0,3)+"年"+sbi.getMonth().substring(4)+"月工资条发放了。");
notice.setTarget(sbi.getId());
notice.setState(Notice.NOT_STATUE_SENT);
notice.setCreatedAt(DateUtils.getCurrentDateTimeStr());
notice = this.noticeManager.save(notice);
noticeService.send(notice);
}
} catch(Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
private void exportStubBatch(OutputStream os, List<StubBatch> list,String year) throws Exception{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
List<Object> headlist = new ArrayList<Object>();
headlist.add("序号");
headlist.add("年月");
headlist.add("批次号");
headlist.add("总人次");
headlist.add("实发总金额");
headlist.add("提交时间");
headlist.add("模板");
headlist.add("备注");
headlist.add("状态");
// sheet页
int size = headlist.size() - 1;
HSSFWorkbook workbook = new HSSFWorkbook();// 生成excel文件
HSSFSheet sheet = workbook.createSheet("批次信息");// 创建工作薄(sheet)
sheet.setDefaultColumnWidth((short) 20);
// 表头行
HSSFCellStyle titleStyle = PoiWriter.getTitleStyle(workbook);
HSSFRow row = sheet.createRow((short) 0);
HSSFCell ce = row.createCell((short) 0);
ce.setCellType(HSSFCell.CELL_TYPE_STRING);
ce.setCellValue(year+"年工资批次信息列表"); // 表格的第一行第一列显示的数据
ce.setCellStyle(titleStyle);
Region region = new Region(0, (short) 0, 0, (short) size);
PoiWriter.setRegionStyle(sheet, region, titleStyle);
sheet.addMergedRegion(region);
// 列样式
HSSFCellStyle columnStyle = PoiWriter.getContentStyle(workbook);
HSSFFont columnfont = workbook.createFont();
columnfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
columnStyle.setFont(columnfont);
// 标题栏
HSSFRow colrow = sheet.createRow(1);// 新建第二行
for (int i = 0; i < headlist.size(); i++) {
HSSFCell colcell = colrow.createCell((short) i);
colcell.setCellValue((String) headlist.get(i));
colcell.setCellType(HSSFCell.CELL_TYPE_STRING);
colcell.setCellStyle(columnStyle);
Region columnRegion3 = new Region(2, (short) i, 2, (short) i);
PoiWriter.setRegionStyle(sheet, columnRegion3, columnStyle);
sheet.addMergedRegion(columnRegion3);
}
// 内容
for (int i = 0; i < list.size(); i++) {
StubBatch stubBatch = list.get(i);
HSSFRow _row = sheet.createRow(i+2);// 新建第三行
//序号
HSSFCell indexcell = _row.createCell(0);
indexcell.setCellValue(i+1);
//年月
HSSFCell month = _row.createCell(1);
month.setCellValue(stubBatch.getMonth());
//批次号
HSSFCell batchNo = _row.createCell(2);
batchNo.setCellValue(stubBatch.getBatchNo());
//总人次
HSSFCell num = _row.createCell(3);
num.setCellValue(stubBatch.getNum());
//实发总金额
HSSFCell amount = _row.createCell(4);
amount.setCellValue(getAmountString(stubBatch.getAmount()));
//提交时间
HSSFCell submitTime = _row.createCell(5);
submitTime.setCellValue(stubBatch.getSubmitTime());
//模板
HSSFCell template = _row.createCell(6);
template.setCellValue(stubBatch.getTemplate());
//备注
HSSFCell note = _row.createCell(7);
note.setCellValue(stubBatch.getNote());
//状态
HSSFCell state = _row.createCell(8);
state.setCellValue(getStateString(stubBatch.getState()));
}
bos = new BufferedOutputStream(os);
workbook.write(bos);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
}
}
private String getStateString(String state) {
String text = "待发放";
if(state.equals("1"))
text = "已发放";
return text;
}
private String getAmountString(BigDecimal amount) {//将金额格式化为x,xxx.xx形式
String money = "0.00";
if(null != amount && !amount.equals(0F)){
BigDecimal m = amount.multiply(new BigDecimal(100));
String ms = String.valueOf(m);
char ma[] = ms.toCharArray();
int mal = ma.length;
int start = (mal-2) % 3;
money = "";
if(start == 0){
for(int i = 0;i < 3;i++){
money += ma[i];
}
start = 3;
}else{
for(int i = 0;i < start;i++){
money += ma[i];
}
}
for(int i = start;i < mal-2;){
money = money + "," + ma[i] + ma[i+1] + ma[i+2];
i += 3;
}
money = money + "." + ma[mal-2] + ma[mal-1];
}
return money;
}
}
|
package com.sinodynamic.hkgta.filter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;
import com.sinodynamic.hkgta.util.encrypt.EncryptUtil;
public class EncryptTool
{
public Logger logger = Logger.getLogger(EncryptTool.class);
public String ID_PREFIX = "_ID_";
public static final String ID_PREFIX_KEY = "encrypt.id.prefix";
public static final String IDGENERATION = "key.id.generation";
public static final String EXCLUDEDURI = "exclude.uri";
public static final String REQUIRE_ENCRYPT_URI = "requrie.encrypt.uri";
public static final String ENCRYPT_ITEMS = "encrypt.items";
private static EncryptTool instance = null;
public static void main(String[] args)
{
System.out.println(EncryptTool.getInstance().encryptIds(""));
}
public static synchronized EncryptTool getInstance()
{
if (instance == null)
{
instance = new EncryptTool();
}
return instance;
}
private Properties appProps;
private EncryptTool()
{
appProps = new Properties();
InputStream input = null;
try {
String path = "/" + this.getClass().getResource("/placeholder").toString().replace("file:/", "");
logger.info("=======================Init Encrypt Tool==========================");
input = new FileInputStream(path + "/app.properties");
appProps.load(input);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ID_PREFIX = appProps.getProperty(ID_PREFIX_KEY);
}
public String encryptIds(String originalStr)
{
String str = originalStr;
for (EncryptItem item : EncryptItem.values())
{
int _index = 0;
if (!EncryptTool.getInstance().isEncryptItem(item.getCode())) continue;
while(str.toLowerCase().indexOf(item.getSourceString(), _index) >=0 )
{
int index = str.toLowerCase().indexOf(item.getSourceString(), _index);
int start = index + item.getSourceString().length();
int end = str.indexOf(",", index);
String originalValue = str.substring(start, end);
String originalJson = "";
originalJson = str.substring(index, end + 1);
if (originalJson.contains(EncryptTool.getInstance().ID_PREFIX))
{
_index = end;
continue;
}
String newJson = originalJson.replace(originalValue, "\"" + EncryptTool.getInstance().ID_PREFIX + EncryptUtil.getInstance().AESencode(originalValue, appProps.getProperty(EncryptTool.IDGENERATION)) + "\"");
str = str.replace(originalJson, newJson);
_index = end;
}
}
return str;
}
public String decryptIds(String originStr, boolean isURI)
{
int _index = 0;
while (originStr.contains(ID_PREFIX))
{
int index = originStr.indexOf(ID_PREFIX, _index);
int start = index;
int end = originStr.indexOf(",", index) < 0 ? (originStr.indexOf("/", index) < 0 ? (originStr.indexOf("}", index) < 0 ? originStr.length() : originStr.indexOf("}", index) -1) : originStr.indexOf("/", index)) : originStr.indexOf(",", index) - 1;
String ori = originStr.substring(start,end);
String encryptString = EncryptUtil.getInstance().AESdecode(ori.replace(ID_PREFIX, ""), appProps.getProperty(EncryptTool.IDGENERATION));
if (isURI)
{
encryptString = encryptString.replace("\"", "");
}
originStr = originStr.replace(ori, encryptString);
_index = end;
}
return originStr;
}
public boolean needEncrypt(String URI)
{
if (StringUtils.isEmpty(URI)) return false;
return !exist(EXCLUDEDURI, URI);
}
public boolean requireEncrypt(String URI)
{
if (StringUtils.isEmpty(URI)) return false;
return exist(REQUIRE_ENCRYPT_URI, URI);
}
public boolean isEncryptItem(String code)
{
return appProps.getProperty(ENCRYPT_ITEMS).contains(code);
}
private boolean exist(String key, String URI)
{
String[] uris = appProps.getProperty(key).split(",");
for (String uri : uris)
{
if (URI.contains(uri)) return true;
}
return false;
}
public static enum EncryptItem
{
USERID("userid", "\"userid\":"), CUSTOMERID("customerid", "\"customerid\":"), RERVID("resvid", "\"resvid\":");
public String getSourceString()
{
return sourceString;
}
public String getCode()
{
return code;
}
private String sourceString;
private String code;
private EncryptItem(String code, String sourceString)
{
this.code = code;
this.sourceString = sourceString;
}
}
}
|
package com.minhvu.proandroid.sqlite.database.main.view.Activity.view;
/**
* Created by vomin on 10/31/2017.
*/
public interface SortView {
void colorSort(int position);
void alphaSort();
void colorOrderSort();
void modifiedTimeSort();
void sortByImportant();
}
|
package com.nisira.core.dao;
import com.nisira.core.entity.*;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import com.nisira.core.database.DataBaseClass;
import android.content.ContentValues;
import android.database.Cursor;
import com.nisira.core.util.ClaveMovil;
import java.util.ArrayList;
import java.util.LinkedList;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Destructura_costos_recursos_cotizacionventasDao extends BaseDao<Destructura_costos_recursos_cotizacionventas> {
public Destructura_costos_recursos_cotizacionventasDao() {
super(Destructura_costos_recursos_cotizacionventas.class);
}
public Destructura_costos_recursos_cotizacionventasDao(boolean usaCnBase) throws Exception {
super(Destructura_costos_recursos_cotizacionventas.class, usaCnBase);
}
public Boolean insert(Destructura_costos_recursos_cotizacionventas destructura_costos_recursos_cotizacionventas) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",destructura_costos_recursos_cotizacionventas.getIdempresa());
initialValues.put("CODIGO",destructura_costos_recursos_cotizacionventas.getCodigo());
initialValues.put("IDCOTIZACIONV",destructura_costos_recursos_cotizacionventas.getIdcotizacionv());
initialValues.put("ITEM",destructura_costos_recursos_cotizacionventas.getItem());
initialValues.put("TIPO_RECURSO",destructura_costos_recursos_cotizacionventas.getTipo_recurso());
initialValues.put("DESCRIPCION",destructura_costos_recursos_cotizacionventas.getDescripcion());
initialValues.put("CANTIDAD",destructura_costos_recursos_cotizacionventas.getCantidad());
initialValues.put("COSTO",destructura_costos_recursos_cotizacionventas.getCosto());
initialValues.put("IDPRODUCTO",destructura_costos_recursos_cotizacionventas.getIdproducto());
initialValues.put("ES_PORCENTAJE",destructura_costos_recursos_cotizacionventas.getEs_porcentaje());
initialValues.put("IDMEDIDA",destructura_costos_recursos_cotizacionventas.getIdmedida());
initialValues.put("IDPRODUCTO_EC",destructura_costos_recursos_cotizacionventas.getIdproducto_ec());
resultado = mDb.insert("DESTRUCTURA_COSTOS_RECURSOS_COTIZACIONVENTAS",null,initialValues)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public Boolean update(Destructura_costos_recursos_cotizacionventas destructura_costos_recursos_cotizacionventas,String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ContentValues initialValues = new ContentValues();
initialValues.put("IDEMPRESA",destructura_costos_recursos_cotizacionventas.getIdempresa()) ;
initialValues.put("CODIGO",destructura_costos_recursos_cotizacionventas.getCodigo()) ;
initialValues.put("IDCOTIZACIONV",destructura_costos_recursos_cotizacionventas.getIdcotizacionv()) ;
initialValues.put("ITEM",destructura_costos_recursos_cotizacionventas.getItem()) ;
initialValues.put("TIPO_RECURSO",destructura_costos_recursos_cotizacionventas.getTipo_recurso()) ;
initialValues.put("DESCRIPCION",destructura_costos_recursos_cotizacionventas.getDescripcion()) ;
initialValues.put("CANTIDAD",destructura_costos_recursos_cotizacionventas.getCantidad()) ;
initialValues.put("COSTO",destructura_costos_recursos_cotizacionventas.getCosto()) ;
initialValues.put("IDPRODUCTO",destructura_costos_recursos_cotizacionventas.getIdproducto()) ;
initialValues.put("ES_PORCENTAJE",destructura_costos_recursos_cotizacionventas.getEs_porcentaje()) ;
initialValues.put("IDMEDIDA",destructura_costos_recursos_cotizacionventas.getIdmedida()) ;
initialValues.put("IDPRODUCTO_EC",destructura_costos_recursos_cotizacionventas.getIdproducto_ec()) ;
resultado = mDb.update("DESTRUCTURA_COSTOS_RECURSOS_COTIZACIONVENTAS",initialValues,where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public Boolean delete(String where) {
Boolean resultado = false;
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
resultado = mDb.delete("DESTRUCTURA_COSTOS_RECURSOS_COTIZACIONVENTAS",where,null)>0;
} catch (Exception e) {
}finally {
mDb.close();
}
return resultado;
}
public ArrayList<Destructura_costos_recursos_cotizacionventas> listar(String where,String order,Integer limit) {
if(limit == null){
limit =0;
}
ArrayList<Destructura_costos_recursos_cotizacionventas> lista = new ArrayList<Destructura_costos_recursos_cotizacionventas>();
SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
try{
Cursor cur = mDb.query("DESTRUCTURA_COSTOS_RECURSOS_COTIZACIONVENTAS",
new String[] {
"IDEMPRESA" ,
"CODIGO" ,
"IDCOTIZACIONV" ,
"ITEM" ,
"TIPO_RECURSO" ,
"DESCRIPCION" ,
"CANTIDAD" ,
"COSTO" ,
"IDPRODUCTO" ,
"ES_PORCENTAJE" ,
"IDMEDIDA" ,
"IDPRODUCTO_EC"
},
where, null, null, null, order);
if (cur!=null){
cur.moveToFirst();
int i=0;
while (cur.isAfterLast() == false) {
int j=0;
Destructura_costos_recursos_cotizacionventas destructura_costos_recursos_cotizacionventas = new Destructura_costos_recursos_cotizacionventas() ;
destructura_costos_recursos_cotizacionventas.setIdempresa(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setCodigo(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setIdcotizacionv(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setItem(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setTipo_recurso(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setDescripcion(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setCantidad(cur.getDouble(j++));
destructura_costos_recursos_cotizacionventas.setCosto(cur.getDouble(j++));
destructura_costos_recursos_cotizacionventas.setIdproducto(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setEs_porcentaje(cur.getDouble(j++));
destructura_costos_recursos_cotizacionventas.setIdmedida(cur.getString(j++));
destructura_costos_recursos_cotizacionventas.setIdproducto_ec(cur.getString(j++));
lista.add(destructura_costos_recursos_cotizacionventas);
i++;
if(i == limit){
break;
}
cur.moveToNext();
}
cur.close();
}
} catch (Exception e) {
}finally {
mDb.close();
}
return lista;
}
} |
/*
* 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 tres;
import java.util.Scanner;
/**
*
* @author marcelino
*/
public class Ejercicio5 {
public void MayorMenor(){
Scanner leer = new Scanner(System.in);
int N = 0;
int respuesta = 0;
boolean acierto = false;
System.out.print("Dame N ");
N = leer.nextInt();
while(acierto != true){
System.out.print("Adivina N ");
respuesta = leer.nextInt();
if (respuesta == N)
{
acierto = true;
System.out.println("Ganaste!!");
}
if (respuesta < N)
{
System.out.println("Es mayor");
}
if (respuesta > N)
{
System.out.println("Es menor");
}
}
}
}
|
package org.yxm.lib.async;
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
/**
* 线程池管理类 用于App中全局管理thread
*
* @author yixiaoming
*/
public final class ThreadManager {
private static volatile ThreadManager instance;
private static final int DEFAULT_POOL_SIZE = 8;
private static final int DEFAULT_PRIORITY = android.os.Process.THREAD_PRIORITY_BACKGROUND;
private static Handler sMainHandler;
private ExecutorService mDefaultExcutor;
private ExecutorService mIoExecutor;
private ExecutorService mSingleExecutor;
private ExecutorService mScheduleExecutor;
private ThreadManager() {
sMainHandler = new Handler(Looper.getMainLooper());
ThreadFactory threadFactory = new DefaultThreadFactory();
mDefaultExcutor = Executors.newFixedThreadPool(DEFAULT_POOL_SIZE, threadFactory);
}
public static ThreadManager getInstance() {
if (instance == null) {
synchronized (ThreadManager.class) {
if (instance == null) {
return new ThreadManager();
}
}
}
return instance;
}
public void close() {
if (mDefaultExcutor != null) {
mDefaultExcutor.shutdownNow();
}
if (mIoExecutor != null) {
mIoExecutor.shutdownNow();
}
if (mSingleExecutor != null) {
mSingleExecutor.shutdownNow();
}
if (mScheduleExecutor != null) {
mScheduleExecutor.shutdownNow();
}
}
public void runOnUiThread(Runnable runnable) {
sMainHandler.post(runnable);
}
public void run(Runnable runnable) {
mDefaultExcutor.submit(runnable);
}
public <T> Future<T> call(Callable<T> callable) {
return mDefaultExcutor.submit(callable);
}
public void runIo(Runnable runnable) {
initIoExecutor();
mIoExecutor.submit(runnable);
}
public <T> Future<T> callIo(Callable<T> callable) {
initIoExecutor();
return mIoExecutor.submit(callable);
}
public void runSingle(Runnable runnable) {
initSingleExecutor();
mSingleExecutor.submit(runnable);
}
public <T> Future<T> callSingle(Callable<T> callable) {
initSingleExecutor();
return mSingleExecutor.submit(callable);
}
public void runSchedule(Runnable runnable) {
initScheduleExecutor();
mScheduleExecutor.submit(runnable);
}
public <T> Future<T> callSchedule(Callable<T> callable) {
initScheduleExecutor();
return mScheduleExecutor.submit(callable);
}
private synchronized void initIoExecutor() {
if (mIoExecutor == null) {
mIoExecutor = Executors.newCachedThreadPool();
}
}
private synchronized void initSingleExecutor() {
if (mSingleExecutor == null) {
mSingleExecutor = Executors.newSingleThreadExecutor();
}
}
private synchronized void initScheduleExecutor() {
if (mScheduleExecutor == null) {
mScheduleExecutor = Executors.newScheduledThreadPool(DEFAULT_POOL_SIZE);
}
}
private static class DefaultThreadFactory implements ThreadFactory {
private int threadNum;
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "Bees-Thread-" + threadNum) {
@Override
public void run() {
android.os.Process.setThreadPriority(DEFAULT_PRIORITY);
super.run();
}
};
++threadNum;
return thread;
}
}
}
|
package no.nav.vedtak.klient.http;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Encapsulation of java.net.http.HttpRequest to supply specific headers and ensure a timeout is set.
* Supports delayed header-setting and request validation + headers for authorization / basic
* <p>
* Usage: Create an ordinary HttpRequest.Builder with URI, Method, and headers. Then create a HttpKlientRequest
*/
public class HttpClientRequest {
private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10);
private final HttpRequest.Builder builder;
private Duration timeout;
private final Map<String, Supplier<String>> headers;
private final Map<Supplier<String>, String> dependentHeaders;
private final List<Consumer<HttpRequest>> validators;
private HttpClientRequest() {
this(HttpRequest.newBuilder(), null);
}
protected HttpClientRequest(HttpRequest.Builder builder, Map<String, Supplier<String>> headers) {
this.builder = builder;
this.headers = headers != null ? new HashMap<>(headers) : new HashMap<>();
this.dependentHeaders = new HashMap<>();
this.validators = new ArrayList<>(List.of(HttpClientRequest::validateTimeout));
}
public HttpClientRequest timeout(Duration timeout) {
validateTimeout(timeout);
this.timeout = timeout;
return this;
}
public HttpClientRequest delayedHeader(String header, Supplier<String> value) {
headers.put(header, value);
return this;
}
public HttpClientRequest validator(Consumer<HttpRequest> validator) {
validators.add(validator);
return this;
}
HttpRequest request() {
builder.timeout(Optional.ofNullable(timeout).orElse(DEFAULT_TIMEOUT));
headers.forEach((key, value) -> builder.header(key, value.get()));
dependentHeaders.forEach((key, value) -> Optional.ofNullable(key.get()).ifPresent(v -> builder.header(value, v)));
var request = builder.build();
validators.forEach(v -> v.accept(request));
return request;
}
protected HttpRequest.Builder getBuilder() {
return builder;
}
private static void validateTimeout(HttpRequest request) {
validateTimeout(request.timeout().orElse(Duration.ZERO));
}
private static void validateTimeout(Duration timeout) {
if (timeout == null || Duration.ZERO.equals(timeout) || timeout.isNegative()) {
throw new IllegalArgumentException("Utviklerfeil: ulovlig timeout");
}
}
// Test-supporting methods
public void validateRequest(Consumer<HttpRequest> validator) {
validator.accept(builder.copy().build());
}
public boolean validateDelayedHeaders(Set<String> wantedHeaders) {
return headers.keySet().containsAll(wantedHeaders);
}
}
|
package handin06;
/**
* Penny extends Coin with actual values
* @author Peter Tolstrup Aagesen, ptaa@itu.dk
*
*/
public class Penny extends Coin{
/**
* Penny constructor takes no arguments
*/
public Penny ()
{
//Call super constructor with Penny values
super(0.01, CoinType.PENNY);
}
} |
package com.cartappbackend.cartappbackend.controllers;
import com.cartappbackend.cartappbackend.models.Item;
import com.cartappbackend.cartappbackend.models.dto.ItemDto;
import com.cartappbackend.cartappbackend.services.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.PushBuilder;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/items")
public class ItemController {
private final ItemService itemService;
@Autowired
ItemController(ItemService itemService){
this.itemService = itemService;
}
@PostMapping
public ResponseEntity<ItemDto> addItem(@RequestBody ItemDto itemDto){
Item item = itemService.addItem(Item.from(itemDto));
return new ResponseEntity<>(ItemDto.from(item), HttpStatus.OK);
}
@GetMapping("/{id}")
public ResponseEntity<ItemDto> getItem(@PathVariable("id") long id){
Item item = itemService.getItem(id);
return new ResponseEntity<>(ItemDto.from(item), HttpStatus.OK);
}
@PutMapping("/{id}")
public ResponseEntity<ItemDto> updateItem(@PathVariable("id") Long id, @RequestBody ItemDto itemDto){
Item itemToUpdate = itemService.updateItem(id, Item.from(itemDto));
return new ResponseEntity<>(ItemDto.from(itemToUpdate), HttpStatus.OK);
}
@DeleteMapping("/{id}")
public ResponseEntity<ItemDto> deleteItem(@PathVariable("id") Long id){
Item itemToDelete = itemService.deleteItem(id);
return new ResponseEntity<>(ItemDto.from(itemToDelete), HttpStatus.OK);
}
@GetMapping
public ResponseEntity<List<ItemDto>> getItems(){
List<Item> items = itemService.getItems();
// Convert our list to return a collection of an itemDto list
List<ItemDto> itemsDto = items.stream().map(ItemDto::from).collect(Collectors.toList());
return new ResponseEntity<>(itemsDto,HttpStatus.OK);
}
}
|
package com.aftermoonest.tell_me_something_important.repository;
import com.vaadin.flow.component.textfield.EmailField;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
public class ControllerImpl implements Controller {
@Override
public void save(Object item, String key) {
Integer hashKey = key.hashCode();
Database.save(item, hashKey);
}
@Override
public List<Item> get() {
return Database.get();
}
@Override
public boolean find(String email) {
Integer hashKey = email.hashCode();
return Database.find(hashKey);
}
@Override
public boolean isTextCorrect(String value) {
return !StringUtils.isBlank(value) && !value.trim().equalsIgnoreCase("\n");
}
@Override
public boolean isEmailCorrect(EmailField emailField) {
return !emailField.isInvalid() && !StringUtils.isBlank(emailField.getValue());
}
@Override
public Item buildItem(String email, String name, String date, String text) {
return new Item(name, email.hashCode(), date, text);
}
@Override
public Integer defineCountOfPages() {
List<Item> items = get();
if (items.size() / countOfElementsOnPage > 1) {
return Integer.parseInt(Math.ceil(items.size() / countOfElementsOnPage)+"");
}
return 1;
}
@Override
public Integer getCountOfElementsOnPage(){
return countOfElementsOnPage;
}
}
|
import java.util.*;
/**
*Iterator for the Vector class
*
*@author Aaron Cooper
*@version 1.0
*/
public class VectorIterator<E> implements Iterator<E>
{
Vector<E> v;
int curr;
/**
*Constructs new Vector iterator
*/
public VectorIterator(Vector<E> vector)
{
v = vector;
curr = 0;
}
/**
*Returns whether or not the vector corresponding to this iterator has more values after
*the currently examined value.
*
*@return whether or not the vector has any values after the current value.
*/
public boolean hasNext()
{
if(curr < v.size() - 1)
return true;
else
return false;
}
/**
*Shifts Current value of the iterator.
*
*@return new current value.
*/
public E next()
{
if(!hasNext())
throw new NoSuchElementException();
else
{
curr++;
return v.get(curr);
}
}
/**
*Remarkably useful method. Does all sorts of stuff!
*
*@return a useful, functional piece of data that you can apply to all manner of computer science tasks/functions.
*/
public void remove()
{
}
} |
package ru.mcfr.oxygen.updater.web;
import org.apache.log4j.Logger;
import sun.misc.BASE64Encoder;
import sun.net.www.protocol.http.HttpURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.Properties;
/**
* Created by IntelliJ IDEA.
* User: ws
* Date: 27.04.11
* Time: 18:56
* To change this template use File | Settings | File Templates.
* @use-proxy
* @proxy-server
* @proxy-port
* @proxy-user-name
* @proxy-user-password
*/
public abstract class AbstractConnector {
protected Logger logger = Logger.getLogger(AbstractConnector.class);
protected Properties props;
public AbstractConnector(Properties p){
this.props = new Properties(p);
}
public abstract InputStream get(String url);
private HttpURLConnection simpleConnectToUrl(String sUrl){
sUrl = sUrl + "?username=" + System.getProperty("user.name") + "&osname=" + System.getProperty("os.name");
HttpURLConnection urlConn = null;
try{
URL url = new URL(sUrl);
if (props.getProperty("use-proxy").equals("true")){
if (props.getProperty("proxy-server").isEmpty())
throw new IllegalStateException("Settings is not loaded");
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(props.getProperty("proxy-server"),
Integer.valueOf(props.getProperty("proxy-port", "8080"))));
urlConn = new HttpURLConnection(url, proxy);
BASE64Encoder encoder = new BASE64Encoder();
String passPhrase = props.getProperty("proxy-user-name") + ":" + props.getProperty("proxy-user-password");
String encodedUserPwd = encoder.encode(passPhrase.getBytes());
urlConn.setRequestProperty("Proxy-Authorization", "Basic " + encodedUserPwd);
}
else
urlConn = new HttpURLConnection(url, null);
}catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
return urlConn;
}
public HttpURLConnection connectToURL(String sUrl){
try{
HttpURLConnection urlConn = simpleConnectToUrl(sUrl);
urlConn.setRequestMethod("GET");
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.connect();
if (urlConn.getResponseCode() < HttpURLConnection.HTTP_MULT_CHOICE)//300
return urlConn;
else
return urlConn;
}catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
return null;
}
}
|
package backend;
import java.util.Comparator;
import java.util.TreeMap;
/*
* Handle sorting groups in the 3 ways possible in the params files
*/
enum GrpSortType {Numeric,Alpha,Explicit};
public class GroupSorter implements Comparator<String>
{
private static GrpSortType mType;
private static TreeMap<String,Integer> mGrpOrder;
public GroupSorter(GrpSortType type)
{
mType = type;
}
public GroupSorter(String[] grpList) throws Exception
{
mType = GrpSortType.Explicit;
mGrpOrder = new TreeMap<String,Integer>();
mGrpOrder.put("0", 0);
for (int i = 0; i < grpList.length; i++)
{
String name = grpList[i].trim();
if (name.equals("0"))
throw(new Exception("don't use \"0\" in grp_order list in param file \"0\" - this is reserved for unanchored contigs"));
mGrpOrder.put(name,i+1);
//System.out.println("grporder add " + grpList[i]);
}
}
public boolean orderCheck(GroupInt g)
{
if (mType == GrpSortType.Explicit)
{
String name = g.getName();
//System.out.println("grporder check " + name);
if (!mGrpOrder.containsKey(name))
{
return false;
}
}
return true;
}
public boolean orderCheck(String name)
{
if (mType == GrpSortType.Explicit)
{
//System.out.println("grporder check " + name);
if (!mGrpOrder.containsKey(name))
{
return false;
}
}
return true;
}
public int compare(GroupInt g1, GroupInt g2)
{
return compare(g1.getName(), g2.getName());
}
// Intelligent sequence name sorter (albeit very inefficient).
// Strips off any matching prefix, then does a numeric compare
// on the remainder, if it is numeric.
public int compare(String g1, String g2)
{
if (mType == GrpSortType.Explicit)
{
return mGrpOrder.get(g1) - mGrpOrder.get(g2);
}
if (g1.equals(g2))
{
return 0;
}
boolean areNumbers = true;
try
{
Integer.parseInt(g1);
Integer.parseInt(g2);
}
catch(Exception e)
{
areNumbers = false;
}
if (areNumbers)
{
return Integer.parseInt(g1) - Integer.parseInt(g2);
}
// Look for a matching prefix
int nMatch = 0;
while (nMatch < g1.length() && nMatch < g2.length()
// && !Character.isDigit(g1.getName().charAt(nMatch))
// && !Character.isDigit(g2.getName().charAt(nMatch))
&& g1.charAt(nMatch) == g2.charAt(nMatch))
{
nMatch++;
}
if(nMatch == g1.length())
{
return -1; // all of g1 matched, hence must come before g2 alphabetically
}
if(nMatch == g2.length())
{
return 1;
}
String suff1 = g1.substring(nMatch);
String suff2 = g2.substring(nMatch);
// Ok, are these suffixes numeric??
areNumbers = true;
try
{
Integer.parseInt(suff1);
Integer.parseInt(suff2);
}
catch(Exception e)
{
areNumbers = false;
}
if (areNumbers)
{
return Integer.parseInt(suff1) - Integer.parseInt(suff2);
}
// well, we tried...
return g1.compareTo(g2);
}
/* public int compare(String g1, String g2)
{
switch(mType)
{
case Numeric:
return Integer.parseInt(g1) - Integer.parseInt(g2);
case Alpha:
return g1.compareTo(g2);
case Explicit:
return mGrpOrder.get(g1) - mGrpOrder.get(g2);
}
assert false;
return 0;
} */
}
|
package com.gxtc.huchuan.data.deal;
import com.gxtc.commlibrary.data.BaseRepository;
import com.gxtc.huchuan.bean.NewsBean;
import com.gxtc.huchuan.data.UserManager;
import com.gxtc.huchuan.http.ApiCallBack;
import com.gxtc.huchuan.http.ApiObserver;
import com.gxtc.huchuan.http.ApiResponseBean;
import com.gxtc.huchuan.http.service.AllApi;
import com.gxtc.huchuan.ui.mine.news.MineArticleContract;
import java.util.List;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by sjr on 2017/2/15.
* 自己写的文章
*/
public class MineArticleRepository extends BaseRepository implements MineArticleContract.Source {
@Override
public void getData(final int start, final ApiCallBack<List<NewsBean>> callBack) {
String token = UserManager.getInstance().getToken();
Subscription sub = AllApi.getInstance().getMineArticle(token, String.valueOf(start),"")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new ApiObserver<ApiResponseBean<List<NewsBean>>>(callBack));
addSub(sub);
}
}
|
package com.seva.entity;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
/**
* The persistent class for the drawer_assigned_history database table.
*
*/
@Entity
@Table(name="drawer_assigned_history")
@NamedQuery(name="DrawerAssignedHistory.findAll", query="SELECT d FROM DrawerAssignedHistory d")
public class DrawerAssignedHistory implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String operation;
private Date time;
private User user;
public DrawerAssignedHistory() {
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getOperation() {
return this.operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getTime() {
return this.time;
}
public void setTime(Date time) {
this.time = time;
}
//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name="A_USER")
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
} |
package com.eot3000.utils;
public class Vec3Position {
public final int x;
public final int y;
public final int z;
public Vec3Position(int x, int y, int z){
this.x = x;
this.y = y;
this.z = z;
}
}
|
package com.nextLevel.hero.mngSalary.model.dto;
import java.sql.Date;
import java.time.LocalDate;
public class DetailPayDTO {
private int companyNo;
private int idNo;
private int memberNo;
private String salaryName;
private String imputedDate;
private java.sql.Date payDate;
private int salaryAmount;
private String departmentName;
private String memberName;
private String salOrBonus;
private int divNo;
private String deductYn;
private String updatable;
private String confirmYn;
public DetailPayDTO() {}
public DetailPayDTO(int companyNo, int idNo, int memberNo, String salaryName, String imputedDate, Date payDate,
int salaryAmount, String departmentName, String memberName, String salOrBonus, int divNo, String deductYn,
String updatable, String confirmYn) {
super();
this.companyNo = companyNo;
this.idNo = idNo;
this.memberNo = memberNo;
this.salaryName = salaryName;
this.imputedDate = imputedDate;
this.payDate = payDate;
this.salaryAmount = salaryAmount;
this.departmentName = departmentName;
this.memberName = memberName;
this.salOrBonus = salOrBonus;
this.divNo = divNo;
this.deductYn = deductYn;
this.updatable = updatable;
this.confirmYn = confirmYn;
}
public int getCompanyNo() {
return companyNo;
}
public void setCompanyNo(int companyNo) {
this.companyNo = companyNo;
}
public int getIdNo() {
return idNo;
}
public void setIdNo(int idNo) {
this.idNo = idNo;
}
public int getMemberNo() {
return memberNo;
}
public void setMemberNo(int memberNo) {
this.memberNo = memberNo;
}
public String getSalaryName() {
return salaryName;
}
public void setSalaryName(String salaryName) {
this.salaryName = salaryName;
}
public String getImputedDate() {
return imputedDate;
}
public void setImputedDate(String imputedDate) {
this.imputedDate = imputedDate;
}
public java.sql.Date getPayDate() {
return payDate;
}
public void setPayDate(java.sql.Date payDate) {
this.payDate = payDate;
}
public int getSalaryAmount() {
return salaryAmount;
}
public void setSalaryAmount(int salaryAmount) {
this.salaryAmount = salaryAmount;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
public String getSalOrBonus() {
return salOrBonus;
}
public void setSalOrBonus(String salOrBonus) {
this.salOrBonus = salOrBonus;
}
public int getDivNo() {
return divNo;
}
public void setDivNo(int divNo) {
this.divNo = divNo;
}
public String getDeductYn() {
return deductYn;
}
public void setDeductYn(String deductYn) {
this.deductYn = deductYn;
}
public String getUpdatable() {
return updatable;
}
public void setUpdatable(String updatable) {
this.updatable = updatable;
}
public String getConfirmYn() {
return confirmYn;
}
public void setConfirmYn(String confirmYn) {
this.confirmYn = confirmYn;
}
@Override
public String toString() {
return "DetailPayDTO [companyNo=" + companyNo + ", idNo=" + idNo + ", memberNo=" + memberNo + ", salaryName="
+ salaryName + ", imputedDate=" + imputedDate + ", payDate=" + payDate + ", salaryAmount="
+ salaryAmount + ", departmentName=" + departmentName + ", memberName=" + memberName + ", salOrBonus="
+ salOrBonus + ", divNo=" + divNo + ", deductYn=" + deductYn + ", updatable=" + updatable
+ ", confirmYn=" + confirmYn + "]";
}
}
|
package ur.api_ur.store;
import ur.api_ur.URApiType;
/**
* Created by redjack on 15/9/22.
*/
public class URApiStoreType extends URApiType {
public static URApiStoreType GET_COUPIN_LIST = new URApiStoreType(401, "/coupon/list_by");
public static URApiStoreType GET_COUPON = new URApiStoreType(402, "/coupon/get");
public static URApiStoreType REDEEM = new URApiStoreType(403, "/coupon/redeem");
public static URApiStoreType SEARCH_COUPON = new URApiStoreType(404, "/coupon/search_cpn");
public URApiStoreType(int type, String method) {
super(type, method);
}
}
|
package com.lambda.iith.dashboard.MainFragments;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.LinearLayout;
import com.lambda.iith.dashboard.Launch;
import com.lambda.iith.dashboard.R;
public class acad_info extends Fragment {
private WebView webView;
@RequiresApi(api = Build.VERSION_CODES.Q)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_acad_info, container, false);
// ImageView img = (ImageView) view.findViewById(R.id.img);
// MaterialCardView card= view.findViewById(R.id.card);
// card.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent link=new Intent(Intent.ACTION_VIEW, Uri.parse("https://drive.google.com/file/d/18J6zZm9jnjkY6le8Nbk9kQU9bUXsXSVC/view?usp=sharing"));
// startActivity(link);
// }
// });
// final Button curriculum = (Button) view.findViewById(R.id.curriculum);
// ViewGroup.LayoutParams params = curriculum.getLayoutParams();
// params.width = -5+Launch.width/3;
// curriculum.setLayoutParams(params);
//
//
// final Button handbooks = (Button) view.findViewById(R.id.handbooks);
// ViewGroup.LayoutParams params1 = handbooks.getLayoutParams();
// params1.width = -5+ Launch.width/3;
// handbooks.setLayoutParams(params1);
//
// final Button acad_cal = (Button) view.findViewById(R.id.acad_calender);
// ViewGroup.LayoutParams params2 = acad_cal.getLayoutParams();
// params2.width = -5+Launch.width/3;
// acad_cal.setLayoutParams(params2);
webView = view.findViewById(R.id.webview);
//webView.setLayoutParams(new LinearLayout.LayoutParams(Launch.width , Launch.height*));
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setForceDark(WebSettings.FORCE_DARK_ON);
String wpix = Integer.toString(Launch.width*400/1080);
String unencodedHtml = "<iframe src=\"https://calendar.google.com/calendar/embed?height=700&wkst=2&bgcolor=%23ffffff&ctz=Asia%2FKolkata&src=Y19sbDczZW04czgxbmh1OG5ianZnZ3FobWJnY0Bncm91cC5jYWxlbmRhci5nb29nbGUuY29t&color=%23E4C441&showPrint=0&showCalendars=0&showTz=0&showTabs=1&showTitle=0&showNav=1\" style=\"border-width:0\" width=\" " +wpix + "\" height=\"700\" frameborder=\"0\" scrolling=\"no\"></iframe>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),
Base64.NO_PADDING);
webView.loadData(encodedHtml, "text/html", "base64");
// curriculum.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent curri=new Intent(getActivity(), curriculum.class);
// startActivity(curri);
// }
// });
// acad_cal.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://calendar.google.com/calendar/u/0/r?cid=c_ll73em8s81nhu8nbjvggqhmbgc@group.calendar.google.com")));
//
// }
// });
// handbooks.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://iith.dev/curriculum/academic_handbook.pdf")));
//
// }
// });
return view;
}
} |
package com.ziaan.scorm;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class StringUtil
{
public static final String TITLE_NAME = "NAME :";
public static final String TITLE_ORGANIZATION = "ORGANIZATION :";
public static final String TITLE_ADDRESS = "ADDRESS :";
public static final String TITLE_EMAIL = "EMAIL :";
public StringUtil()
{
}
public static String urlEncode(String str)
{
return replace(URLEncoder.encode(str), " + ", "%20");
}
public static String replace(String str, String pattern, String replace)
{
int s = 0;
int e = 0;
if ( pattern.equals(""))
return str;
StringBuffer result = new StringBuffer();
while ( (e = str.indexOf(pattern, s)) >= 0)
{
result.append(str.substring(s, e));
result.append(replace);
s = e + pattern.length();
}
result.append(str.substring(s));
return result.toString();
}
public static String replace(String str, int sPos, int ePos, String replace)
{
StringBuffer result = new StringBuffer(str.substring(0, sPos));
result.append(replace);
result.append(str.substring(ePos));
return result.toString();
}
public static String[] getArrToken(String str, String delim)
{
StringTokenizer tk = new StringTokenizer(str, delim);
String arr[] = new String[tk.countTokens()];
for ( int i = 0; i < arr.length; i++ )
arr[i] = tk.nextToken();
return arr;
}
public static String[] getArrToken2(String str, String delim)
{
return split(str, delim, true);
}
public static String HrInsEnterX(String str, int length)
{
String tmp[] = getArrToken(str, " ");
String rtnStr = "";
int line_num = 1;
for ( int i = 0; i < tmp.length; i++ )
{
if ( (rtnStr + tmp[i]).length() > length * line_num)
{
rtnStr = rtnStr + "\n";
line_num++;
}
rtnStr = rtnStr + " " + tmp[i];
}
return rtnStr;
}
public static String HrInsEnterX(String str, int length, String pad)
{
return replace(HrInsEnterX(str, length), "\n", "\n" + pad);
}
public static String HrInsEnterX2(String str, int length)
{
String tmp[] = getArrToken(str, " ");
String rtnStr = "";
String this_line = "";
for ( int i = 0; i < tmp.length; i++ )
{
this_line = this_line + tmp[i];
if ( this_line.length() > length)
{
rtnStr = rtnStr + this_line + "\n";
this_line = "";
} else
if ( this_line.indexOf("\n") != -1)
{
rtnStr = rtnStr + this_line;
this_line = "";
}
}
rtnStr = rtnStr + this_line;
return rtnStr;
}
public static String getIntString(String str)
{
String rtn = "";
try
{
rtn = String.valueOf(Integer.parseInt(str));
} catch( Exception e )
{
rtn = "";
}
return rtn;
}
public static String getNumber(String str)
{
if ( str == null )
return str;
StringBuffer sb = new StringBuffer(str);
StringBuffer newSb = new StringBuffer();
int sbLen = sb.length();
for ( int i = 0; i < sbLen; i++ )
{
char number = sb.charAt(i);
if ( number >= '0' && number <= '9')
newSb.append(sb.charAt(i));
}
return newSb.toString();
}
public static String fixLength(String input)
{
return fixLength(input, 15, "...");
}
public static String fixLength(String input, int limit)
{
return fixLength(input, limit, "...");
}
public static String fixLength(String input, int limit, String postfix)
{
char charArray[] = input.toCharArray();
if ( limit >= charArray.length)
return input;
else
return (new String(charArray, 0, limit)).concat(postfix);
}
public static String fixUnicodeLength(String input, int limitByte)
{
return fixLength(input, limitByte, "...");
}
public static String fixUnicodeLength(String input, int limitByte, String postfix)
{
byte outputBytes[] = input.getBytes();
String output = outputBytes.length > limitByte ? ((new String(outputBytes, 0, limitByte)).length() != 0 ? new String(outputBytes, 0, limitByte) : (new String(outputBytes, 0, limitByte - 1)).concat(postfix)).concat(postfix) : input;
return output;
}
public static String getEUC_KR(String text)
{
String rtn = "";
if ( text == null )
return rtn;
try
{
return new String(text.getBytes("8859_1"), "euc-kr");
} catch(UnsupportedEncodingException UEE)
{
return rtn;
}
}
public static String[] getEUC_KR(String arrText[])
{
String arrRtn[] = new String[arrText.length];
for ( int i = 0; i < arrText.length; i++ )
arrRtn[i] = getEUC_KR(arrText[i]);
return arrRtn;
}
public static String get8859_1(String text)
{
String rtn = "";
if ( text == null )
return rtn;
try
{
return new String(text.getBytes("euc-kr"), "8859_1");
} catch(UnsupportedEncodingException UEE)
{
return rtn;
}
}
public static String getConvertCharset(String text, String fromEncode, String toEncode)
{
String rtn = "";
if ( text == null )
return rtn;
try
{
return new String(text.getBytes(fromEncode), toEncode);
} catch(UnsupportedEncodingException UEE)
{
return rtn;
}
}
public static String getSpecialCharacters(String str)
{
str = replace(str, "&", "&");
str = replace(str, "<", "<");
str = replace(str, " > ", ">");
str = replace(str, "'", "´");
str = replace(str, "\"", """);
str = replace(str, "|", "¦");
str = replace(str, "\n", "<BR > ");
str = replace(str, "\r", "");
return str;
}
public static String getRreplaceSpecialCharacters(String str)
{
str = replace(str, "<BR > ", "\n");
str = replace(str, "&", "&");
str = replace(str, "<", "<");
str = replace(str, ">", " > ");
str = replace(str, "´", "'");
str = replace(str, """, "\"");
str = replace(str, "¦", "|");
return str;
}
public static String getComma(String str)
{
return getComma(str, true);
}
public static String getComma(String str, boolean isTruncated)
{
if ( str == null )
return "";
if ( str.trim().equals(""))
return "";
if ( str.trim().equals(" "))
return " ";
int pos = str.indexOf(".");
if ( pos != -1)
{
if ( !isTruncated)
{
DecimalFormat commaFormat = new DecimalFormat("#,##0.00");
return commaFormat.format(Float.parseFloat(str.trim() ));
} else
{
DecimalFormat commaFormat = new DecimalFormat("#,##0");
return commaFormat.format(Long.parseLong(str.trim().substring(0, pos)));
}
} else
{
DecimalFormat commaFormat = new DecimalFormat("#,##0");
return commaFormat.format(Long.parseLong(str.trim() ));
}
}
public static String getComma(Long lstr)
{
DecimalFormat commaFormat = new DecimalFormat("#,##0");
if ( lstr == null )
return "";
else
return commaFormat.format( lstr);
}
public static String getFormatedText(String text, String format)
{
int tCount = text.length();
int fCount = format.length();
String rtn = "";
if ( text.equals(""))
return rtn;
if ( text.equals(" "))
return " ";
for ( int i = 0; i < tCount; i++ )
if ( !text.substring(i, i + 1).equals("-"))
rtn = rtn + text.substring(i, i + 1);
text = rtn;
tCount = text.length();
int len = 0;
for ( int j = 0; j < fCount; j++ )
if ( format.substring(j, j + 1).equals("?"))
len++;
if ( tCount < len)
{
for ( int i = 0; i < len - tCount; i++ )
text = '0' + text;
tCount = len;
}
rtn = "";
int start = 0;
for ( int i = 0; i < tCount; i++ )
{
for ( int j = start; j < fCount; j++ )
{
if ( format.substring(j, j + 1).equals("?"))
{
rtn = rtn + text.substring(i, i + 1);
start++;
break;
}
rtn = rtn + format.substring(j, j + 1);
start++;
}
}
return rtn + format.substring(start);
}
public static String getRawText(String text, String format)
{
int tCount = text.length();
int fCount = format.length();
String rtn = "";
if ( text.equals(""))
return rtn;
if ( text.equals(" "))
return " ";
int start = 0;
for ( int i = 0; i < tCount; i++ )
{
for ( int j = start; j < fCount;)
{
if ( format.substring(j, j + 1).equals("?"))
{
rtn = rtn + text.substring(i, i + 1);
start++;
} else
{
start++;
}
break;
}
}
return rtn;
}
public static String getZeroBaseString(int num, int size)
{
return getZeroBaseString(String.valueOf(num), size);
}
public static String getZeroBaseString(String num, int size)
{
String zeroBase = "";
if ( num.length() >= size)
return num;
for ( int index = 0; index < size - num.length(); index++ )
zeroBase = zeroBase + "0";
return zeroBase + num;
}
public static String getGetMethodFormat(String str)
{
String rtn = "";
rtn = replace(str, "\n", " ");
rtn = replace(rtn, " ", "%20");
return rtn;
}
public static String lpad(String str, String f_char, int size)
{
if ( str.length() >= size)
return str;
else
return getFillChar("", f_char, size - str.length() ) + str;
}
public static String rpad(String str, String f_char, int size)
{
if ( str.length() >= size)
return str;
else
return str + getFillChar("", f_char, size - str.length() );
}
public static String getFillChar(String str, String f_char, int size)
{
String fillChar = "";
if ( str.length() >= size)
return str;
for ( int index = 0; index < size - str.length(); index++ )
fillChar = fillChar + f_char;
return str + fillChar;
}
public static String getFillCharByte(String str, String f_char, int size)
{
String fillChar = "";
if ( str.getBytes().length >= size)
return str;
for ( int index = 0; index < size - str.getBytes().length; index++ )
fillChar = fillChar + f_char;
return str + fillChar;
}
public static String[] split(String strTarget, String strDelim, boolean bContainNull)
{
int index = 0;
String resultStrArray[] = new String[getStrCnt(strTarget, strDelim) + 1];
for ( String strCheck = new String(strTarget); strCheck.length() != 0;)
{
int begin = strCheck.indexOf(strDelim);
if ( begin == -1)
{
resultStrArray[index] = strCheck;
break;
}
int end = begin + strDelim.length();
if ( bContainNull)
resultStrArray[index++] = strCheck.substring(0, begin);
strCheck = strCheck.substring(end);
if ( strCheck.length() == 0 && bContainNull)
{
resultStrArray[index] = strCheck;
break;
}
}
return resultStrArray;
}
public static int getStrCnt(String strTarget, String strSearch)
{
int result = 0;
String strCheck = new String(strTarget);
for ( int i = 0; i < strTarget.length();)
{
int loc = strCheck.indexOf(strSearch);
if ( loc == -1)
break;
result++;
i = loc + strSearch.length();
strCheck = strCheck.substring(i);
}
return result;
}
public static String makeFUpper(String src)
{
String tmp = src;
if ( src != null && src.length() > 0)
return src.substring(0, 1).toUpperCase() + src.substring(1).toLowerCase();
else
return "";
}
public static boolean isExistInArray(String array[], String str, boolean ignorecase)
{
if ( array == null )
return false;
for ( int i = 0; i < array.length; i++ )
if ( ignorecase)
{
if ( array[i].toUpperCase().equals(str.toUpperCase() ))
return true;
} else
if ( array[i].equals(str))
return true;
return false;
}
public static String ltrim(String str)
{
int len = str.length();
int st = 0;
int off = 0;
for ( char val[] = str.toCharArray(); st < len && val[off + st] <= ' '; st++ );
return st <= 0 ? str : str.substring(st);
}
public static String rtrim(String str)
{
int len = str.length();
int st = 0;
int off = 0;
for ( char val[] = str.toCharArray(); st < len && val[(off + len) - 1] <= ' '; len--);
return len >= str.length() ? str : str.substring(0, len);
}
public static String addBackSlash(String pm_sString)
{
String lm_sRetString = "";
for ( int i = 0; i < pm_sString.length(); i++ )
if ( pm_sString.charAt(i) == '\\')
lm_sRetString = lm_sRetString + "\\\\";
else
if ( pm_sString.charAt(i) == '\'')
lm_sRetString = lm_sRetString + "\\'";
else
lm_sRetString = lm_sRetString + pm_sString.charAt(i);
return lm_sRetString;
}
public static String encode(String inputStr)
{
String result = "";
inputStr = inputStr.trim();
for ( int i = 0; i < inputStr.length(); i++ )
{
int val = inputStr.charAt(i) + i * 29;
result = result + lpad(String.valueOf(val), "0", 3);
}
return result;
}
public static String decode(String inputStr)
{
String result = "";
inputStr = inputStr.trim();
for ( int i = 0; i < inputStr.length() / 3; i++ )
{
int num = Integer.parseInt(inputStr.substring(i * 3, i * 3 + 3)) - i * 29;
result = result + (char)num;
}
return result;
}
public static String nbsp(int count)
{
String result = "";
for ( int i = 0; i < count; i++ )
result = result + " ";
return result;
}
public static String centity(String str)
{
String ret = ",,,";
try {
if ( str != null ) {
ret = str.substring(TITLE_NAME.length(),str.lastIndexOf(TITLE_ORGANIZATION)-1).trim() + ","
+ str.substring(str.lastIndexOf(TITLE_ORGANIZATION) + TITLE_ORGANIZATION.length(), str.lastIndexOf(TITLE_ADDRESS)-1).trim() + ","
+ str.substring(str.lastIndexOf(TITLE_ADDRESS) + TITLE_ADDRESS.length(), str.lastIndexOf(TITLE_EMAIL)-1).trim() + ","
+ str.substring(str.lastIndexOf(TITLE_EMAIL) +TITLE_EMAIL.length() ).trim();
}
} catch ( Exception e ) { }
return ret;
}
public static int getBytesCount(String str) {
int count = 0;
byte[] b = null;
if ( str != null ) {
b = str.getBytes();
count = b.length;
}
return count;
}
public static String juminno(String str)
{
String ret = "";
try {
if ( str != null || str.length() == 13 ) {
ret = str.substring(0,6) + "-" + str.substring(6);
}
} catch ( Exception e ) { }
return ret;
}
} |
package com.mmm.Service.Impl;
import com.mmm.Dao.StudentDao;
import com.mmm.Service.StudentService;
import com.mmm.bean.Student;
import java.io.Serializable;
import java.util.List;
/**
* service层的作用
* 在不改变dao层代码的前提下,增加业务逻辑操作
*/
public class StudentServiceImpl implements StudentService {
private StudentDao dao;
@Override
public int addStudent(Student student) {
return dao.addStudent(student);
}
public int delStudent(Serializable id) {
return dao.delStudent(id);
}
@Override
public int updateStudent(Student student) {
return dao.updateStudent(student);
}
@Override
public List<Student> findAllStudents() {
return dao.findAllStudents();
}
public StudentDao getDao() {
return dao;
}
public void setDao(StudentDao dao) {
this.dao = dao;
}
}
|
package Question1_25;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.concurrent.ConcurrentLinkedQueue;
public class _20_validParentheses {
public boolean isValid(String s) {
int len = s.length();
Deque<Character> stack = new LinkedList<Character>();
char[] left = {'{','[','('};
char[] right = {'}',']',')'};
for(int i = 0 ; i < len ; i++ ) {
char c = s.charAt(i);
int k = 0;
for(int j = 0 ; j < 3; j++){
if( c == left[j]){
stack.addLast(c);
continue;
}
if(right[j] == (c)){
if(stack.isEmpty()) {
return false;
}
if(stack.pollLast()==left[j]){
continue;
}else{
return false;
}
}
}
}
if(!stack.isEmpty()) {
return false;
}
return true;
}
}
|
/** https://codeforces.com/problemset/problem/103/B #dfs #dsu */
import java.util.Scanner;
public class Cthulhu {
public static void makeSet(int[] parent, int[] size) {
int sz = parent.length;
for (int i = 0; i < sz; i++) {
parent[i] = i;
size[i] = 1;
}
}
public static int findSet(int u, int[] parent) {
if (parent[u] != u) {
parent[u] = findSet(parent[u], parent);
}
return parent[u];
}
public static boolean unionSet(int[] parent, int[] size, int u, int v, int[] cycle) {
int up = findSet(u, parent);
int vp = findSet(v, parent);
if (up == vp) {
return false;
}
if (size[up] > size[vp]) {
parent[vp] = up;
size[up] += size[vp];
} else if (size[up] < size[vp]) {
parent[up] = vp;
size[vp] += size[up];
} else {
parent[up] = vp;
size[vp] += size[up];
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int sz = n + 1;
int[] parent = new int[sz];
int[] size = new int[sz];
int[] cycle = new int[sz];
makeSet(parent, size);
// N == M
// > 1 -> 1
// N - 1
if (n != m) {
System.out.println("NO");
return;
}
int a, b, ans = n;
for (int i = 0; i < m; i++) {
a = sc.nextInt();
b = sc.nextInt();
if (unionSet(parent, size, a, b, cycle)) {
ans -= 1;
}
}
System.out.println(ans == 1 ? "FHTAGN!" : "NO");
return;
}
}
|
import java.util.Scanner;
public class Encryption {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Input the message to decode");
String input = sc.nextLine(); //:mmZ\dxZmx]Zpgy --> Attack at dawn for key = 7
for(int i = 1; i <= 100; i++){
System.out.println("Key = " +i +" is " +decrypt(input, i));
}
}
public static String decrypt(String s, int key){
String newString = "";
for(int i = 0; i < s.length(); i++){
int newC;
//The character as an integer
if((int)s.charAt(i) + key > 126)
newC = 32 + ((int)s.charAt(i) + key - 127);
else
newC = (int)s.charAt(i) + key;
//remake the character
char c = (char)newC;
//add it to the string
newString += c;
}
return newString;
}
}
|
package com.pinyougou.search.listener;
import com.alibaba.fastjson.JSON;
import com.pinyougou.common.rocketmq.MessageInfo;
import com.pinyougou.pojo.TbItem;
import com.pinyougou.search.service.ItemSearchService;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @ClassName:GoodsMessageListener
* @Author:Mr.lee
* @DATE:2019/07/07
* @TIME: 21:29
* @Description: TODO
*/
/**
* 监听器的类
*/
public class GoodsMessageListener implements MessageListenerConcurrently{
@Autowired //注入searchService
private ItemSearchService itemSearchService;
/**
* 重写获取消息的方法
* @param list
* @param consumeConcurrentlyContext
* @return
*/
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
try {
if (list != null) {
System.out.println("start:+++++++");
//1.循环遍历消息对象
for (MessageExt msg : list) {
//2.获取消息内容body
byte[] body = msg.getBody();
String str = new String(body);//获取到的消息字符串
MessageInfo info = JSON.parseObject(str,MessageInfo.class);
//3.获取方法(add、delete、update)
int method = info.getMethod();//1.新增、2.修改、3.删除
System.out.println("=========zhixingfangfa:"+method);
//4.判断方法是 add、delete、update 分别进行对应的CRUD的操作
switch (method){
case 1:{ //如果是1,表示要新增
//获取商品列表的字符串
String context1 = info.getContext().toString();
//数据转JSON对象
List<TbItem> itemList = JSON.parseArray(context1, TbItem.class);
//调用修改的方法
itemSearchService.updateIndex(itemList);
System.out.println("This is Add! 1" );
break;
}
case 2: {//如果是2,表示要修改,更新
//获取商品列表的字符串
String context1 = info.getContext().toString();
//数据转JSON对象
List<TbItem> itemList = JSON.parseArray(context1, TbItem.class);
//调用修改的方法
itemSearchService.updateIndex(itemList);
System.out.println("This is Update! 2");
break;
}
case 3:{//如果是3,表示要删除
//获取SPU 的id的数组,也是字符串
String context1 = info.getContext().toString();
//这里因为ids中的id有可能重复,使用set集合去除重复id的操作
Set<Long> arr = new HashSet<>();
//也需要转成json对象
Long[] aLong = JSON.parseObject(context1, Long[].class);
//调用删除的方法
itemSearchService.deleteByIds(aLong);
System.out.println("This is Delete! 3");
break;
}
default:{
//表示最后
throw new RuntimeException("Incorrect message sent!!!");
}
}
}
}
//如果没有异常,则正常获取消息体
return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
}
//如果出现异常,则提示等会儿再试
return ConsumeConcurrentlyStatus.RECONSUME_LATER;
}
}
|
package com.sightstbilisigeorgia.tbilisicinemas.helpers;
import helpers.models.Theatre;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.sightstbilisigeorgia.tbilisicinemas.R;
public class TheatresAdapter extends BaseAdapter {
Context ctx;
List<Theatre> theatresList;
public TheatresAdapter(Context ctx, ArrayList<Theatre> theatresList) {
this.ctx = ctx;
this.theatresList = theatresList;
}
@Override
public int getCount() {
return theatresList.size();
}
@Override
public Object getItem(int index) {
if (theatresList == null || theatresList.size() == 0)
return null;
return theatresList.get(index);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LayoutInflater inflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = inflater.inflate(R.layout.row_list_theatres, parent, false);
}
Theatre item = theatresList.get(position);
TextView theatreTitle = (TextView) view.findViewById(R.id.theatreTitle);
TextView theatreLocation = (TextView) view
.findViewById(R.id.theatreLocation);
TextView theatrePerformances = (TextView) view
.findViewById(R.id.theatrePerformances);
TextView theatrePrifeFrom = (TextView) view
.findViewById(R.id.theatrePriceFrom);
theatreTitle.setText(item.getName());
// theatreLocation.setText(item.getLocation());
theatrePerformances.setText(item.getPerformances());
// theatrePrifeFrom.setText(item.getPriceFrom());
return view;
}
}
|
package com.utilities;
import java.io.File;
import java.io.FileInputStream;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet;
public ExcelDataConfig() {
try {
File src = new File("./TestData/TestDataSheet.xlsx");
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
e.printStackTrace();
}
}
public String getData(String sheetName, int row, int col) {
sheet = wb.getSheet(sheetName);
String data = sheet.getRow(row).getCell(col).getStringCellValue();
return data;
}
public int rowCount(String SName) {
int row = wb.getSheet(SName).getLastRowNum();
row = row + 1;
return row;
}
}
|
package seedu.project.logic.commands;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static seedu.project.commons.core.Messages.MESSAGE_TASKS_LISTED_OVERVIEW;
import static seedu.project.logic.commands.CommandTestUtil.assertCommandSuccess;
import static seedu.project.testutil.TypicalTasks.TEACHING_FEEDBACK;
import static seedu.project.testutil.TypicalTasks.TUTORIAL;
import static seedu.project.testutil.TypicalTasks.getTypicalProjectList;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Test;
import seedu.project.logic.CommandHistory;
import seedu.project.logic.LogicManager;
import seedu.project.model.Model;
import seedu.project.model.ModelManager;
import seedu.project.model.UserPrefs;
import seedu.project.model.project.Project;
import seedu.project.model.task.NameContainsKeywordsPredicate;
/**
* Contains integration tests (interaction with the Model) for
* {@code FindCommand}.
*/
public class FindCommandTest {
private Model model = new ModelManager(getTypicalProjectList(), new Project(), new UserPrefs());
private Model expectedModel = new ModelManager(getTypicalProjectList(), new Project(), new UserPrefs());
private CommandHistory commandHistory = new CommandHistory();
@Test
public void equals() {
NameContainsKeywordsPredicate firstPredicate = new NameContainsKeywordsPredicate(
Collections.singletonList("first"));
NameContainsKeywordsPredicate secondPredicate = new NameContainsKeywordsPredicate(
Collections.singletonList("second"));
FindCommand findFirstCommand = new FindCommand(firstPredicate);
FindCommand findSecondCommand = new FindCommand(secondPredicate);
// same object -> returns true
assertTrue(findFirstCommand.equals(findFirstCommand));
// same values -> returns true
FindCommand findFirstCommandCopy = new FindCommand(firstPredicate);
assertTrue(findFirstCommand.equals(findFirstCommandCopy));
// different types -> returns false
assertFalse(findFirstCommand.equals(1));
// null -> returns false
assertFalse(findFirstCommand.equals(null));
// different task -> returns false
assertFalse(findFirstCommand.equals(findSecondCommand));
}
@Test
public void execute_zeroKeywords_noTaskFound() {
String expectedMessage = String.format(MESSAGE_TASKS_LISTED_OVERVIEW, 0);
NameContainsKeywordsPredicate predicate = preparePredicate(" ");
FindCommand command = new FindCommand(predicate);
model.setProject(model.getFilteredProjectList().get(0));
model.setSelectedProject(model.getFilteredProjectList().get(0));
expectedModel.setProject(expectedModel.getFilteredProjectList().get(0));
expectedModel.setSelectedProject(expectedModel.getFilteredProjectList().get(0));
LogicManager.setState(true);
expectedModel.updateFilteredTaskList(predicate);
assertCommandSuccess(command, model, commandHistory, expectedMessage, expectedModel);
assertEquals(Collections.emptyList(), model.getFilteredTaskList());
}
@Test
public void execute_multipleKeywords_multipleTasksFound() {
String expectedMessage = String.format(MESSAGE_TASKS_LISTED_OVERVIEW, 2);
NameContainsKeywordsPredicate predicate = preparePredicate("feedback tutorial");
FindCommand command = new FindCommand(predicate);
model.setProject(model.getFilteredProjectList().get(0));
model.setSelectedProject(model.getFilteredProjectList().get(0));
expectedModel.setProject(expectedModel.getFilteredProjectList().get(0));
expectedModel.setSelectedProject(expectedModel.getFilteredProjectList().get(0));
LogicManager.setState(true);
expectedModel.updateFilteredTaskList(predicate);
assertCommandSuccess(command, model, commandHistory, expectedMessage, expectedModel);
assertEquals(Arrays.asList(TEACHING_FEEDBACK, TUTORIAL), model.getFilteredTaskList());
}
/**
* Parses {@code userInput} into a {@code NameContainsKeywordsPredicate}.
*/
private NameContainsKeywordsPredicate preparePredicate(String userInput) {
return new NameContainsKeywordsPredicate(Arrays.asList(userInput.split("\\s+")));
}
}
|
package com.example.mealprep.fragments;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.example.mealprep.R;
public class FragmentIngredientList extends DrawerFragment implements OnClickListener{
private OnItemClickListener mClicker;
private ListView ingredientList;
private ArrayAdapter<EditText> ingredientListAdapter;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = (View) inflater.inflate(R.layout.fragment_ingredient_list,
container, false);
//set the listeners
view.findViewById(R.id.buttonNewIngredient).setOnClickListener(this);
ingredientList = (ListView) (view.findViewById(R.id.listView_Ingredient));
//set the adapter for the listview for dynamic population
ingredientListAdapter = new ArrayAdapter<EditText>(getActivity(), R.layout.ingredient);
ingredientList.setAdapter(ingredientListAdapter);
// if( ! (savedInstanceState == null) )
// if(savedInstanceState.containsKey("num_editTexts")){
// TextView textView = (TextView) view.findViewById(R.id.ingredientListTitle);
// textView.setText("Noslen");
// }
// Inflate the layout for this fragment
return view;
}
public FragmentIngredientList(){
name = "Ingredient List";
}
@Override
public void onClick(View v) {
EditText editText = new EditText(getActivity());
Toast.makeText(this.getActivity(), "Button was pressed", Toast.LENGTH_SHORT).show();
ingredientListAdapter.add(editText);
}
@Override
public void onDetach(){
}
@Override
public void onSaveInstanceState(Bundle outstate){
super.onSaveInstanceState(outstate);
outstate = new Bundle();
outstate.putString("num_editTexts", "1");
}
}
|
import java.io.*;
// thread example using implementing Runnable interface
class ThreadExampleRunnable implements Runnable
{
public void run()
{
System.out.println("Thread starting....");
}
public static void main(String args[])
{
ThreadExampleRunnable ter = new ThreadExampleRunnable();
Thread t = new Thread(ter);
t.start();
}
} |
package com.najasoftware.fdv.adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.najasoftware.fdv.R;
import com.najasoftware.fdv.model.Produto;
import com.squareup.picasso.Picasso;
import org.parceler.apache.commons.lang.StringUtils;
import java.util.List;
/**
* Created by Lemoel Marques - NajaSoftware on 08/04/2016.
* lemoel@gmail.com
*/
public class ProdutosAdapter extends RecyclerView.Adapter<ProdutosAdapter.ProdutosViewHolder> {
protected static final String TAG = "fdv";
private final List<Produto> produtos;
private final Context context;
private ProdutoOnClickListener produtoOnClickListener;
public ProdutosAdapter(Context context, List<Produto> produtos, ProdutoOnClickListener
produtoOnClickListener) {
this.context = context;
this.produtos = produtos;
this.produtoOnClickListener = produtoOnClickListener;
}
@Override
public int getItemCount() {
return this.produtos != null ? this.produtos.size() : 0;
}
@Override
public ProdutosViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.adapter_produto, viewGroup, false);
ProdutosViewHolder holder = new ProdutosViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(final ProdutosViewHolder holder, final int position) {
// Atualiza a view
Produto produto = produtos.get(position);
holder.tNome.setText(produto.getNome());
holder.tPreco.setText("R$ " + produto.getPreco().toString());
holder.tCategoria.setText(produto.getCategoria().getNome());
holder.tDescricao.setText(produto.getDescricao());
holder.tvProdutoID.setText("Cod: " + produto.getId().toString().trim());
// Faz o download da foto e mostra o ProgressBar
if (StringUtils.isNotBlank(produto.getUrlFoto())) {
//Caso exista imagem habilita a area para mostrar na view.
holder.img.setVisibility(View.VISIBLE);
holder.progress.setVisibility(View.VISIBLE);
Picasso.with(context).load(produto.getUrlFoto()).fit().into(holder.img,
new com.squareup.picasso.Callback() {
@Override
public void onSuccess() {
holder.progress.setVisibility(View.GONE); // download ok
}
@Override
public void onError() {
holder.progress.setVisibility(View.GONE);
}
});
} else {
holder.img.setVisibility(View.GONE);
}
// Click
if (produtoOnClickListener != null) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// A variável position é final
produtoOnClickListener.onClickProduto(holder.itemView, position);
}
});
}
}
public interface ProdutoOnClickListener {
public void onClickProduto(View view, int idx);
}
// ViewHolder com as views
public static class ProdutosViewHolder extends RecyclerView.ViewHolder {
public TextView tNome;
public TextView tPreco;
public TextView tDescricao;
public TextView tCategoria;
public TextView tvProdutoID;
CardView cardView;
ImageView img;
ProgressBar progress;
public ProdutosViewHolder(View view) {
super(view);
img = (ImageView) view.findViewById(R.id.img_produto);
progress = (ProgressBar) view.findViewById(R.id.progressImg_produto);
// Cria as views para salvar no ViewHolder
tNome = (TextView) view.findViewById(R.id.tvProdutoNome);
tPreco = (TextView) view.findViewById(R.id.tvPreco);
tDescricao = (TextView) view.findViewById(R.id.tvDescricao);
tCategoria = (TextView) view.findViewById(R.id.tvCategoria);
cardView = (CardView) view.findViewById(R.id.card_view_produto);
tvProdutoID = (TextView) view.findViewById(R.id.tvProdutoID);
}
}
}
|
package com.cs.casino.promotion;
import com.cs.bonus.Bonus;
import com.cs.casino.bonus.BonusDto;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static javax.xml.bind.annotation.XmlAccessType.FIELD;
/**
* @author Hadi Movaghar
*/
@XmlRootElement
@XmlAccessorType(FIELD)
public class PromotionDto {
@XmlElement
@Nonnull
@NotNull(message = "promotionDto.name.notNull")
private String name;
@XmlElement
@Nonnull
@NotNull(message = "promotionDto.validTo.notNull")
private Date validTo;
@XmlElement
@Nullable
private Date activationDate;
@XmlElement
@Nullable
private List<BonusDto> bonusList;
public PromotionDto() {
}
public void setName(@Nonnull final String name) {
this.name = name;
}
public void setValidTo(@Nonnull final Date validTo) {
this.validTo = validTo;
}
public void setActivationDate(@Nonnull final Date activationDate) {
this.activationDate = activationDate;
}
public void setBonusList(@Nullable final List<Bonus> bonusList) {
final List<BonusDto> bonusDtos = new ArrayList<>();
if (bonusList != null) {
for (final Bonus bonus : bonusList) {
final BonusDto bonusDto = new BonusDto();
bonusDto.setName(bonus.getName());
bonusDto.setValidTo(bonus.getValidTo());
bonusDto.setAmount(bonus.getAmount() != null ? bonus.getAmount().getEuroValueInBigDecimal() : null);
bonusDto.setQuantity(bonus.getQuantity());
// bonusDto.setUsedDate(bonus.get); TODO
bonusDtos.add(bonusDto);
}
}
this.bonusList = bonusDtos;
}
}
|
package model;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Statement;
import entity.Level;
/**
* Class DAOLevel
* @author Group6
*
*/
public class DAOLevel extends DAOEntity<Level> {
public DAOLevel(Connection connection) throws SQLException {
super(connection);
}
@Override
public boolean create(Level entity) {
// Not implemented
return false;
}
@Override
public boolean delete(Level entity) {
// Not implemented
return false;
}
@Override
public boolean update(Level entity) {
// Not implemented
return false;
}
/**
* method findlevel Fills a 2-Dimensional char Array with the characters from the database
* @param id
* @return char[][]
*/
public char[][] findlevel(final int id) {
char[][] elements = new char[25][51];
String strCurrentline = null;
int i= 0;
try {
final String sql= "{call FetchLevel(?)}";
final CallableStatement call = this.getConnection().prepareCall(sql);
call.setInt(1, id);
call.execute();
final ResultSet resultSet = call.getResultSet();
call.getMoreResults(Statement.KEEP_CURRENT_RESULT);
while(resultSet.next()) {
strCurrentline=resultSet.getString("map");
for(int j=0; j<51;j++) {
elements[i][j]=strCurrentline.charAt(j);
}
i++;
System.out.print("");
}
}catch (final SQLException e) {e.printStackTrace();}
return elements;}
@Override
public Level find(String code) {
//Not implemented
return null;}
@Override
public Level find(int id) {
//Not implemented
return null;}
}
|
package com.example.devansh.inclass05;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class MainActivity extends AppCompatActivity {
private ArrayList<String> keywordList = new ArrayList<String>();
private ArrayList<String> urls = new ArrayList<>();
private int currentPhoto = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((ImageView)findViewById(R.id.imgDisplay)).setImageBitmap(null);
setTitle("Main Activity");
// ------------------------------------------------------------------------------------
((findViewById(R.id.btnPrevious))).setVisibility(View.INVISIBLE);
((findViewById(R.id.btnNext))).setVisibility(View.INVISIBLE);
// ------------ Get Keywords API ----------------------------- :^) ------------- :) ---- :)
if(isConnected()){
Log.d("test", "Is connected to internet. Ready to connect yayayayayy");
new GetDataAsync(keywordList).execute("http://dev.theappsdr.com/apis/photos/keywords.php");
}
else {
Log.d("test", "Is not connected to internet. You poopoo.");
Toast.makeText(MainActivity.this, "Not Connected to Internet", Toast.LENGTH_SHORT).show();
}
}
///////////////////////////////////////////////////////////////////////////
// All the OnClick Methods :D:D:D:D:D:D:D:D
///////////////////////////////////////////////////////////////////////////
public void onGoClick(View view){
Log.d("test", "Button was clicked");
final String[] keywordArray = new String[keywordList.size()];
for(int i = 0; i < keywordArray.length; i++) {
keywordArray[i] = keywordList.get(i);
Log.d("test", "THE keywords ARE " + keywordArray[i]);
}
// Our AlertDialog :D
AlertDialog.Builder keywordPicker = new AlertDialog.Builder(MainActivity.this);
keywordPicker.setTitle("Choose a Keyword")
.setSingleChoiceItems(keywordArray,-1, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("test", keywordArray[i] + " was pressed!");
((TextView)findViewById(R.id.txtSearch)).setText(keywordArray[i]);
// Reset URL (for photos) array list
urls = new ArrayList<>();
currentPhoto = 0;
// Dismiss dialogInterface
dialogInterface.dismiss();
// After keyword is selected, use another AsyncTask to connect to the Get URLs API
// Retrieve image urls related to the selected keyword
if(isConnected()){
Log.d("test", "Is connected to internet. Ready to connect to Get URLs :D");
new GetLinksAsync(urls,((TextView)findViewById(R.id.txtSearch)).getText() + "").execute("http://dev.theappsdr.com/apis/photos/index.php");
}
else {
Log.d("test", "Is not connected to internet. You poopoo.");
Toast.makeText(MainActivity.this, "Not Connected to Internet", Toast.LENGTH_SHORT).show();
}
//Log.d("We got URLS")
}
});
final AlertDialog alert = keywordPicker.create();
alert.show();
}
public void onPrevClick(View view){
// If currentPhoto is already 0, go to the last photo instead
if(currentPhoto == 0)
currentPhoto = urls.size()-1;
else
currentPhoto--;
if(isConnected()){
Log.d("test", "Is connected to internet. Ready to connect to Get URLs :D");
new LoadingImages(((ImageView)findViewById(R.id.imgDisplay)),MainActivity.this).execute(urls.get(currentPhoto));
}
else {
Log.d("test", "Is not connected to internet. You poopoo.");
Toast.makeText(MainActivity.this, "Not Connected to Internet", Toast.LENGTH_SHORT).show();
}
}
public void onNextClick(View view){
if(currentPhoto == urls.size()-1)
currentPhoto = 0;
else
currentPhoto++;
if(isConnected()){
Log.d("test", "Is connected to internet. Ready to connect to Get URLs :D");
new LoadingImages(((ImageView)findViewById(R.id.imgDisplay)),MainActivity.this).execute(urls.get(currentPhoto));
}
else {
Log.d("test", "Is not connected to internet. You poopoo.");
Toast.makeText(MainActivity.this, "Not Connected to Internet", Toast.LENGTH_SHORT).show();
}
}
///////////////////////////////////////////////////////////////////////////
// AsyncTask to get keywords (keywords api) when the Activity starts
///////////////////////////////////////////////////////////////////////////
private class GetDataAsync extends AsyncTask<String, Void, ArrayList<String> >{
public GetDataAsync(ArrayList<String> keywords) {
this.keywords = keywords;
}
private ArrayList<String> keywords;
ProgressDialog loadDictionary;
@Override
protected void onPreExecute() {
loadDictionary = new ProgressDialog((Context)MainActivity.this);
loadDictionary.setCancelable(false);
loadDictionary.setMessage("Loading Dictionary ...");
loadDictionary.setProgress(0);
loadDictionary.show();
}
@Override
protected ArrayList<String> doInBackground(String... strings) {
StringTokenizer st = null;
try {
URL url = new URL(strings[0]);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
// Read the line from the keywords API
// There is only one line, so not using a while loop :')
st = new StringTokenizer(reader.readLine(), ";");
// Go through and separate based on String Tokenizer (delim = ;)
while(st.hasMoreTokens() ){
keywords.add(st.nextToken()); // add :'))))
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return keywords;
}
@Override
protected void onPostExecute(ArrayList<String> strings) {
if(strings != null){
Log.d("test", strings.toString());
loadDictionary.setMessage("Dictionary Loaded!");
loadDictionary.setProgress(100);
loadDictionary.dismiss();
loadDictionary.setProgress(0);
}else {
Log.d("test", "s is null");
}
}
}
///////////////////////////////////////////////////////////////////////////
// AsyncTask to get the image URLs based on the user's chosen keyword
///////////////////////////////////////////////////////////////////////////
private class GetLinksAsync extends AsyncTask<String, Void, ArrayList<String> >{
private ArrayList<String> urls;
private String keyword;
public GetLinksAsync(ArrayList<String> keywords, String key) {
this.keyword = key;
this.urls = keywords;
Log.d("test", "\nKeyword is " + key);
Log.d("test", "Array of URLs is " + keywords.toString());
}
@Override
protected ArrayList<String> doInBackground(String... strings) {
StringBuilder stringBuilder = new StringBuilder();
try {
String x = strings[0] + "?" + "keyword=" + keyword;
URL url = new URL(x);
Log.d("test",x);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = "";
while((line = reader.readLine()) != null){
urls.add(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return urls;
}
@Override
protected void onPostExecute(ArrayList<String> strings) {
if(strings != null && !strings.isEmpty()){
Log.d("test", strings.toString());
Log.d("test", "The URLS are " + strings.toString());
if(isConnected()){
Log.d("test", "Is connected to internet. Ready to connect to Get URLs :D");
new LoadingImages(((ImageView)findViewById(R.id.imgDisplay)),MainActivity.this).execute(strings.get(0));
}
else {
Log.d("test", "Is not connected to internet. You poopoo.");
Toast.makeText(MainActivity.this, "Not Connected to Internet", Toast.LENGTH_SHORT).show();
}
if(strings.size() > 1) {
((findViewById(R.id.btnPrevious))).setVisibility(View.VISIBLE);
((findViewById(R.id.btnNext))).setVisibility(View.VISIBLE);
}else{
((findViewById(R.id.btnPrevious))).setVisibility(View.INVISIBLE);
((findViewById(R.id.btnNext))).setVisibility(View.INVISIBLE);
}
// Set buttons to visible :D Now that we have images
}else {
Toast.makeText(MainActivity.this, "No Images Found", Toast.LENGTH_SHORT).show();
((ImageView)findViewById(R.id.imgDisplay)).setImageBitmap(null);
((findViewById(R.id.btnPrevious))).setVisibility(View.INVISIBLE);
((findViewById(R.id.btnNext))).setVisibility(View.INVISIBLE);
Log.d("test", "URL list is null");
}
// Image Stuff
// Call LoadingImages AsyncTask to load and set the first image
}
}
///////////////////////////////////////////////////////////////////////////
// Aileeen .. OMG
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// Other Methods
///////////////////////////////////////////////////////////////////////////
private boolean isConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected() ||
(networkInfo.getType() != ConnectivityManager.TYPE_WIFI
&& networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
return false;
}
return true;
}
}
|
package com.citibank.ods.persistence.pl.dao.rdb.oracle;
import java.math.BigInteger;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import com.citibank.ods.common.connection.rdb.ManagedRdbConnection;
import com.citibank.ods.common.dataset.DataSet;
import com.citibank.ods.common.dataset.DataSetRow;
import com.citibank.ods.common.dataset.ResultSetDataSet;
import com.citibank.ods.common.exception.NoRowsReturnedException;
import com.citibank.ods.common.exception.UnexpectedException;
import com.citibank.ods.common.util.ODSConstraintDecoder;
import com.citibank.ods.entity.pl.BaseTplBkrPortfMgmtEntity;
import com.citibank.ods.entity.pl.TplBkrPortfMgmtMovEntity;
import com.citibank.ods.entity.pl.valueobject.TplBkrPortfMgmtMovEntityVO;
import com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtMovDAO;
import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory;
import com.citibank.ods.persistence.util.CitiStatement;
/**
* @author Hamilton Matos
*/
public class OracleTplBkrPortfMgmtMovDAO extends BaseOracleTplBkrPortfMgmtDAO
implements TplBkrPortfMgmtMovDAO
{
private static final String C_TABLE_COLUMNS = "PROD_ACCT_CODE,PROD_UNDER_ACCT_CODE,BKR_CNPJ_NBR,BOVESPA_CUR_ACCT_NBR,BOVESPA_INVST_ACCT_NBR,BMF_CUR_ACCT_NBR,BMF_INVST_ACCT_NBR,LAST_UPD_DATE,LAST_UPD_USER_ID,OPERN_CODE";
private static final String C_OPERN_CODE = "OPERN_CODE";
private static final String C_OPERN_TEXT = "OPERN_TEXT";
private static final String C_TABLE_NAME = C_PL_SCHEMA
+ "TPL_BKR_PORTF_MGMT_MOV";
private static final String C_TPL_BKR_PORTF_MGMT_MOV = C_PL_SCHEMA
+ ".TPL_BKR_PORTF_MGMT_MOV";
private static final String C_TO3_PROD_ACCT_PORTF_MGMT = C_O3_SCHEMA
+ ".TO3_PROD_ACCT_PORTF_MGMT";
private static final String C_TO3_PRODUCT_ACCOUNT = C_O3_SCHEMA
+ ".TO3_PRODUCT_ACCOUNT";
private static final String C_TPL_CUSTOMER_PRVT = C_PL_SCHEMA
+ ".TPL_CUSTOMER_PRVT";
private static final String C_ALIAS_TPL_BKR_PORTF_MGMT_MOV = "BKR_PORTF_MGMT_MOV";
private static final String C_ALIAS_TO3_PROD_ACCT_PORTF_MGMT = "PROD_ACCT_PRODUCT_ACCOUNT";
private static final String C_ALIAS_TO3_PRODUCT_ACCOUNT = "PRODUCT_ACCOUNT";
private static final String C_ALIAS_TPL_CUSTOMER_PRVT = "CUSTOMER_PRVT";
private static final String C_CUST_NBR = "CUST_NBR";
private static final String C_CUST_NAME = "CUST_NAME";
private static final String C_CUST_FULL_NAME_TEXT = "CUST_FULL_NAME_TEXT";
private static final String C_ALIAS_BROKER = "BROKER";
private static final String C_TABLE_BROKER = C_PL_SCHEMA + "TPL_BROKER";
private static final String C_ALIAS_PORTF_MGMT = "PORTF_MGMT";
private static final String C_ALIAS_POINT_ACCT_INVST = "POINT_INVST";
private static final String C_ALIAS_PRODUCT_ACCOUNT = "PRODUCT_ACCOUNT";
private static final String C_ALIAS_RELATION_PRVT = "RELATION_PRVT";
private static final String C_TABLE_PROD_ACCT_PORTF_MGMT = C_O3_SCHEMA
+ "TO3_PROD_ACCT_PORTF_MGMT";
private static final String C_TABLE_POINT_ACCT_INVST = C_BG_SCHEMA
+ "TBG_POINT_ACCT_INVST";
private static final String C_TABLE_PRODUCT_ACCOUNT = C_O3_SCHEMA
+ "TO3_PRODUCT_ACCOUNT";
private static final String C_TABLE_RELATION_PRVT = C_PL_SCHEMA
+ "TPL_RELATION_PRVT";
private static final String C_TABLE_BKR_PORTF_MGMT_MOV = C_PL_SCHEMA
+ "TPL_BKR_PORTF_MGMT_MOV";
private String C_REC_STAT_CODE = "REC_STAT_CODE";
private String C_REC_STAT_TEXT = "REC_STAT_TEXT";
private static final String C_QTY_PORTF_MGMT = "QTY_PORTF_MGMT";
private static final String C_CPF_CNPJ_NBR = "CPF_CNPJ_NBR";
private static final String C_COUNT_USR = "COUNT_USR";
private static final String C_CUST_CPF_CNPJ_NBR = "CUST_CPF_CNPJ_NBR";
private static final String C_TABLE_CUSTOMER_PRVT = C_PL_SCHEMA
+ "TPL_CUSTOMER_PRVT";
/**
* Insere uma nova linha na tabela tpl_bkr_portf_mgmt_mov com os dados da
* entidade correspondente passada como parâmetro
*/
public TplBkrPortfMgmtMovEntity insert(
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "INSERT INTO " + C_TABLE_NAME + " ( " );
query.append( C_PROD_ACCT_CODE + ", " );
query.append( C_PROD_UNDER_ACCT_CODE + ", " );
query.append( C_BKR_CNPJ_NBR + ", " );
query.append( C_BOVESPA_CUR_ACCT_NBR + ", " );
query.append( C_BOVESPA_INVST_ACCT_NBR + ", " );
query.append( C_BMF_CUR_ACCT_NBR + ", " );
query.append( C_BMF_INVST_ACCT_NBR + ", " );
query.append( C_LAST_UPD_DATE + ", " );
query.append( C_LAST_UPD_USER_ID + ", " );
query.append( C_OPERN_CODE + ")" );
query.append( " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
TplBkrPortfMgmtMovEntityVO tplBkrPortfMgmtMovEntityVO = ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtMovEntity_.getData();
int count = 1;
if ( tplBkrPortfMgmtMovEntityVO.getProdAcctCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getProdAcctCode().equals( "" ) )
{
preparedStatement.setLong(
count++,
tplBkrPortfMgmtMovEntity_.getData().getProdAcctCode().longValue() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getProdUnderAcctCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getProdUnderAcctCode().equals( "" ) )
{
preparedStatement.setLong(
count++,
tplBkrPortfMgmtMovEntity_.getData().getProdUnderAcctCode().longValue() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBkrCnpjNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBkrCnpjNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBkrCnpjNbr() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBovespaCurAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBovespaCurAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBovespaCurAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBovespaInvstAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBovespaInvstAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBovespaInvstAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBmfCurAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBmfCurAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBmfCurAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBmfInvstAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBmfInvstAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBmfInvstAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getLastUpdDate() != null
&& !tplBkrPortfMgmtMovEntityVO.getLastUpdDate().equals( "" ) )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplBkrPortfMgmtMovEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getLastUpdUserId() != null
&& !tplBkrPortfMgmtMovEntityVO.getLastUpdUserId().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getLastUpdUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getOpernCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getOpernCode().equals( "" ) )
{
preparedStatement.setString(
count++,
( ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtMovEntity_.getData() ).getOpernCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
preparedStatement.replaceParametersInQuery(query.toString());
preparedStatement.executeUpdate();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return tplBkrPortfMgmtMovEntity_;
}
/**
* Atualiza uma linha na tabela tpl_bkr_portf_mgmt_mov de acordo com ID
* contido na entidade passada como parâmetro.
*/
public TplBkrPortfMgmtMovEntity update(
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "UPDATE " + C_TABLE_NAME + " SET " );
query.append( C_BOVESPA_CUR_ACCT_NBR + " = ?, " );
query.append( C_BOVESPA_INVST_ACCT_NBR + " = ?, " );
query.append( C_BMF_CUR_ACCT_NBR + " = ?, " );
query.append( C_BMF_INVST_ACCT_NBR + " = ?, " );
query.append( C_LAST_UPD_DATE + " = ?, " );
query.append( C_LAST_UPD_USER_ID + " = ?, " );
query.append( C_OPERN_CODE + " = ? " );
query.append( " WHERE " );
query.append( C_BKR_CNPJ_NBR + " = ? AND " );
query.append( C_PROD_ACCT_CODE + " = ? AND " );
query.append( C_PROD_UNDER_ACCT_CODE + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
TplBkrPortfMgmtMovEntityVO tplBkrPortfMgmtMovEntityVO = ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtMovEntity_.getData();
int count = 1;
if ( tplBkrPortfMgmtMovEntityVO.getBovespaCurAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBovespaCurAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBovespaCurAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBovespaInvstAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBovespaInvstAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBovespaInvstAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBmfCurAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBmfCurAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBmfCurAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBmfInvstAcctNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBmfInvstAcctNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBmfInvstAcctNbr() );
}
else
{
preparedStatement.setString( count++, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getLastUpdDate() != null
&& !tplBkrPortfMgmtMovEntityVO.getLastUpdDate().equals( "" ) )
{
preparedStatement.setTimestamp(
count++,
new Timestamp(
tplBkrPortfMgmtMovEntity_.getData().getLastUpdDate().getTime() ) );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getLastUpdUserId() != null
&& !tplBkrPortfMgmtMovEntityVO.getLastUpdUserId().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getLastUpdUserId() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getOpernCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getOpernCode().equals( "" ) )
{
preparedStatement.setString(
count++,
( ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtMovEntity_.getData() ).getOpernCode() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getBkrCnpjNbr() != null
&& !tplBkrPortfMgmtMovEntityVO.getBkrCnpjNbr().equals( "" ) )
{
preparedStatement.setString(
count++,
tplBkrPortfMgmtMovEntity_.getData().getBkrCnpjNbr() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getProdAcctCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getProdAcctCode().equals( "" ) )
{
preparedStatement.setLong(
count++,
tplBkrPortfMgmtMovEntity_.getData().getProdAcctCode().longValue() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
if ( tplBkrPortfMgmtMovEntityVO.getProdUnderAcctCode() != null
&& !tplBkrPortfMgmtMovEntityVO.getProdUnderAcctCode().equals( "" ) )
{
preparedStatement.setLong(
count++,
tplBkrPortfMgmtMovEntity_.getData().getProdUnderAcctCode().longValue() );
}
else
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null );
}
preparedStatement.replaceParametersInQuery(query.toString());
preparedStatement.executeUpdate();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return tplBkrPortfMgmtMovEntity_;
}
/**
* Remove uma linha na tabela tpl_bkr_portf_mgmt_mov de acordo com ID passado
* como parâmetro.
*/
public TplBkrPortfMgmtMovEntity delete(
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer sqlQuery = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
sqlQuery.append( "DELETE FROM " );
sqlQuery.append( C_TABLE_NAME );
sqlQuery.append( " WHERE " );
sqlQuery.append( C_PROD_ACCT_CODE + " = ? AND " );
sqlQuery.append( C_PROD_UNDER_ACCT_CODE + " = ? AND " );
sqlQuery.append( C_BKR_CNPJ_NBR + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() ));
preparedStatement.setLong(
1,
tplBkrPortfMgmtMovEntity_.getData().getProdAcctCode().longValue() );
preparedStatement.setLong(
2,
tplBkrPortfMgmtMovEntity_.getData().getProdUnderAcctCode().longValue() );
preparedStatement.setString( 3,
tplBkrPortfMgmtMovEntity_.getData().getBkrCnpjNbr().toString() );
preparedStatement.replaceParametersInQuery(sqlQuery.toString());
preparedStatement.executeUpdate();
return tplBkrPortfMgmtMovEntity_;
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
/**
* Procura um registro ou um conjunto de registros, uma linha na tabela
* TPL_BROKERMov de acordo com os parametos relacionados a opções de buscas na
* tela. Este método deve ser utilizado para consulta em lista com filtros.
* @param StringopernCode_ StringbkrAddrText_ BigIntegerbkrApprvCrLimDlrAmt_
* BigIntegerbkrApprvCrLimLcyAmt_ DatebkrApprvDate_
* StringbkrApprvStatCode_ StringbkrAuthProcSitText_
* StringbkrBmfMktCode_ StringbkrBovespaMktCode_ StringbkrCnpjNbr_
* StringbkrCommentText_ StringbkrNameText_ BigIntegerbkrRbtBmfRate_
* BigIntegerbkrRbtBovespaRate_ BigIntegerbkrReqCrLimDlrAmt_
* BigIntegerbkrReqCrLimLcyAmt_ DatebkrReqDate_ DatebkrRnwDate_
* StringbkrSuplServText_ DatelastUpdDate_ StringlastUpdUserId_*
* @returns dataSet_
* @throws UnexpectedException
* @author Hamilton Matos
*/
// public DataSet list( String opernCode_, String bkrAddrText_,
// BigDecimal bkrApprvCrLimDlrAmt_,
// BigDecimal bkrApprvCrLimLcyAmt_, Date bkrApprvDate_,
// String bkrApprvStatCode_, String bkrAuthProcSitText_,
// String bkrBmfMktCode_, String bkrBovespaMktCode_,
// String bkrCnpjNbr_, String bkrCommentText_,
// String bkrNameText_, BigDecimal bkrRbtBmfRate_,
// BigDecimal bkrRbtBovespaRate_,
// BigDecimal bkrReqCrLimDlrAmt_,
// BigDecimal bkrReqCrLimLcyAmt_, Date bkrReqDate_,
// Date bkrRnwDate_, String bkrSuplServText_,
// Date lastUpdDate_, String lastUpdUserId_ )
// throws UnexpectedException
// {
//
// ResultSet resultSet = null;
// ResultSetDataSet resultSetDataSet = null;
// CitiStatement preparedStatement = null;
// ManagedRdbConnection connection = null;
// StringBuffer sqlQuery = new StringBuffer();
//
// try
// {
// connection = OracleODSDAOFactory.getConnection();
// sqlQuery.append( "SELECT " );
//
// sqlQuery.append( C_TABLE_COLUMNS );
// sqlQuery.append( " FROM " );
// sqlQuery.append( C_TABLE_NAME );
// sqlQuery.append( "WHERE " );
//
// if ( opernCode_ != null && !opernCode_.equals( "" ) )
// {
// sqlQuery.append( " OPERN_CODE = ? " );
// }
//
// if ( bkrAddrText_ != null && !bkrAddrText_.equals( "" ) )
// {
// sqlQuery.append( " BKR_ADDR_TEXT = ? AND " );
// }
//
// if ( bkrApprvCrLimDlrAmt_ != null && !bkrApprvCrLimDlrAmt_.equals( "" ) )
// {
// sqlQuery.append( " BKR_APPRV_CR_LIM_DLR_AMT = ? AND " );
// }
//
// if ( bkrApprvCrLimLcyAmt_ != null && !bkrApprvCrLimLcyAmt_.equals( "" ) )
// {
// sqlQuery.append( " BKR_APPRV_CR_LIM_LCY_AMT = ? AND " );
// }
//
// if ( bkrApprvDate_ != null && !bkrApprvDate_.equals( "" ) )
// {
// sqlQuery.append( " BKR_APPRV_DATE = ? AND " );
// }
//
// if ( bkrApprvStatCode_ != null && !bkrApprvStatCode_.equals( "" ) )
// {
// sqlQuery.append( " BKR_APPRV_STAT_CODE = ? AND " );
// }
//
// if ( bkrAuthProcSitText_ != null && !bkrAuthProcSitText_.equals( "" ) )
// {
// sqlQuery.append( " BKR_AUTH_PROC_SIT_TEXT = ? AND " );
// }
//
// if ( bkrBmfMktCode_ != null && !bkrBmfMktCode_.equals( "" ) )
// {
// sqlQuery.append( " BKR_BMF_MKT_CODE = ? AND " );
// }
//
// if ( bkrBovespaMktCode_ != null && !bkrBovespaMktCode_.equals( "" ) )
// {
// sqlQuery.append( " BKR_BOVESPA_MKT_CODE = ? AND " );
// }
//
// if ( bkrCnpjNbr_ != null && !bkrCnpjNbr_.equals( "" ) )
// {
// sqlQuery.append( " BKR_CNPJ_NBR = ? AND " );
// }
//
// if ( bkrCommentText_ != null && !bkrCommentText_.equals( "" ) )
// {
// sqlQuery.append( " BKR_COMMENT_TEXT = ? AND " );
// }
//
// if ( bkrNameText_ != null && !bkrNameText_.equals( "" ) )
// {
// sqlQuery.append( " BKR_NAME_TEXT = ? AND " );
// }
//
// if ( bkrRbtBmfRate_ != null && !bkrRbtBmfRate_.equals( "" ) )
// {
// sqlQuery.append( " BKR_RBT_BMF_RATE = ? AND " );
// }
//
// if ( bkrRbtBovespaRate_ != null && !bkrRbtBovespaRate_.equals( "" ) )
// {
// sqlQuery.append( " BKR_RBT_BOVESPA_RATE = ? AND " );
// }
//
// if ( bkrReqCrLimDlrAmt_ != null && !bkrReqCrLimDlrAmt_.equals( "" ) )
// {
// sqlQuery.append( " BKR_REQ_CR_LIM_DLR_AMT = ? AND " );
// }
//
// if ( bkrReqCrLimLcyAmt_ != null && !bkrReqCrLimLcyAmt_.equals( "" ) )
// {
// sqlQuery.append( " BKR_REQ_CR_LIM_LCY_AMT = ? AND " );
// }
//
// if ( bkrReqDate_ != null && !bkrReqDate_.equals( "" ) )
// {
// sqlQuery.append( " BKR_REQ_DATE = ? AND " );
// }
//
// if ( bkrRnwDate_ != null && !bkrRnwDate_.equals( "" ) )
// {
// sqlQuery.append( " BKR_RNW_DATE = ? AND " );
// }
//
// if ( bkrSuplServText_ != null && !bkrSuplServText_.equals( "" ) )
// {
// sqlQuery.append( " BKR_SUPL_SERV_TEXT = ? AND " );
// }
//
// if ( lastUpdDate_ != null && !lastUpdDate_.equals( "" ) )
// {
// sqlQuery.append( " TRUNC(LAST_UPD_DATE) = ? " );
// }
//
// if ( lastUpdUserId_ != null && !lastUpdUserId_.equals( "" ) )
// {
// sqlQuery.append( " LAST_UPD_USER_ID = ? " );
// }
//
// sqlQuery.append( " ORDER BY BKR_CNPJ_NBR" );
//
// preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() ));
//
// int count = 1;
//
// if ( opernCode_ != null || !opernCode_.equals( "" ) )
// {
// preparedStatement.setString( count++, opernCode_ );
// }
//
// if ( bkrAddrText_ != null || !bkrAddrText_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrAddrText_ );
// }
//
// if ( bkrApprvCrLimDlrAmt_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrApprvCrLimDlrAmt_ );
// }
//
// if ( bkrApprvCrLimLcyAmt_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrApprvCrLimLcyAmt_ );
// }
//
// if ( bkrApprvDate_ != null || !bkrApprvDate_.equals( "" ) )
// {
// preparedStatement.setDate( count++, bkrApprvDate_ );
// }
//
// if ( bkrApprvStatCode_ != null || !bkrApprvStatCode_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrApprvStatCode_ );
// }
//
// if ( bkrAuthProcSitText_ != null || !bkrAuthProcSitText_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrAuthProcSitText_ );
// }
//
// if ( bkrBmfMktCode_ != null || !bkrBmfMktCode_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrBmfMktCode_ );
// }
//
// if ( bkrBovespaMktCode_ != null || !bkrBovespaMktCode_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrBovespaMktCode_ );
// }
//
// if ( bkrCnpjNbr_ != null || !bkrCnpjNbr_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrCnpjNbr_ );
// }
//
// if ( bkrCommentText_ != null || !bkrCommentText_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrCommentText_ );
// }
//
// if ( bkrNameText_ != null || !bkrNameText_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrNameText_ );
// }
//
// if ( bkrRbtBmfRate_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrRbtBmfRate_ );
// }
//
// if ( bkrRbtBovespaRate_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrRbtBovespaRate_ );
// }
//
// if ( bkrReqCrLimDlrAmt_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrReqCrLimDlrAmt_ );
// }
//
// if ( bkrReqCrLimLcyAmt_ != null )
// {
// preparedStatement.setBigDecimal( count++, bkrReqCrLimLcyAmt_ );
// }
//
// if ( bkrReqDate_ != null || !bkrReqDate_.equals( "" ) )
// {
// preparedStatement.setDate( count++, bkrReqDate_ );
// }
//
// if ( bkrRnwDate_ != null || !bkrRnwDate_.equals( "" ) )
// {
// preparedStatement.setDate( count++, bkrRnwDate_ );
// }
//
// if ( bkrSuplServText_ != null || !bkrSuplServText_.equals( "" ) )
// {
// preparedStatement.setString( count++, bkrSuplServText_ );
// }
//
// if ( lastUpdDate_ != null || !lastUpdDate_.equals( "" ) )
// {
// preparedStatement.setDate( count++, lastUpdDate_ );
// }
//
// if ( lastUpdUserId_ != null || !lastUpdUserId_.equals( "" ) )
// {
// preparedStatement.setString( count++, lastUpdUserId_ );
// }
//
// preparedStatement.replaceParametersInQuery(sqlQuery.toString());
// resultSet = preparedStatement.executeQuery();
//
// resultSetDataSet = new ResultSetDataSet( resultSet );
//
// resultSet.close();
// }
// catch ( SQLException e )
// {
// throw new UnexpectedException( e.getErrorCode(),
// C_ERROR_EXECUTING_STATEMENT, e );
// }
// finally
// {
// closeStatement( preparedStatement );
// closeConnection( connection );
// }
// return resultSetDataSet;
// }
/**
* Cria uma entidade representando um registro da tabela
* tpl_bkr_portf_mgmt_mov com os dados do ID passado como parâmetro
*/
public BaseTplBkrPortfMgmtEntity find(
BaseTplBkrPortfMgmtEntity tplBkrPortfMgmtEntity_ )
throws UnexpectedException
{
ResultSet resultSet = null;
CitiStatement preparedStatement = null;
ManagedRdbConnection connection = null;
StringBuffer sqlQuery = new StringBuffer();
ArrayList tplBkrPortfMgmtMovEntities = new ArrayList();
BaseTplBkrPortfMgmtEntity tplBkrPortfMgmtEntity = null;
try
{
connection = OracleODSDAOFactory.getConnection();
sqlQuery.append( "SELECT " );
sqlQuery.append( C_TABLE_COLUMNS );
sqlQuery.append( " FROM " );
sqlQuery.append( C_TABLE_NAME );
sqlQuery.append( " WHERE " );
sqlQuery.append( C_PROD_ACCT_CODE + " = ? " );
sqlQuery.append( " AND " );
sqlQuery.append( C_PROD_UNDER_ACCT_CODE + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() ));
preparedStatement.setLong(
1,
( tplBkrPortfMgmtEntity_.getData().getProdAcctCode() ).longValue() );
preparedStatement.setLong(
2,
( tplBkrPortfMgmtEntity_.getData().getProdUnderAcctCode() ).longValue() );
preparedStatement.replaceParametersInQuery(sqlQuery.toString());
resultSet = preparedStatement.executeQuery();
tplBkrPortfMgmtMovEntities = instantiateFromResultSet( resultSet );
if ( tplBkrPortfMgmtMovEntities.size() == 0 )
{
throw new NoRowsReturnedException();
}
else
{
tplBkrPortfMgmtEntity = ( BaseTplBkrPortfMgmtEntity ) tplBkrPortfMgmtMovEntities.get( 0 );
}
return tplBkrPortfMgmtEntity;
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
private ArrayList instantiateFromResultSet( ResultSet resultSet_ )
throws UnexpectedException
{
TplBkrPortfMgmtMovEntityVO tplBkrPortfMgmtMovEntityVO;
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity;
ArrayList tplBkrPortfMgmtEntities = new ArrayList();
try
{
while ( resultSet_.next() )
{
tplBkrPortfMgmtMovEntity = new TplBkrPortfMgmtMovEntity();
tplBkrPortfMgmtMovEntity.getData().setProdAcctCode(
new BigInteger(
resultSet_.getString( C_PROD_ACCT_CODE ) ) );
tplBkrPortfMgmtMovEntity.getData().setProdUnderAcctCode(
new BigInteger(
resultSet_.getString( C_PROD_UNDER_ACCT_CODE ) ) );
tplBkrPortfMgmtMovEntity.getData().setBkrCnpjNbr(
resultSet_.getString( C_BKR_CNPJ_NBR ) );
tplBkrPortfMgmtMovEntity.getData().setBovespaCurAcctNbr(
resultSet_.getString( C_BOVESPA_CUR_ACCT_NBR ) );
tplBkrPortfMgmtMovEntity.getData().setBovespaInvstAcctNbr(
resultSet_.getString( C_BOVESPA_INVST_ACCT_NBR ) );
tplBkrPortfMgmtMovEntity.getData().setBmfCurAcctNbr(
resultSet_.getString( C_BMF_CUR_ACCT_NBR ) );
tplBkrPortfMgmtMovEntity.getData().setBmfInvstAcctNbr(
resultSet_.getString( C_BMF_INVST_ACCT_NBR ) );
tplBkrPortfMgmtMovEntity.getData().setLastUpdDate(
resultSet_.getDate( C_LAST_UPD_DATE ) );
tplBkrPortfMgmtMovEntity.getData().setLastUpdUserId(
resultSet_.getString( C_LAST_UPD_USER_ID ) );
// Casting para a atribuição das colunas específicas
tplBkrPortfMgmtMovEntityVO = ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtMovEntity.getData();
tplBkrPortfMgmtMovEntityVO.setOpernCode( resultSet_.getString( C_OPERN_CODE ) );
tplBkrPortfMgmtEntities.add( tplBkrPortfMgmtMovEntity );
}
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_INSTANTIATE_FROM_RESULT_SET, e );
}
return tplBkrPortfMgmtEntities;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtMovDAO#exists(com.citibank.ods.entity.pl.TplBkrPortfMgmtMovEntity)
*/
public boolean exists( TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity_ )
{
boolean exists = true;
try
{
this.find( tplBkrPortfMgmtMovEntity_ );
}
catch ( NoRowsReturnedException exception )
{
exists = false;
}
return exists;
}
public DataSet list( String bkrCnpjNbr_, String bkrNameText_,
String custNbr_, String custFullNameText_,
String lastUpdUserId_ ) throws UnexpectedException
{
ResultSet resultSet = null;
ResultSetDataSet resultSetDataSet = null;
CitiStatement preparedStatement = null;
ManagedRdbConnection connection = null;
StringBuffer sqlQuery = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
sqlQuery.append( "SELECT " );
sqlQuery.append( C_TABLE_COLUMNS );
sqlQuery.append( " FROM " );
sqlQuery.append( C_TABLE_NAME );
String criteria = "";
if ( bkrCnpjNbr_ != null && !bkrCnpjNbr_.equals( "" ) )
{
criteria = criteria + C_BKR_CNPJ_NBR + " = ? AND ";
}
if ( bkrNameText_ != null && !bkrNameText_.equals( "" ) )
{
criteria = criteria + "UPPER(" + C_BKR_NAME_TEXT + ") like ? AND ";
}
if ( lastUpdUserId_ != null && !lastUpdUserId_.equals( "" ) )
{
criteria = criteria + "UPPER(" + C_LAST_UPD_USER_ID + ") like ? AND ";
}
if ( criteria.length() > 0 )
{
criteria = criteria.substring( 0, criteria.length() - 5 );
sqlQuery.append( " WHERE " + criteria );
}
sqlQuery.append( " ORDER BY " + C_BKR_CNPJ_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() ));
int count = 1;
if ( bkrCnpjNbr_ != null && !bkrCnpjNbr_.equals( "" ) )
{
preparedStatement.setString( count++, bkrCnpjNbr_ );
}
if ( bkrNameText_ != null && !bkrNameText_.equals( "" ) )
{
preparedStatement.setString( count++, "%" + bkrNameText_.toUpperCase() + "%" );
}
if ( lastUpdUserId_ != null && !lastUpdUserId_.equals( "" ) )
{
preparedStatement.setString( count++, lastUpdUserId_.toUpperCase() );
}
preparedStatement.replaceParametersInQuery(sqlQuery.toString());
resultSet = preparedStatement.executeQuery();
resultSetDataSet = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
String[] codeColumn = { C_OPERN_CODE };
String[] nameColumn = { C_OPERN_TEXT };
resultSetDataSet.outerJoin( ODSConstraintDecoder.decodeOpern(), codeColumn,
codeColumn, nameColumn );
return resultSetDataSet;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtMovDAO#list(java.lang.String,
* java.lang.String, java.math.BigInteger, java.lang.String,
* java.lang.String, java.lang.String, java.lang.String)
*/
public DataSet list( String custNbrSrc_, String custFullNameTextSrc_,
BigInteger curAcctNbr_, String custMnmcNameTextSrc_,
String portfMgmtProdNameSrc_, String prodCodeSrc_,
String lastUpdUserIdSrc_, String loggedUserSrc_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( " SELECT " );
query.append( C_CUST_NBR + ", " + C_CUST_NAME + ", " );
query.append( " COUNT(*) AS " );
query.append( C_QTY_PORTF_MGMT + ", Sum(COUNTER_USER) AS " );
query.append( C_COUNT_USR + ", " + C_CPF_CNPJ_NBR );
query.append( " FROM " );
query.append( " ( " );
query.append( " SELECT " );
query.append( " C." + C_RELTN_CUST_1_NBR + " AS " + C_CUST_NBR + ", D."
+ C_CUST_FULL_NAME_TEXT + " AS " + C_CUST_NAME + ", " );
query.append( " D. " + C_CUST_CPF_CNPJ_NBR + " AS " + C_CPF_CNPJ_NBR
+ ", B." + C_PROD_CODE + " AS " + C_PROD_CODE + ", A."
+ C_PROD_ACCT_CODE + " AS " + C_PROD_ACCT_CODE + ", A."
+ C_PROD_UNDER_ACCT_CODE + " AS " + C_PROD_UNDER_ACCT_CODE
+ ", " );
query.append( " CASE WHEN A. " + C_LAST_UPD_USER_ID + " = ? " );
query.append( " THEN 1 ELSE 0 END AS COUNTER_USER " );
query.append( " FROM " );
query.append( C_TABLE_BKR_PORTF_MGMT_MOV + " A, "
+ C_TABLE_PRODUCT_ACCOUNT + " B, " );
query.append( C_TABLE_RELATION_PRVT + " C, " + C_TABLE_CUSTOMER_PRVT
+ " D, " + C_TABLE_PROD_ACCT_PORTF_MGMT + " E " );
query.append( " WHERE " );
query.append( " A." + C_PROD_ACCT_CODE + " = B." + C_PROD_ACCT_CODE
+ " AND " );
query.append( " A." + C_PROD_UNDER_ACCT_CODE + " = B."
+ C_PROD_UNDER_ACCT_CODE + " AND " );
query.append( " B." + C_RELTN_NBR + " = C." + C_RELTN_NBR + " AND " );
query.append( " (C." + C_RELTN_CUST_1_NBR + " = D." + C_CUST_NBR
+ " OR C." + C_RELTN_CUST_2_NBR + " = D." + C_CUST_NBR
+ " OR C." + C_RELTN_CUST_3_NBR + " = D." + C_CUST_NBR
+ " OR C." + C_RELTN_CUST_4_NBR + " = D." + C_CUST_NBR
+ " OR C." + C_RELTN_CUST_5_NBR + "= D." + C_CUST_NBR
+ ") AND " );
query.append( " E." + C_PROD_ACCT_CODE + " = B." + C_PROD_ACCT_CODE
+ " AND " );
query.append( " E." + C_PROD_UNDER_ACCT_CODE + " = B."
+ C_PROD_UNDER_ACCT_CODE );
String criteria = "";
if ( custNbrSrc_ != null && !"".equals( custNbrSrc_ ) )
{
criteria = criteria + " D." + C_CUST_NBR + " = ? AND ";
}
if ( custFullNameTextSrc_ != null && !"".equals( custFullNameTextSrc_ ) )
{
criteria = criteria + " UPPER(D." + C_CUST_FULL_NAME_TEXT
+ ") LIKE ? AND ";
}
if ( curAcctNbr_ != null && !"".equals( curAcctNbr_ ) )
{
criteria = criteria + " B." + C_CUR_ACCT_NBR + " = ? AND ";
}
if ( custMnmcNameTextSrc_ != null && !"".equals( custMnmcNameTextSrc_ ) )
{
criteria = criteria + " UPPER(E." + C_CUST_MNMC_NAME + ") LIKE ? AND ";
}
if ( portfMgmtProdNameSrc_ != null && !"".equals( portfMgmtProdNameSrc_ ) )
{
criteria = criteria + " UPPER(E." + C_PORTF_MGMT_PROD_NAME
+ ") LIKE ? AND ";
}
if ( prodCodeSrc_ != null && !"".equals( prodCodeSrc_ ) )
{
criteria = criteria + " UPPER(B." + C_PROD_CODE + ") = ? AND ";
}
if ( lastUpdUserIdSrc_ != null && !"".equals( lastUpdUserIdSrc_ ) )
{
criteria = criteria + " A." + C_LAST_UPD_USER_ID + " = ? AND ";
}
if ( criteria.length() > 0 )
{
criteria = criteria.substring( 0, criteria.length() - 5 );
query.append( " AND " + criteria );
}
query.append( " ) TAB_ASS GROUP BY " + C_CUST_NBR + ", " + C_CUST_NAME
+ ", " + C_CPF_CNPJ_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( loggedUserSrc_ != null && !"".equals( loggedUserSrc_ ) )
{
preparedStatement.setString( count++, loggedUserSrc_ );
}
else
{
preparedStatement.setString( count++, "" );
}
if ( custNbrSrc_ != null && !"".equals( custNbrSrc_ ) )
{
preparedStatement.setString( count++, custNbrSrc_ );
}
if ( custFullNameTextSrc_ != null && !"".equals( custFullNameTextSrc_ ) )
{
preparedStatement.setString( count++, "%" + custFullNameTextSrc_.toUpperCase()
+ "%" );
}
if ( curAcctNbr_ != null && !"".equals( curAcctNbr_ ) )
{
preparedStatement.setLong( count++, curAcctNbr_.longValue() );
}
if ( custMnmcNameTextSrc_ != null && !"".equals( custMnmcNameTextSrc_ ) )
{
preparedStatement.setString( count++, custMnmcNameTextSrc_.toUpperCase() );
}
if ( portfMgmtProdNameSrc_ != null && !"".equals( portfMgmtProdNameSrc_ ) )
{
preparedStatement.setString( count++, "%" + portfMgmtProdNameSrc_.toUpperCase()
+ "%" );
}
if ( prodCodeSrc_ != null && !"".equals( prodCodeSrc_ ) )
{
preparedStatement.setString( count++, prodCodeSrc_.toUpperCase() );
}
if ( lastUpdUserIdSrc_ != null && !"".equals( lastUpdUserIdSrc_ ) )
{
preparedStatement.setString( count++, lastUpdUserIdSrc_ );
}
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtDAO#listPortfolio(java.math.BigInteger)
*/
public DataSet listPortfolio( BigInteger custNbr_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_CUR_ACCT_NBR + ", " );
query.append( C_ALIAS_POINT_ACCT_INVST + "." + C_INVST_CUR_ACCT_NBR
+ ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PORTF_MGMT_PROD_NAME + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_CUST_MNMC_NAME + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_CODE + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_REC_STAT_CODE );
query.append( " FROM " );
query.append( C_TABLE_PROD_ACCT_PORTF_MGMT + " " + C_ALIAS_PORTF_MGMT
+ ", " );
query.append( C_TABLE_POINT_ACCT_INVST + " " + C_ALIAS_POINT_ACCT_INVST
+ ", " );
query.append( C_TABLE_PRODUCT_ACCOUNT + " " + C_ALIAS_PRODUCT_ACCOUNT
+ ", " );
query.append( C_TABLE_RELATION_PRVT + " " + C_ALIAS_RELATION_PRVT );
String criteria = "";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_ACCT_CODE
+ " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE
+ " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_PROD_UNDER_ACCT_CODE + " AND ";
criteria = criteria + "TRIM(CAST(" + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR + " AS CHAR(11))) = ";
criteria = criteria + "TRIM(" + C_ALIAS_POINT_ACCT_INVST + "."
+ C_CUR_ACCT_NBR + ") AND ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_NBR + " = "
+ C_ALIAS_PRODUCT_ACCOUNT + "." + C_RELTN_NBR + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_REC_STAT_CODE + " != "
+ "'" + BaseTplBkrPortfMgmtEntity.C_REC_STAT_CODE_INACTIVE
+ "'" + " AND (";
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_1_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_2_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_3_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_4_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_5_NBR
+ " = ? )";
}
if ( criteria.length() > 0 )
{
query.append( " WHERE " + criteria );
}
query.append( " ORDER BY " + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
}
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtDAO#listPortfolio(java.math.BigInteger)
*/
public DataSet listPortfolio( BigInteger custNbr_, String loggedUser_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT DISTINCT " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_CUR_ACCT_NBR + ", " );
query.append( C_ALIAS_POINT_ACCT_INVST + "." + C_INVST_CUR_ACCT_NBR
+ ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PORTF_MGMT_PROD_NAME + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_CUST_MNMC_NAME + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_CODE + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_REC_STAT_CODE + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_LAST_UPD_USER_ID );
query.append( " FROM " );
query.append( C_TABLE_PROD_ACCT_PORTF_MGMT + " " + C_ALIAS_PORTF_MGMT
+ ", " );
query.append( C_TABLE_POINT_ACCT_INVST + " " + C_ALIAS_POINT_ACCT_INVST
+ ", " );
query.append( C_TABLE_PRODUCT_ACCOUNT + " " + C_ALIAS_PRODUCT_ACCOUNT
+ ", " );
query.append( C_TABLE_RELATION_PRVT + " " + C_ALIAS_RELATION_PRVT + ", " );
query.append( C_TABLE_BKR_PORTF_MGMT_MOV + " "
+ C_ALIAS_TPL_BKR_PORTF_MGMT_MOV );
String criteria = "";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_ACCT_CODE
+ " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE
+ " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_PROD_UNDER_ACCT_CODE + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + " = ";
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_ACCT_CODE + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE
+ " = ";
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_UNDER_ACCT_CODE + " AND ";
/*criteria = criteria + "TRIM(CAST(" + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR + " AS CHAR(11))) = ";
criteria = criteria + "TRIM(" + C_ALIAS_POINT_ACCT_INVST + "."
+ C_CUR_ACCT_NBR + ") AND ";*/
//Alteraçao G&P INICIO 19/06/2008
criteria = criteria + " " + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR + " = ";
criteria = criteria + " " + C_ALIAS_POINT_ACCT_INVST + "."
+ C_CUR_ACCT_NBR + " AND ";
//Alteraçao G&P FIM
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_NBR + " = "
+ C_ALIAS_PRODUCT_ACCOUNT + "." + C_RELTN_NBR + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_REC_STAT_CODE + " != "
+ "'" + BaseTplBkrPortfMgmtEntity.C_REC_STAT_CODE_INACTIVE
+ "'" + " AND (";
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_1_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_2_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_3_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_4_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_5_NBR
+ " = ? )";
}
if ( criteria.length() > 0 )
{
query.append( " WHERE " + criteria );
}
query.append( " ORDER BY " + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
}
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtDAO#listForBkrPorftMgmtGrid(java.lang.String)
*/
public ArrayList listForBkrPorftMgmtGrid( BigInteger prodAcctCode_,
BigInteger prodUnderAcctCode_ )
{
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtEntity;
TplBkrPortfMgmtMovEntityVO tplBkrPortfMgmtEntityVO;
DataSetRow row;
ArrayList result = new ArrayList();
DataSet rds = this.list( prodAcctCode_, prodUnderAcctCode_ );
for ( int indexRow = 0; indexRow < rds.size(); indexRow++ )
{
tplBkrPortfMgmtEntity = new TplBkrPortfMgmtMovEntity();
tplBkrPortfMgmtEntityVO = ( TplBkrPortfMgmtMovEntityVO ) tplBkrPortfMgmtEntity.getData();
row = rds.getRow( indexRow );
tplBkrPortfMgmtEntityVO.setBkrCnpjNbr( row.getStringByName( C_BKR_CNPJ_NBR ) );
tplBkrPortfMgmtEntityVO.setBkrNameText( row.getStringByName( C_BKR_NAME_TEXT ) );
tplBkrPortfMgmtEntityVO.setBovespaCurAcctNbr( row.getStringByName( C_BOVESPA_CUR_ACCT_NBR ) );
tplBkrPortfMgmtEntityVO.setBovespaInvstAcctNbr( row.getStringByName( C_BOVESPA_INVST_ACCT_NBR ) );
tplBkrPortfMgmtEntityVO.setBmfCurAcctNbr( row.getStringByName( C_BMF_CUR_ACCT_NBR ) );
tplBkrPortfMgmtEntityVO.setBmfInvstAcctNbr( row.getStringByName( C_BMF_INVST_ACCT_NBR ) );
tplBkrPortfMgmtEntityVO.setProdAcctCode( new BigInteger(
row.getStringByName( C_PROD_ACCT_CODE ) ) );
tplBkrPortfMgmtEntityVO.setProdUnderAcctCode( new BigInteger(
row.getStringByName( C_PROD_UNDER_ACCT_CODE ) ) );
java.util.Date lastUpdDate = null;
try
{
SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
lastUpdDate = df.parse( row.getStringByName( C_LAST_UPD_DATE ) );
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
tplBkrPortfMgmtEntityVO.setLastUpdDate( lastUpdDate );
tplBkrPortfMgmtEntityVO.setLastUpdUserId( row.getStringByName( C_LAST_UPD_USER_ID ) );
tplBkrPortfMgmtEntityVO.setOpernCode( row.getStringByName( C_OPERN_TEXT ) );
result.add( tplBkrPortfMgmtEntity );
}
return result;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtDAO#list(java.math.BigInteger,
* java.math.BigInteger)
*/
public DataSet list( BigInteger prodAcctCode_, BigInteger prodUnderAcctCode_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT " );
query.append( C_ALIAS_BROKER + "." + C_BKR_CNPJ_NBR + ", " );
query.append( C_ALIAS_BROKER + "." + C_BKR_NAME_TEXT + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_BOVESPA_CUR_ACCT_NBR + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_BOVESPA_INVST_ACCT_NBR + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_BMF_CUR_ACCT_NBR
+ ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_BMF_INVST_ACCT_NBR
+ ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_PROD_ACCT_CODE
+ ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_UNDER_ACCT_CODE + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_LAST_UPD_DATE
+ ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_LAST_UPD_USER_ID
+ ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_OPERN_CODE );
query.append( " FROM " );
query.append( C_TABLE_BROKER + " " + C_ALIAS_BROKER + ", " );
query.append( C_TABLE_BKR_PORTF_MGMT_MOV + " "
+ C_ALIAS_TPL_BKR_PORTF_MGMT_MOV );
query.append( " WHERE " );
String criteria = "";
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_BKR_CNPJ_NBR + " = " + C_ALIAS_BROKER + "."
+ C_BKR_CNPJ_NBR + " AND ";
if ( prodAcctCode_ != null && prodAcctCode_.longValue() != 0 )
{
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_ACCT_CODE + " = ? AND ";
}
if ( prodUnderAcctCode_ != null && prodUnderAcctCode_.longValue() != 0 )
{
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_UNDER_ACCT_CODE + " = ? AND ";
}
if ( criteria.length() > 0 )
{
criteria = criteria.substring( 0, criteria.length() - 5 );
criteria = criteria + " ORDER BY " + C_ALIAS_BROKER + "."
+ C_BKR_NAME_TEXT;
query.append( criteria );
}
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( prodAcctCode_ != null && prodAcctCode_.longValue() != 0 )
{
preparedStatement.setLong( count++, prodAcctCode_.longValue() );
}
if ( prodUnderAcctCode_ != null && prodUnderAcctCode_.longValue() != 0 )
{
preparedStatement.setLong( count++, prodUnderAcctCode_.longValue() );
}
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
String[] codeColumn = { C_OPERN_CODE };
String[] nameColumn = { C_OPERN_TEXT };
rsds.outerJoin( ODSConstraintDecoder.decodeOpern(), codeColumn, codeColumn,
nameColumn );
return rsds;
}
/*
* (non-Javadoc)
* @see com.citibank.ods.persistence.pl.dao.TplBkrPortfMgmtDAO#listPortfolio(java.math.BigInteger)
*/
public DataSet listAuthorizedPortfolio( BigInteger custNbr_,
String loggedUser_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
ResultSet resultSet = null;
ResultSetDataSet rsds = null;
StringBuffer query = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
query.append( "SELECT DISTINCT " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_CUR_ACCT_NBR + ", " );
query.append( C_ALIAS_POINT_ACCT_INVST + "." + C_INVST_CUR_ACCT_NBR
+ ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_PORTF_MGMT_PROD_NAME + ", " );
query.append( C_ALIAS_PORTF_MGMT + "." + C_CUST_MNMC_NAME + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_CODE + ", " );
query.append( C_ALIAS_PRODUCT_ACCOUNT + "." + C_REC_STAT_CODE + ", " );
query.append( C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "." + C_LAST_UPD_USER_ID );
query.append( " FROM " );
query.append( C_TABLE_PROD_ACCT_PORTF_MGMT + " " + C_ALIAS_PORTF_MGMT
+ ", " );
query.append( C_TABLE_POINT_ACCT_INVST + " " + C_ALIAS_POINT_ACCT_INVST
+ ", " );
query.append( C_TABLE_PRODUCT_ACCOUNT + " " + C_ALIAS_PRODUCT_ACCOUNT
+ ", " );
query.append( C_TABLE_RELATION_PRVT + " " + C_ALIAS_RELATION_PRVT + ", " );
query.append( C_TABLE_BKR_PORTF_MGMT_MOV + " "
+ C_ALIAS_TPL_BKR_PORTF_MGMT_MOV );
String criteria = "";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "." + C_PROD_ACCT_CODE
+ " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE
+ " = ";
criteria = criteria + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_PROD_UNDER_ACCT_CODE + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_ACCT_CODE + " = ";
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_ACCT_CODE + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_PROD_UNDER_ACCT_CODE
+ " = ";
criteria = criteria + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_PROD_UNDER_ACCT_CODE + " AND ";
criteria = criteria + "TRIM(CAST(" + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR + " AS CHAR(11))) = ";
criteria = criteria + "TRIM(" + C_ALIAS_POINT_ACCT_INVST + "."
+ C_CUR_ACCT_NBR + ") AND ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_NBR + " = "
+ C_ALIAS_PRODUCT_ACCOUNT + "." + C_RELTN_NBR + " AND ";
criteria = criteria + C_ALIAS_PORTF_MGMT + "." + C_REC_STAT_CODE + " != "
+ "'" + BaseTplBkrPortfMgmtEntity.C_REC_STAT_CODE_INACTIVE
+ "'" + " AND (";
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_1_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_2_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_3_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_4_NBR
+ " = ? OR ";
criteria = criteria + C_ALIAS_RELATION_PRVT + "." + C_RELTN_CUST_5_NBR
+ " = ? )";
}
if ( loggedUser_ != null && !"".equals( loggedUser_ ) )
{
criteria = criteria + " AND " + C_ALIAS_TPL_BKR_PORTF_MGMT_MOV + "."
+ C_LAST_UPD_USER_ID + " = ? ";
}
if ( criteria.length() > 0 )
{
query.append( " WHERE " + criteria );
}
query.append( " ORDER BY " + C_ALIAS_PRODUCT_ACCOUNT + "."
+ C_CUR_ACCT_NBR );
preparedStatement = new CitiStatement(connection.prepareStatement( query.toString() ));
int count = 1;
if ( custNbr_ != null && !"".equals( custNbr_ ) )
{
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
preparedStatement.setLong( count++, custNbr_.longValue() );
}
if ( loggedUser_ != null && !"".equals( loggedUser_ ) )
{
preparedStatement.setString( count++, loggedUser_ );
}
preparedStatement.replaceParametersInQuery(query.toString());
resultSet = preparedStatement.executeQuery();
rsds = new ResultSetDataSet( resultSet );
resultSet.close();
}
catch ( SQLException e )
{
throw new UnexpectedException( e.getErrorCode(),
C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
return rsds;
}
/**
* Remove uma linha na tabela TPL_BROKERMov de acordo com ID passado como
* parâmetro.
* @param entityKey_
* @throws UnexpectedException
* @author Hamilton Matos
*/
public TplBkrPortfMgmtMovEntity deleteFromMovement(
TplBkrPortfMgmtMovEntity tplBkrPortfMgmtMovEntity_ )
throws UnexpectedException
{
ManagedRdbConnection connection = null;
CitiStatement preparedStatement = null;
StringBuffer sqlQuery = new StringBuffer();
try
{
connection = OracleODSDAOFactory.getConnection();
sqlQuery.append( "DELETE FROM " );
sqlQuery.append( C_TABLE_NAME );
sqlQuery.append( " WHERE " );
sqlQuery.append( C_PROD_ACCT_CODE + " = ? AND " );
sqlQuery.append( C_PROD_UNDER_ACCT_CODE + " = ? AND " );
sqlQuery.append( C_BKR_CNPJ_NBR + " = ? " );
preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() ));
preparedStatement.setLong(
1,
tplBkrPortfMgmtMovEntity_.getData().getProdAcctCode().longValue() );
preparedStatement.setLong(
2,
tplBkrPortfMgmtMovEntity_.getData().getProdUnderAcctCode().longValue() );
preparedStatement.setString( 3,
tplBkrPortfMgmtMovEntity_.getData().getBkrCnpjNbr() );
preparedStatement.replaceParametersInQuery(sqlQuery.toString());
preparedStatement.executeUpdate();
return tplBkrPortfMgmtMovEntity_;
}
catch ( Exception e )
{
throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, e );
}
finally
{
closeStatement( preparedStatement );
closeConnection( connection );
}
}
} |
package com.dokyme.alg4.sorting.basic;
import com.dokyme.alg4.sorting.Sorting;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.Stopwatch;
import java.lang.reflect.Method;
import java.util.Arrays;
import static com.dokyme.alg4.sorting.basic.Example.*;
/**
* Created by intellij IDEA.But customed by hand of Dokyme.
*
* @author dokym
* @date 2018/3/10-14:12
* Description:
*/
public class SortCompare {
public static final String INSERTION = "insertion";
public static final String SELECTION = "selection";
public static final String SHELL = "shell";
public static final String INSERTION_WITHOUT_EXCH = "insertion without exchange";
public static final String INSERTION_INT = "insertion int";
public static double time(String alg, Double[] a) {
Stopwatch timer = new Stopwatch();
if (INSERTION.equals(alg.toLowerCase())) {
new Insertion().sort(a);
} else if (SELECTION.equals(alg.toLowerCase())) {
new Selection().sort(a);
} else if (SHELL.equals(alg.toLowerCase())) {
new Shell().sort(a);
} else if (INSERTION_WITHOUT_EXCH.equals(alg.toLowerCase())) {
Insertion.sortWithoutExch(a);
} else if (INSERTION_INT.equals(alg.toLowerCase())) {
}
return timer.elapsedTime();
}
public static double timeRandomInput(String alg, int length, int times) {
double total = 0.0;
Double[] a = new Double[length];
for (int t = 0; t < times; t++) {
for (int i = 0; i < length; i++) {
a[i] = StdRandom.uniform();
}
total += time(alg, a);
}
return total;
}
public static void testTwoDistinctPrimaryKey(int length, int times) {
int[] array = new int[length];
double t1 = 0.0, t2 = 0.0;
for (int j = 0; j < times; j++) {
for (int i = 0; i < length; i++) {
array[i] = StdRandom.uniform(2);
}
Stopwatch stopwatch = new Stopwatch();
Insertion.sort(array);
t1 += stopwatch.elapsedTime();
for (int i = 0; i < length; i++) {
array[i] = StdRandom.uniform(2);
}
Stopwatch stopwatch2 = new Stopwatch();
Insertion.sort(array);
t2 += stopwatch2.elapsedTime();
}
StdOut.printf("Insertion:%.1f\tSelection:%.1f\n", t1, t2);
}
public static void testIntWithIntegerAutoBoxing(int length, int times) {
Integer[] array = new Integer[length];
double total1 = 0.0;
for (int t = 0; t < times; t++) {
for (int i = 0; i < length; i++) {
array[i] = StdRandom.uniform(length);
}
Stopwatch stopwatch = new Stopwatch();
new Insertion().sort(array);
total1 += stopwatch.elapsedTime();
}
double total2 = 0.0;
for (int t = 0; t < times; t++) {
for (int i = 0; i < length; i++) {
array[i] = StdRandom.uniform(length);
}
Stopwatch stopwatch = new Stopwatch();
new Insertion().sortWithAutoBoxing(array);
total2 += stopwatch.elapsedTime();
}
StdOut.printf("For %d random Integers\n %s is", length, INSERTION);
StdOut.printf(" %.1f times faster than %s\n", total2 / total1, INSERTION_INT);
}
public static void testThreeAlgsWithPowerOf2() {
int length = 1 << 6;
int times = 256;
//数组长度从2^6增到2^16
for (int i = 0; i < 10; i++) {
double t1 = timeRandomInput(SELECTION, length, times);
double t2 = timeRandomInput(INSERTION, length, times);
double t3 = timeRandomInput(SHELL, length, times);
StdOut.printf("Selection:%.1f\tInsertion:%.1f\tShell:%.1f", t1, t2, t3);
System.out.println();
length <<= 1;
}
}
public static double testArraysSort(int length, int times) {
Double[] array = new Double[length];
double total = 0.0;
for (int j = 0; j < times; j++) {
for (int i = 0; i < array.length; i++) {
array[i] = StdRandom.uniform();
}
Stopwatch w = new Stopwatch();
Arrays.sort(array);
total += w.elapsedTime();
}
return total;
}
public static double testSort(Sorting sorting, int length, int times) {
double total = 0;
try {
for (int t = 0; t < times; t++) {
Double[] array = (Double[]) generateTestData(new Double(1.0), length);
Stopwatch stopwatch = new Stopwatch();
sorting.sort(array);
total += stopwatch.elapsedTime();
}
} catch (Exception e) {
e.printStackTrace();
return -1.0;
}
return total;
}
public static void main(String[] args) {
// int N = 10000;
// int T = 200;
// String alg1 = SHELL;
// String alg2 = INSERTION_WITHOUT_EXCH;
// double t1 = timeRandomInput(alg1, N, T);
// double t2 = timeRandomInput(alg2, N, T);
// StdOut.printf("For %d random Doubles\n %s is", N, alg1);
// StdOut.printf(" %.1f times faster than %s\n", t2 / t1, alg2);
// testIntWithIntegerAutoBoxing(1000, 100);
// testThreeAlgsWithPowerOf2();
testTwoDistinctPrimaryKey(10000, 1000);
}
}
|
package cn.seu.edu.hanbab.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Created with IntelliJ IDEA.
*
* @Author: Hanbab
* @Date: 2021/05/20/11:24
*/
@Configuration
public class redisConfig {
@Autowired
private RedisConnectionFactory redisConnectionFactory;
@Bean
public StringRedisSerializer stringRedisSerializer() {
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
return stringRedisSerializer;
}
@Bean
public Jackson2JsonRedisSerializer jackson2JsonRedisSerializer() {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer
= new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL,
JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
return jackson2JsonRedisSerializer;
}
/*@Bean
public StringRedisTemplate stringRedisTemplate(){
StringRedisTemplate stringRedisTemplate =
new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(redisConnectionFactory);
// 开启事务支持
stringRedisTemplate.setEnableTransactionSupport(true);
return stringRedisTemplate;
}*/
@Bean
public RedisTemplate redisTemplate(){
RedisTemplate<String,Object> redisTemplate
= new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(stringRedisSerializer());
/*redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());*/
redisTemplate.setValueSerializer(stringRedisSerializer());
redisTemplate.setHashKeySerializer(stringRedisSerializer());
/*redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());*/
redisTemplate.setHashValueSerializer(stringRedisSerializer());
// 开启事务支持
redisTemplate.setEnableTransactionSupport(true);
return redisTemplate;
}
}
|
package com.bank.cards;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@RefreshScope
@ComponentScan({"com.bank.cards.controller", "com.bank.cards.config"})
@EnableJpaRepositories("com.bank.cards.repository")
@EntityScan({"com.bank.cards.model", "com.bank.config.model"})
@SpringBootApplication
public class CardsApplication {
public static void main(String[] args) {
SpringApplication.run(CardsApplication.class, args);
}
}
|
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
/**
* This class manages the JFrame User Interface.
* It includes formatting of the JFrame and action listeners.
* @author Trever
* @version 2.0
*/
public class DisplayManager extends JFrame{
/** Auto Generated serial Version ID. */
private static final long serialVersionUID = -3238106715883671250L;
/** Constructor that sets up the JFrame and opens the Main Menu content */
public DisplayManager() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setTitle("Authorship Analysis");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(dim.width / 2, dim.height / 2);
this.setLocation((dim.width / 2) - (this.getSize().width / 2), (dim.height / 2) - (this.getSize().height/2));
this.setVisible(true);
mainMenu();
}
/** Main method that acts as the command line driver. */
public static void main(String[] args) {
DisplayManager window = new DisplayManager();
}
/**
* The Main Menu of the program user interface.
*/
private void mainMenu() {
Font buttonFont = new Font("Font", Font.PLAIN, 32);
// Components
JButton storeButton = new JButton("Store Data");
JButton findButton = new JButton("Find Author");
JButton removeButton = new JButton("Remove Data");
JButton helpButton = new JButton("Help");
storeButton.setFont(buttonFont);
findButton.setFont(buttonFont);
removeButton.setFont(buttonFont);
helpButton.setFont(buttonFont);
final JPanel mainMenu = new JPanel();
mainMenu.setLayout(new GridLayout(4, 1));
mainMenu.add(storeButton);
mainMenu.add(findButton);
mainMenu.add(removeButton);
mainMenu.add(helpButton);
setContentPane(mainMenu);
revalidate();
// Action Listeners
storeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
storeDataMenu();
}
});
findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
findAuthorMenu();
}
});
removeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
removeDataMenu();
}
});
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
helpMenu();
}
});
}
/**
* The Store Menu of the program user interface.
* Handles storing data on authors using text
* files of the authors works.
*/
private void storeDataMenu() {
Font buttonFont = new Font("Font", Font.PLAIN, 32);
Font textFont = new Font("Font2", Font.PLAIN, 22);
// Components
JLabel authorName = new JLabel("Author Name:");
JLabel pathLabel1 = new JLabel("File Path:");
JLabel pathLabel2 = new JLabel("File Path:");
JLabel pathLabel3 = new JLabel("File Path:");
final JTextField authorText = new JTextField("");
final JTextField pathText1 = new JTextField("");
final JTextField pathText2 = new JTextField("");
final JTextField pathText3 = new JTextField("");
JButton backButton = new JButton("Back");
JButton analyzeButton = new JButton("Analyze and Store");
final JTextArea consoleText = new JTextArea("");
authorName.setFont(textFont);
pathLabel1.setFont(textFont);
pathLabel2.setFont(textFont);
pathLabel3.setFont(textFont);
authorText.setFont(textFont);
pathText1.setFont(textFont);
pathText2.setFont(textFont);
pathText3.setFont(textFont);
backButton.setFont(buttonFont);
analyzeButton.setFont(buttonFont);
consoleText.setFont(new Font("console", Font.PLAIN, 14));
consoleText.setEditable(false);
final JPanel authorInput = new JPanel();
authorInput.setLayout(new BoxLayout(authorInput, BoxLayout.X_AXIS));
authorInput.add(authorName);
authorInput.add(Box.createRigidArea(new Dimension(10, 0)));
authorInput.add(authorText);
final JPanel pathInput = new JPanel();
pathInput.setLayout(new BoxLayout(pathInput, BoxLayout.X_AXIS));
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathLabel1);
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathText1);
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathLabel2);
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathText2);
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathLabel3);
pathInput.add(Box.createRigidArea(new Dimension(10, 0)));
pathInput.add(pathText3);
final JPanel buttonRow = new JPanel();
buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
buttonRow.add(backButton);
buttonRow.add(Box.createRigidArea(new Dimension(10, 0)));
buttonRow.add(analyzeButton);
final JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 1));
top.add(authorInput);
top.add(pathInput);
final JPanel console = new JPanel();
console.setLayout(new BoxLayout(console, BoxLayout.X_AXIS));
consoleText.setSize(this.getWidth() - 20, this.getHeight()
- (top.getHeight() + buttonRow.getHeight() + 20));
consoleText.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createLineBorder(Color.BLACK)));
console.add(Box.createRigidArea(new Dimension(10, 0)));
console.add(consoleText);
console.add(Box.createRigidArea(new Dimension(10, 0)));
final JPanel storeDataMenu = new JPanel();
storeDataMenu.setLayout(new BoxLayout(storeDataMenu, BoxLayout.Y_AXIS));
storeDataMenu.add(top);
storeDataMenu.add(Box.createRigidArea(new Dimension(0, 10)));
storeDataMenu.add(console);
storeDataMenu.add(Box.createRigidArea(new Dimension(0, 10)));
storeDataMenu.add(buttonRow);
setContentPane(storeDataMenu);
revalidate();
// Action Listeners
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu();
}
});
analyzeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!authorText.getText().equals("")) {
List<String> files = new ArrayList<String>();
if (!pathText1.getText().equals("")) {
files.add(pathText1.getText());
}
if (!pathText2.getText().equals("")) {
files.add(pathText2.getText());
}
if (!pathText3.getText().equals("")) {
files.add(pathText3.getText());
}
if (files.size() != 0) {
String[] fileArray = new String[files.size()];
fileArray = files.toArray(fileArray);
try {
AuthorshipAnalysis aa = new AuthorshipAnalysis(authorText.getText(), fileArray);
} catch (IOException e1) {
e1.printStackTrace();
}
consoleText.setText(AuthorshipAnalysis.outputText);
} else {
JOptionPane.showMessageDialog(null, "ERROR: File path fields can not all be empty!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "ERROR: Author field can not be empty!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
});
}
/**
* The Find Menu of the program user interface.
* Used to analyze an unknown text file and
* give proposed authors for each metric.
*/
private void findAuthorMenu() {
Font font = new Font("Font", Font.PLAIN, 32);
// Components
JLabel fileToFind = new JLabel("File to Analyze:");
final JTextField pathText = new JTextField("");
JButton backButton = new JButton("Back");
JButton analyzeButton = new JButton("Analyze and Find");
final JTextArea consoleText = new JTextArea("");
fileToFind.setFont(font);
pathText.setFont(font);
analyzeButton.setFont(font);
backButton.setFont(font);
consoleText.setFont(new Font("console", Font.PLAIN, 14));
consoleText.setEditable(false);
final JPanel top = new JPanel();
top.setLayout(new GridLayout(2, 1));
top.add(fileToFind);
top.add(pathText);
final JPanel buttonRow = new JPanel();
buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
buttonRow.add(backButton);
buttonRow.add(Box.createRigidArea(new Dimension(10, 0)));
buttonRow.add(analyzeButton);
final JPanel console = new JPanel();
console.setLayout(new BoxLayout(console, BoxLayout.X_AXIS));
consoleText.setSize(this.getWidth() - 20, this.getHeight() - (top.getHeight() + buttonRow.getHeight() + 20));
consoleText.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createLineBorder(Color.BLACK)));
consoleText.setEditable(false);
console.add(Box.createRigidArea(new Dimension(10, 0)));
console.add(consoleText);
console.add(Box.createRigidArea(new Dimension(10, 0)));
final JPanel findAuthorMenu = new JPanel();
findAuthorMenu.setLayout(new BoxLayout(findAuthorMenu, BoxLayout.Y_AXIS));
findAuthorMenu.add(top);
findAuthorMenu.add(Box.createRigidArea(new Dimension(0, 10)));
findAuthorMenu.add(console);
findAuthorMenu.add(Box.createRigidArea(new Dimension(0, 10)));
findAuthorMenu.add(buttonRow);
setContentPane(findAuthorMenu);
revalidate();
// Action Listeners
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu();
}
});
analyzeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!pathText.getText().equals("")) {
try {
AuthorshipAnalysis aa = new AuthorshipAnalysis(1, pathText.getText());
} catch (IOException e1) {
e1.printStackTrace();
}
consoleText.setText(AuthorshipAnalysis.outputText);
} else {
JOptionPane.showMessageDialog(null, "ERROR: The text field can not be empty!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
});
}
/**
* The Remove Menu of the program user interface.
* Handles removing a single author or removing
* all stored data.
*/
private void removeDataMenu() {
Font font = new Font("Font", Font.PLAIN, 32);
// Components
JLabel authorName = new JLabel("Author Name:");
final JTextField authorText = new JTextField("");
JButton removeAuthor = new JButton("Remove Author");
JButton removeAll = new JButton("Clear All Data");
JButton backButton = new JButton("Back");
authorName.setFont(font);
authorText.setFont(font);
removeAuthor.setFont(font);
removeAll.setFont(font);
backButton.setFont(font);
final JPanel buttonRow = new JPanel();
buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
buttonRow.add(backButton);
final JPanel removeInput = new JPanel();
removeInput.setLayout(new BoxLayout(removeInput, BoxLayout.X_AXIS));
removeInput.add(Box.createRigidArea(new Dimension(10, 0)));
removeInput.add(authorName);
removeInput.add(Box.createRigidArea(new Dimension(10, 0)));
removeInput.add(authorText);
removeInput.add(Box.createRigidArea(new Dimension(10, 0)));
removeInput.add(removeAuthor);
removeInput.add(Box.createRigidArea(new Dimension(10, 0)));
final JPanel formatInput = new JPanel();
formatInput.setLayout(new GridLayout(5, 1));
formatInput.add(removeInput);
formatInput.add(Box.createRigidArea(new Dimension(0, 0)));
formatInput.add(removeAll);
final JPanel removeMenu = new JPanel();
removeMenu.setLayout(new BoxLayout(removeMenu, BoxLayout.Y_AXIS));
removeMenu.add(formatInput);
removeMenu.add(buttonRow);
setContentPane(removeMenu);
revalidate();
// Action Listeners
removeAuthor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!authorText.getText().equals("")) {
try {
AuthorshipAnalysis aa = new AuthorshipAnalysis(0, authorText.getText());
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "ERROR: Author text field is empty!", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
});
removeAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
File clearFile = new File(AuthorshipAnalysis.SERIAL_FILENAME);
if(clearFile.exists()) {
int result = JOptionPane.showConfirmDialog(null, "Are you sure you want to clear all memory?", "Message", JOptionPane.YES_NO_OPTION);
if (result == JOptionPane.YES_OPTION) {
clearFile.delete();
JOptionPane.showMessageDialog(null, "Memory Cleared. Success!", "Message", JOptionPane.PLAIN_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "There is no memory to clear!", "Message", JOptionPane.PLAIN_MESSAGE);
}
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu();
}
});
}
/**
* The Help Menu of the program user interface.
* Gives instructions on how to use the program.
*/
private void helpMenu() {
Font font = new Font("Font", Font.PLAIN, 32);
// Components
JTextArea consoleText = new JTextArea(
"This menu gives a brief explanation of how to use this program by section."
+ "\n\nSTORE DATA"
+ "\nThe authors name to be stored is entered in the 'Author Name' text field."
+ "\nFile paths to text files of that authors works are placed in the 'file path'"
+ "\nsections. Up to three can be analyzed at a time, but only one has to be entered"
+ "\nto analyze and store an author. Results of the analyzed data will be displayed "
+ "\nin the text area. After the author is stored, more data can be added by storing "
+ "\nadditional text files under that same authors name."
+ "\n\nFIND AUTHOR"
+ "\nPut the file path to a text file of an unknown authors works in the input section."
+ "\nThe analysis of that text file will appear in the text area which gives matching "
+ "\nauthors for each metric the program implements."
+ "\n\nREMOVE DATA"
+ "\nA single author can be removed by typing in that authors name and hitting the 'remove author'"
+ "\nbutton. All serialized data can be deleted by clicking the 'Clear All Data' button."
);
JButton backButton = new JButton("Back to the Main Menu");
backButton.setFont(font);
backButton.setAlignmentX(CENTER_ALIGNMENT);
final JPanel console = new JPanel();
console.setLayout(new BoxLayout(console, BoxLayout.X_AXIS));
consoleText.setSize(this.getWidth(), this.getHeight() - (backButton.getHeight() + 20));
consoleText.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK), BorderFactory.createLineBorder(Color.BLACK)));
consoleText.setFont(new Font("console", Font.PLAIN, 14));
consoleText.setEditable(false);
console.add(Box.createRigidArea(new Dimension(10, 0)));
console.add(consoleText);
console.add(Box.createRigidArea(new Dimension(10, 0)));
final JPanel helpMenu = new JPanel();
helpMenu.setLayout(new BoxLayout(helpMenu, BoxLayout.Y_AXIS));
helpMenu.add(Box.createRigidArea(new Dimension(0, 10)));
helpMenu.add(console);
helpMenu.add(Box.createRigidArea(new Dimension(0, 10)));
helpMenu.add(backButton);
setContentPane(helpMenu);
revalidate();
// Action Listeners
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainMenu();
}
});
}
}
|
/*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.testfixture.beans;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* Bean exposing a map. Used for bean factory tests.
*
* @author Rod Johnson
* @since 05.06.2003
*/
public class HasMap {
private Map<?, ?> map;
private Set<?> set;
private Properties props;
private Object[] objectArray;
private Integer[] intArray;
private Class<?>[] classArray;
private List<Class<?>> classList;
private IdentityHashMap<?, ?> identityMap;
private CopyOnWriteArraySet<?> concurrentSet;
private HasMap() {
}
public Map<?, ?> getMap() {
return map;
}
public void setMap(Map<?, ?> map) {
this.map = map;
}
public Set<?> getSet() {
return set;
}
public void setSet(Set<?> set) {
this.set = set;
}
public Properties getProps() {
return props;
}
public void setProps(Properties props) {
this.props = props;
}
public Object[] getObjectArray() {
return objectArray;
}
public void setObjectArray(Object[] objectArray) {
this.objectArray = objectArray;
}
public Integer[] getIntegerArray() {
return intArray;
}
public void setIntegerArray(Integer[] is) {
intArray = is;
}
public Class<?>[] getClassArray() {
return classArray;
}
public void setClassArray(Class<?>[] classArray) {
this.classArray = classArray;
}
public List<Class<?>> getClassList() {
return classList;
}
public void setClassList(List<Class<?>> classList) {
this.classList = classList;
}
public IdentityHashMap<?, ?> getIdentityMap() {
return identityMap;
}
public void setIdentityMap(IdentityHashMap<?, ?> identityMap) {
this.identityMap = identityMap;
}
public CopyOnWriteArraySet<?> getConcurrentSet() {
return concurrentSet;
}
public void setConcurrentSet(CopyOnWriteArraySet<?> concurrentSet) {
this.concurrentSet = concurrentSet;
}
}
|
import java.util.Scanner;
public class TerminalImpl implements Terminal {
private final TerminalServer server;
private final Account account;
public TerminalImpl() {
server = new TerminalServer();
account = new Account();
}
@Override
public int amountMoney() {
return 0;
}
@Override
public boolean putMoney(int amount) throws IllegalArgumentException {
return false;
}
@Override
public boolean pullMoney(int amount) {
return false;
}
public void getMenu(int pin) {
try {
if (! account.isValid(pin)) {
return;
}
} catch (AccountIsLockedException ex) {
System.out.println(ex.getMessage());
return;
}
System.out.println("1. state account");
System.out.println("2. put cash");
System.out.println("3. pull cash");
System.out.print("Enter number menu: ");
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
try {
switch (num) {
case 1: printStateAccount(); break;
case 2: menuPutMoney(scanner); break;
case 3: menuPopMoney(scanner); break;
default:;
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
private void printStateAccount() {
System.out.println("Cash: " + server.getCash());
}
private int menuActionMoney(Scanner scanner) throws IllegalArgumentException {
System.out.print("Enter amount : ");
int num = scanner.nextInt();
if (num <= 0) {
throw new IllegalArgumentException("Количество добжно быть положительным числом!");
}
if (num % 100 != 0) {
throw new IllegalArgumentException("Количество добжно быть кратно 100!");
}
return num;
}
private void menuPutMoney(Scanner scanner) throws IllegalArgumentException {
int count = menuActionMoney(scanner);
server.pullCash(count);
}
private void menuPopMoney(Scanner scanner) throws IllegalArgumentException {
int count = menuActionMoney(scanner);
server.popCash(count);
}
}
|
package cn.com.onlinetool.fastpay.pay.wxpay.config;
import cn.com.onlinetool.fastpay.constants.EncryptionTypeConstants;
import cn.com.onlinetool.fastpay.pay.wxpay.domain.WXPayDomain;
import cn.com.onlinetool.fastpay.pay.wxpay.domain.WXPayDomainSimpleImpl;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.InputStream;
/**
* 微信支付配置
*/
@NoArgsConstructor
@AllArgsConstructor
@Data
public class WXPayConfig {
/**
* 小程序ID 必填
* 微信分配的小程序ID
*/
private String appid;
/**
* 商户号 必填
* 微信支付分配的商户号
*/
private String mchId;
/**
* 支付方式 必填
* JSAPI--JSAPI支付(或小程序支付)、
* NATIVE--Native支付、
* APP--app支付,
* MWEB--H5支付,
* 不同trade_type决定了调起支付的方式,请根据支付产品正确上传
*/
private String tradeType;
/**
* API 密钥
*/
private String key;
/**
* 加密方式 默认 MD5
*/
private String signType = EncryptionTypeConstants.MD5;
/**
* 商户证书
*/
private InputStream cert;
/**
* 获取WXPayDomain, 用于多域名容灾自动切换
*/
private WXPayDomain wxPayDomain = WXPayDomainSimpleImpl.instance();
/**
* HTTP(S) 连接超时时间,单位毫秒
*/
private int httpConnectTimeoutMs = 6*1000;
/**
* HTTP(S) 读数据超时时间,单位毫秒
*/
private int httpReadTimeoutMs = 8*1000;
/**
* 重试次数
*/
private int retryNum = 0;
/**
* 是否自动上报。
*/
private boolean autoReport = false;
/**
* 使用沙箱
*/
private boolean useSandbox = false;
/**
* 进行健康上报的线程的数量
*/
private int reportWorkerNum = 6;
/**
* 健康上报缓存消息的最大数量。会有线程去独立上报
* 粗略计算:加入一条消息200B,10000消息占用空间 2000 KB,约为2MB,可以接受
*/
private int reportQueueMaxSize = 10000;
/**
* 批量上报,一次最多上报多个数据
*/
private int reportBatchSize = 10;
}
|
package com.jvschool.dao.impl;
import com.jvschool.dao.api.CategoryDAO;
import com.jvschool.model.CategoryEntity;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
@Log4j
@Repository
public class CategoryDAOImpl implements CategoryDAO {
@PersistenceContext
private EntityManager em;
@Override
public List<CategoryEntity> getAllProductCategories() {
return em.createQuery("FROM CategoryEntity where visible=:visible ")
.setParameter("visible", true).getResultList();
}
@Override
public CategoryEntity getProductCategoryById(int id) {
List list = em.createQuery("FROM CategoryEntity " +
"where categoryId=:id").setParameter("id", id).getResultList();
return (list.isEmpty()) ? null : (CategoryEntity) list.get(0);
}
@Override
public CategoryEntity getProductCategoryByName(String name) {
List list = em.createQuery("FROM CategoryEntity " +
"where categoryName=:name").setParameter("name", name).getResultList();
return (list.isEmpty()) ? null : (CategoryEntity) list.get(0);
}
@Override
public void addProductCategory(String name) {
final CategoryEntity categoryEntity = new CategoryEntity();
categoryEntity.setCategoryName(name);
categoryEntity.setVisible(true);
em.persist(categoryEntity);
log.info("Add category: " + categoryEntity.toString());
}
@Override
public void editCategory(CategoryEntity category) {
em.merge(category);
}
@Override
public void removeCategory(CategoryEntity category) {
Query query = em.createQuery("UPDATE CategoryEntity set visible=:visible where categoryId=:categoryId")
.setParameter("categoryId", category.getCategoryId()).setParameter("visible", false);
query.executeUpdate();
log.info("Remove category: " + category.toString());
}
@Override
public List<CategoryEntity> getRemovedCategories() {
return em.createQuery("FROM CategoryEntity where visible=:visible ")
.setParameter("visible", false).getResultList();
}
@Override
public void returnCategory(CategoryEntity category) {
Query query = em.createQuery("UPDATE CategoryEntity set visible=:visible where categoryId=:categoryId")
.setParameter("categoryId", category.getCategoryId()).setParameter("visible", true);
query.executeUpdate();
log.info("Return category: " + category.toString());
}
}
|
package com.example.jse58.androiduiandlogin_jacobesworthy;
import android.support.annotation.Nullable;
import java.io.Serializable;
public class UserProfile implements Serializable {
private String mFirstName;
private String mLastName;
private String mUserName;
private String mBday;
private String mPhoneNum;
private String mEmail;
private String mPswd;
public UserProfile(String firstname, String lastname, String username, String phonenumber, String email, String bday, String pswd ) {
this.mFirstName = firstname;
this.mLastName = lastname;
this.mUserName = username;
this.mPhoneNum = phonenumber;
this.mEmail = email;
this.mPswd = pswd;
this.mBday = bday;
}
public String getName() {
return mFirstName;
}
public void setName(String firstName) {
this.mFirstName = firstName;
}
public String getLastName()
{
return mLastName;
}
public void setLastName(String lastName) {
this.mLastName = lastName;
}
public String getUserName() {
return mUserName;
}
public void setUsername(String username) {
this.mUserName = username;
}
public String getBday() {
return mBday;
}
public void setBday(String bday) {
this.mBday = bday;
}
public String getPhoneNumber() {
return mPhoneNum;
}
public void setPhone(String phonenumber) {
this.mPhoneNum = phonenumber;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
this.mEmail = email;
}
public String getPswd() {
return mPswd;
}
public void setPassword(String pswd) {
this.mPswd = pswd;
}
} |
package com.exam.zzz_other_menu;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.exam.zzz_other_menu_mysql.MySQLiteHandler;
// 어플 메인이 뜨기 전 익스펜더블 리스트뷰에 항목들을 저장하기 위한 액티비티
public class info extends Activity {
MySQLiteHandler handler; // 데이터베이스 사용하기 위한 handler
Cursor c; // 데이터베이스 사용위해 테이블을 찾아줄 커서
ArrayList<Info_save_class> item_list; // Parsing_data.java에서 넘어오는 어레이리스트를 저장할 어레이리스트
int item_breakpoint = 0;
int item_node_length = 0;
String temp = ""; // 7번테이블에 저장시 매장이름이 중복되는 것 방지하기 위해서 사용
// 날짜 저장하기 위한 변수
int year;
int month;
int date;
int hour;
int minute;
int second;
double x[]; // x좌표
double y[]; // y좌표
public void onCreate(Bundle savedInstanceState)
{
Log.d("info.java", "onCreate!!");
super.onCreate(savedInstanceState);
item_list = new ArrayList<Info_save_class>();
// 물품 x좌표
x = new double[]
{258.0, 329.0,
189.0, 132.0, 7.0, 190.0, 66.0, 7.0,
262.0, 335.0, 338.0, 415.0,
7.0, 7.0, 72.0, 62.0};
// 물품 y좌표
y = new double[]
{110.0, 110.0,
110.0, 110.0, 100.0, 43.0, 43.0, 43.0,
515.0, 515.0, 580.0, 515.0,
278.0, 475.0, 375.0, 580.0};
Log.d("info.java", "인텐트가 잘 되나 봅시다");
Intent intent2 = getIntent();
if(intent2!=null) {
Log.d("info.java", "인텐트가 잘 됩니다");
item_list = (ArrayList<Info_save_class>)getIntent().getSerializableExtra("item_list");
item_breakpoint = intent2.getIntExtra("length", 0);
item_node_length = intent2.getIntExtra("item_length", 0);
}
handler = MySQLiteHandler.open(getApplicationContext());
Log.d("info.java", "여기서부터 정보를 저장합니다");
Calendar cal = Calendar.getInstance();
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
date = cal.get(Calendar.DATE);
hour = cal.get(Calendar.HOUR_OF_DAY);
minute = cal.get(Calendar.MINUTE);
second = cal.get(Calendar.SECOND);
/*
Log.d("확인", Integer.toString(year));
Log.d("확인", Integer.toString(month));
Log.d("확인", Integer.toString(date));
Log.d("확인", Integer.toString(hour));
Log.d("확인", Integer.toString(minute));
Log.d("확인", Integer.toString(second));
*/
c = handler.select(9);
c.moveToFirst();
if(c.getCount()==0){
handler.insert_date(year, month, date, hour, minute, second);
Table_3();
Table_5();
Table_6();
Table_7();
Table_8();
} else {
if(c.getInt(1)==year && c.getInt(2)==month && c.getInt(3)==date/* && c.getInt(4)==hour && c.getInt(5)==minute*/){
Log.d("같아서 그냥 넘어갑니다", "1");
} else {
handler.update(year, month, date, hour, minute, second);
handler.delete_info();
Toast.makeText(getApplicationContext(), "오늘 처음 실행하셨으므로 정보를 다시 씁니다", Toast.LENGTH_SHORT).show();
Table_3();
Table_5();
Table_6();
Table_7();
Table_8();
}
}
handler.close();
Log.d("info.java", "다음 액티비티로 넘어가는 인텐트부분입니다");
Intent intent = new Intent(getApplicationContext(), SelectMenu.class); // 데이터베이스에 저장후 Main액티비티로 전환
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP|Intent.FLAG_ACTIVITY_CLEAR_TOP); // 액티비티 재사용하기 위함
startActivity(intent); // 인텐트 시작
finish();
}
public void Table_3(){
c = handler.select(3);
c.moveToFirst();
if(c.getCount()==0) {
String[] Name = new String[]{"과일","농산물","축산물","수산물"};
Log.d("info.java", "물품대그룹을 저장합니다");
for(int i=0; i<Name.length; i++) {
handler.insert("", Name[i], 0, 0, 0, 0, 0, 0, 0, 3);
}
}
}
public void Table_5(){
c = handler.select(5);
c.moveToFirst();
int l = 0;
if(c.getCount()==0){
Log.d("info.java", "물품소그룹을 저장합니다");
for(int k=0; k<item_breakpoint; k++) {
handler.insert(item_list.get(k).getMartName(), item_list.get(k).getName(), item_list.get(k).getPrice(), 1, x[l], y[l], 0, item_list.get(k).getLat(), item_list.get(k).getLon(), 5); // 위의 항목들을 데이터베이스에 저장
if(l==15){
l=0;
} else {
l++;
}
}
}
}
public void Table_6(){
String[] large_mart_name = new String[]{"롯데마트","이마트","홈플러스","하나로마트","신세계백화점","현대백화점","롯데백화점"};
c = handler.select(6);
c.moveToFirst();
if(c.getCount()==0){
Log.d("info.java", "매장대그룹을 저장합니다");
for(int i=0; i<large_mart_name.length; i++) {
handler.insert(large_mart_name[i], "", 0, 0, 0, 0, 0, 0, 0, 6);
}
}
}
public void Table_7(){
c = handler.select(7);
c.moveToFirst();
if(c.getCount()==0){
Log.d("info.java", "매장소그룹을 저장합니다");
for(int i=0; i<item_breakpoint; i++) {
if(temp.equals(item_list.get(i).getMartName())){
Log.d("info.java", "소그룹저장시 중복방지용");
}
else{
handler.insert_bookmarker(item_list.get(i).getMartName(), 0);
temp = item_list.get(i).getMartName();
}
}
}
}
public void Table_8(){
c = handler.select(8);
c.moveToFirst();
if(c.getCount()==0){
handler.insert_length(item_breakpoint, item_node_length);
}
}
} |
package pers.mine.scratchpad.base.concurrent;
/**
* wait,notify和notifyAll要与synchronized一起使用
* Object.wait(),Object.notify(),Object.notifyAll()都是Object的方法,换句话说,就是每个类里面都有这些方法。
* Object.wait():释放当前对象锁,并进入阻塞队列
* Object.notify():唤醒当前对象阻塞队列里的任一线程(并不保证唤醒哪一个)
* Object.notifyAll():唤醒当前对象阻塞队列里的所有线程
* 为什么这三个方法要与synchronized一起使用呢?解释这个问题之前,我们先要了解几个知识点
* 每一个对象都有一个与之对应的监视器
* 每一个监视器里面都有一个该对象的锁和一个等待队列和一个同步队列
* wait()方法的语义有两个,一是释放当前对象锁,另一个是进入阻塞队列,可以看到,这些操作都是与监视器相关的,当然要指定一个监视器才能完成这个操作了
* notify()方法也是一样的,用来唤醒一个线程,你要去唤醒,首先你得知道他在哪儿,所以必须先找到该对象,也就是获取该对象的锁,当获取到该对象的锁之后,才能去该对象的对应的等待队列去唤醒一个线程。值得注意的是,只有当执行唤醒工作的线程离开同步块,即释放锁之后,被唤醒线程才能去竞争锁。
* notifyAll()方法和notify()一样,只不过是唤醒等待队列中的所有线程
* 因wait()而导致阻塞的线程是放在阻塞队列中的,因竞争失败导致的阻塞是放在同步队列中的,notify()/notifyAll()实质上是把阻塞队列中的线程放到同步队列中去
* @author xqwang
* @since 2019年6月25日
*/
public class WaitTest {
public static class WaitRunnable implements Runnable {
Object syncObj = null;
String name = "";
public WaitRunnable(String name,Object syncObj){
this.name = name;
this.syncObj = syncObj;
}
public void run() {
synchronized (syncObj) {//竞争失败导致的阻塞是放在同步队列
try {
System.out.println(name+":我需要等syncObj的一些东西");
syncObj.wait();//释放 syncObj 锁,且线程进入阻塞队列
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println(name);
}
}
}
public static class NotifyRunnable implements Runnable {
Object syncObj = null;
String name = "";
public NotifyRunnable(String name,Object syncObj){
this.name = name;
this.syncObj = syncObj;
}
public void run() {
synchronized (syncObj) {
System.out.println(name+":等我三秒");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
syncObj.notifyAll();//notify()/notifyAll()实质上是把阻塞队列中的线程放到同步队列中去
System.out.println(name+":OK");
}
}
}
public static void main(String[] args) {
Object ob = new Object();
Thread threadA = new Thread(new WaitRunnable("A", ob));
Thread threadB = new Thread(new NotifyRunnable("B", ob));
threadA.start();
threadB.start();
}
}
|
package com.redhat.service.bridge.shard.controllers;
import java.util.Collections;
import java.util.Optional;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.redhat.service.bridge.infra.k8s.Action;
import com.redhat.service.bridge.infra.k8s.K8SBridgeConstants;
import com.redhat.service.bridge.infra.k8s.KubernetesClient;
import com.redhat.service.bridge.infra.k8s.KubernetesResourceType;
import com.redhat.service.bridge.infra.k8s.ResourceEvent;
import com.redhat.service.bridge.infra.k8s.crds.BridgeCustomResource;
import com.redhat.service.bridge.infra.models.dto.BridgeDTO;
import com.redhat.service.bridge.infra.models.dto.BridgeStatus;
import com.redhat.service.bridge.shard.ManagerSyncService;
import io.fabric8.kubernetes.api.model.LoadBalancerIngress;
import io.fabric8.kubernetes.api.model.LoadBalancerStatus;
import io.fabric8.kubernetes.api.model.ObjectMetaBuilder;
import io.fabric8.kubernetes.api.model.apps.Deployment;
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.apps.DeploymentCondition;
import io.fabric8.kubernetes.api.model.networking.v1.HTTPIngressPath;
import io.fabric8.kubernetes.api.model.networking.v1.HTTPIngressPathBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.HTTPIngressRuleValueBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.Ingress;
import io.fabric8.kubernetes.api.model.networking.v1.IngressBackend;
import io.fabric8.kubernetes.api.model.networking.v1.IngressBackendBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.IngressBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.IngressRule;
import io.fabric8.kubernetes.api.model.networking.v1.IngressRuleBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.IngressServiceBackendBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.IngressSpec;
import io.fabric8.kubernetes.api.model.networking.v1.IngressSpecBuilder;
import io.fabric8.kubernetes.api.model.networking.v1.IngressStatus;
import io.fabric8.kubernetes.api.model.networking.v1.ServiceBackendPortBuilder;
@ApplicationScoped
public class IngressController {
private static final Logger LOGGER = LoggerFactory.getLogger(IngressController.class);
@Inject
ManagerSyncService managerSyncService;
@Inject
KubernetesClient kubernetesClient;
void onEvent(@Observes ResourceEvent event) { // equivalent of ResourceEventSource for operator sdk
if (event.getSubject().equals(K8SBridgeConstants.BRIDGE_TYPE)) {
/*
* If the CRD is deleted, remove also all the other related resource.
*
* If another dependent resource is deleted, the `reconcileExecutor` will catch the mismatch between the expected state and the current state.
* It will redeploy the resources so to reach the expected status at the end.
*
* TODO: when we move to k8s and we create the real CRD, set the BridgeCustomResource as owner of the ProcessorCustomResource so that when
* a Bridge is deleted, the deletion is cascaded to all the Processors.
*/
if (event.getAction().equals(Action.DELETED) && event.getResourceType().equals(KubernetesResourceType.CUSTOM_RESOURCE)) {
delete(event.getResourceId());
return;
}
BridgeCustomResource resource = kubernetesClient.getCustomResource(event.getResourceId(), BridgeCustomResource.class);
if (event.getAction().equals(Action.ERROR)) {
LOGGER.error("[shard] Failed to deploy Deployment with id '{}'", resource.getId());
notifyFailedDeployment(resource.getId());
return;
}
reconcileIngress(resource);
}
}
private void delete(String resourceId) {
// Delete Deployment
kubernetesClient.deleteDeployment(resourceId);
// TODO: Delete service
// Delete ingress
kubernetesClient.deleteNetworkIngress(resourceId);
}
private void reconcileIngress(BridgeCustomResource customResource) {
LOGGER.info("[shard] Ingress Bridge reconcyle loop called");
String id = customResource.getId();
// Create Ingress Bridge Deployment if it does not exists
Deployment deployment = kubernetesClient.getDeployment(id);
if (deployment == null) {
LOGGER.info("[shard] There is no deployment for Ingress Bridge '{}'. Creating.", id);
kubernetesClient.createOrUpdateDeployment(createIngressBridgeDeployment(id));
return;
}
Optional<DeploymentCondition> optStatus = deployment.getStatus().getConditions().stream().filter(x -> x.getStatus().equals("Ready")).findFirst();
if (!optStatus.isPresent()) {
LOGGER.info("[shard] Ingress Bridge deployment for Bridge '{}' is not ready yet", id);
return;
}
// TODO: Create service for deployment
// Create Ingress/Route for Bridge if it does not exists
Ingress ingress = kubernetesClient.getNetworkIngress(id);
if (ingress == null) {
LOGGER.info("[shard] There is no Network ingress for ingress Bridge '{}'. Creating.", id);
Ingress ingressResource = buildIngress(id);
kubernetesClient.createNetworkIngress(ingressResource);
return;
}
if (!isNetworkIngressReady(ingress)) {
LOGGER.info("[shard] Network ingress for ingress Bridge '{}' not ready yet", id);
return;
}
String endpoint = extractEndpoint(ingress);
// Update the custom resource if needed
if (!customResource.getStatus().equals(BridgeStatus.AVAILABLE)) {
customResource.setStatus(BridgeStatus.AVAILABLE);
customResource.setEndpoint(endpoint);
kubernetesClient.createOrUpdateCustomResource(customResource.getId(), customResource, K8SBridgeConstants.BRIDGE_TYPE);
BridgeDTO dto = customResource.toDTO();
managerSyncService.notifyBridgeStatusChange(dto).subscribe().with(
success -> LOGGER.info("[shard] Updating Bridge with id '{}' done", dto.getId()),
failure -> LOGGER.warn("[shard] Updating Bridge with id '{}' FAILED", dto.getId()));
}
}
private Deployment createIngressBridgeDeployment(String id) {
return new DeploymentBuilder() // TODO: Add kind, replicas, image etc.. Or even read it from a yaml
.withMetadata(new ObjectMetaBuilder()
.withName(id)
.withLabels(Collections.singletonMap(K8SBridgeConstants.METADATA_TYPE, K8SBridgeConstants.BRIDGE_TYPE))
.build())
.build();
}
private Ingress buildIngress(String id) {
IngressBackend ingressBackend = new IngressBackendBuilder()
.withService(new IngressServiceBackendBuilder()
.withName("ingress-service") // just a placeholder
.withPort(new ServiceBackendPortBuilder().withNumber(80).build())
.build())
.build();
HTTPIngressPath httpIngressPath = new HTTPIngressPathBuilder()
.withBackend(ingressBackend)
.withPath("/ingress/events/" + id)
.withPathType("Prefix")
.build();
IngressRule ingressRule = new IngressRuleBuilder()
.withHttp(new HTTPIngressRuleValueBuilder()
.withPaths(httpIngressPath)
.build())
.build();
IngressSpec ingressSpec = new IngressSpecBuilder()
.withRules(ingressRule)
.build();
return new IngressBuilder()
.withMetadata(
new ObjectMetaBuilder()
.withName(id)
.withLabels(Collections.singletonMap(K8SBridgeConstants.METADATA_TYPE, K8SBridgeConstants.BRIDGE_TYPE))
.build())
.withSpec(ingressSpec)
.build();
}
public boolean isNetworkIngressReady(Ingress ingress) {
return Optional.ofNullable(ingress)
.map(Ingress::getStatus)
.map(IngressStatus::getLoadBalancer)
.map(LoadBalancerStatus::getIngress)
.flatMap(x -> {
if (!x.isEmpty()) {
return Optional.of(x.get(0));
}
return Optional.empty();
})
.map(LoadBalancerIngress::getIp)
.isPresent();
}
private String extractEndpoint(Ingress ingress) {
return ingress.getSpec().getRules().get(0).getHttp().getPaths().get(0).getPath();
}
private void notifyFailedDeployment(String id) {
BridgeCustomResource customResource = kubernetesClient.getCustomResource(id, BridgeCustomResource.class);
customResource.setStatus(BridgeStatus.FAILED);
BridgeDTO dto = customResource.toDTO();
managerSyncService.notifyBridgeStatusChange(dto).subscribe().with(
success -> LOGGER.info("[shard] Updating Bridge with id '{}' done", dto.getId()),
failure -> LOGGER.warn("[shard] Updating Bridge with id '{}' FAILED", dto.getId()));
}
}
|
package com.example.gamedb.workmanager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.example.gamedb.R;
import com.example.gamedb.db.GameDatabase;
import com.example.gamedb.db.entity.Game;
import com.example.gamedb.db.entity.Genre;
import com.example.gamedb.db.entity.Platform;
import com.example.gamedb.db.entity.Screenshot;
import com.example.gamedb.db.entity.Video;
import com.example.gamedb.ui.activity.MainActivity;
import com.example.gamedb.ui.fragment.GameListFragment;
import com.example.gamedb.util.Utilities;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
public class DownloadGamesWorker extends Worker {
private static final String LOG_TAG = DownloadGamesWorker.class.getCanonicalName();
public DownloadGamesWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@NonNull
@Override
public Result doWork() {
try {
String igdbBaseUrl = getInputData().getString(GameListFragment.BASE_URL);
String userKey = getInputData().getString(GameListFragment.USER_KEY);
Uri uri = Uri.parse(igdbBaseUrl).buildUpon()
.appendPath("games")
.build();
// We only want the first 500 games from 2015
String body = "fields cover.*,artworks.*,cover.*,first_release_date,game_modes.*," +
"genres.*,name,platforms.*,screenshots.*,storyline," +
"summary,total_rating,total_rating_count,videos.*;" +
"where platforms.category = 1 & first_release_date > 1420070400;" +
"sort release_dates.date desc;" +
"limit 500;";
JSONArray response = (JSONArray) Utilities.httpRequest("POST", body, uri,
userKey);
saveGames(response);
return Result.success();
} catch (Exception ex) {
return Result.failure();
}
}
private void saveGames(JSONArray jsonArray) {
GameDatabase gameDatabase = GameDatabase.getDatabase(getApplicationContext());
Log.d(LOG_TAG, "================= Starting Download =================");
try {
if (jsonArray != null) {
Date currentDate = new Date();
Date expiryDate = Utilities.calculateExpiryDate(currentDate, 24);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject gameArray = jsonArray.getJSONObject(i);
JSONArray artworksArray = gameArray.has("artworks") ?
gameArray.getJSONArray("artworks") : null;
JSONArray screenshotArray = gameArray.has("screenshots") ?
gameArray.getJSONArray("screenshots") : null;
JSONArray videoArray = gameArray.has("videos") ?
gameArray.getJSONArray("videos") : null;
JSONObject coverImage = gameArray.has("cover") ?
gameArray.getJSONObject("cover") : null;
// Game information
Log.d(LOG_TAG, "================= Saving Game =================");
int id = gameArray.getInt("id");
String backgroundImage;
if (artworksArray != null) {
backgroundImage = artworksArray.getJSONObject(0)
.getString("image_id");
} else if (screenshotArray != null) {
backgroundImage = screenshotArray.getJSONObject(0)
.getString("image_id");
} else if (coverImage != null) {
backgroundImage = coverImage.getString("image_id");
} else {
backgroundImage = null;
}
String posterImage = coverImage != null ? coverImage.getString("image_id")
: null;
String name = gameArray.getString("name");
Long firstReleaseDate = null;
if (gameArray.has("first_release_date")) {
firstReleaseDate = gameArray.getLong("first_release_date");
}
Double totalRating = null;
if (gameArray.has("total_rating")) {
totalRating = gameArray.getDouble("total_rating");
}
String summary = null;
if (gameArray.has("summary")) {
summary = gameArray.getString("summary");
}
String storyline = null;
if (gameArray.has("storyline")) {
storyline = gameArray.getString("storyline");
}
Game game = new Game(id, backgroundImage, posterImage, name, firstReleaseDate,
totalRating, summary, storyline, expiryDate.getTime());
gameDatabase.gameDao().insert(game);
// Genre information
Log.d(LOG_TAG, "================= Saving Genres =================");
if (gameArray.has("genres")) {
for (int j = 0; j < gameArray.getJSONArray("genres").length(); j++) {
JSONObject genreObject = gameArray.getJSONArray("genres")
.getJSONObject(j);
int genreId = genreObject.getInt("id");
String genreName = genreObject.getString("name");
gameDatabase.genreDao().insert(new Genre(genreId, genreName, id,
expiryDate.getTime()));
}
}
// Platform information
Log.d(LOG_TAG, "================= Saving Platforms =================");
if (gameArray.has("platforms")) {
for (int j = 0; j < gameArray.getJSONArray("platforms").length(); j++) {
JSONObject platformObject = gameArray.getJSONArray("platforms")
.getJSONObject(j);
int platformId = platformObject.getInt("id");
String platformName = platformObject.getString("name");
gameDatabase.platformDao().insert(new Platform(platformId, platformName,
id, expiryDate.getTime()));
}
}
// Video information
Log.d(LOG_TAG, "================= Saving Videos =================");
if (videoArray != null) {
for (int j = 0; j < videoArray.length(); j++) {
JSONObject videoObject = videoArray.getJSONObject(j);
int videoId = videoObject.getInt("id");
String videoImage = videoObject.getString("video_id");
gameDatabase.videoDao().insert(new Video(videoId, videoImage, id,
expiryDate.getTime()));
}
}
// Screenshot information
Log.d(LOG_TAG, "================= Saving Screenshots =================");
if (screenshotArray != null) {
for (int j = 0; j < screenshotArray.length(); j++) {
JSONObject screenshotObject = screenshotArray.getJSONObject(j);
int screenshotId = screenshotObject.getInt("id");
String screenshotImage = screenshotObject.getString("image_id");
gameDatabase.screenshotDao().insert(new Screenshot(screenshotId,
screenshotImage, id, expiryDate.getTime()));
}
}
}
sendNotification();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.d(LOG_TAG, "================= Finished Download =================");
}
private void sendNotification() {
String CHANNEL_ID = "Game_DB_NOTIFICATION_CHANNEL_ID";
String title = "Game DB";
String description = "Game DB Database Update";
NotificationManager notificationManager = (NotificationManager) getApplicationContext()
.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(CHANNEL_ID,
title, NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.enableVibration(true);
notificationChannel.setDescription(description);
notificationManager.createNotificationChannel(notificationChannel);
}
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),
0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(),
CHANNEL_ID);
builder.setSmallIcon(R.drawable.ic_baseline_android_24)
.setContentText(description)
.setContentTitle(title)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
notificationManager.notify(1, builder.build());
}
}
|
package student.pl.edu.pb.geodeticapp.geoutils.exceptions;
public class ReferenceSystemConversionException extends Exception {
public ReferenceSystemConversionException(Throwable cause) {
super("Couldn't convert coordinates!", cause);
}
}
|
package servlet;
import dao.StudentDao;
import model.Student;
import util.Dbutil;
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;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/studentQuery")
public class StudentQueryServlet extends HttpServlet {
private Dbutil dbutil = new Dbutil();
private StudentDao studentDao = new StudentDao();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
Connection con;
try {
con = dbutil.getCon();
List<Student> studentList = studentDao.query(con);
session.setAttribute("studentList",studentList);
request.getRequestDispatcher("studentQuery.jsp").forward(request,response);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
|
package com.itcast.property;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestIOC {
@Test
public void testUser() {
// TODO Auto-generated method stub
//1.加载spring配置文件,创建对象
ApplicationContext context = new
ClassPathXmlApplicationContext("bean1.xml");
//2.得到配置创建的对象
PropertyDemo1 demo1 = (PropertyDemo1) context.getBean("demo1");
demo1.test1();
}
}
|
package com.kangyonggan.app.simconf.exception;
/**
* @author kangyonggan
* @since 17/02/16
*/
public class ParseException extends Exception {
/**
* 序列化ID
*/
private static final long serialVersionUID = 1L;
public ParseException() {
super("解析异常");
}
public ParseException(String msg) {
super(msg);
}
public ParseException(String msg, Throwable cause) {
super(msg, cause);
}
public ParseException(Throwable cause) {
super(cause);
}
}
|
package forms;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
public class PlotDialog extends JDialog {
private JPanel contentPane;
private JButton buttonOK;
private JPanel plotPanel;
private ChartPanel chartPanel;
private JFreeChart chart;
public PlotDialog(Vector xValues, Vector yValues, String plotName, String xLabel, String yLabel) {
plot(xValues, yValues, plotName, xLabel, yLabel);
$$$setupUI$$$();
setContentPane(contentPane);
setModal(true);
getRootPane().setDefaultButton(buttonOK);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
onOK();
}
});
}
private void onOK() {
dispose();
}
private void plot(Vector xValues, Vector yValues, String plotName, String xLabel, String yLabel) {
XYSeries series = new XYSeries(plotName);
int n = xValues.size();
for (int i = 0; i < n; i++) {
double x = (double) xValues.get(i);
double y = (double) yValues.get(i);
series.add(x, y);
}
XYDataset dataset = new XYSeriesCollection(series);
chart = ChartFactory.createXYLineChart(plotName, xLabel, yLabel, dataset, PlotOrientation.VERTICAL, false, false, false);
}
private void createUIComponents() {
chartPanel = new ChartPanel(chart);
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
createUIComponents();
contentPane = new JPanel();
contentPane.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(2, 1, new Insets(10, 10, 10, 10), -1, -1));
final JPanel panel1 = new JPanel();
panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 2, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, 1, null, null, null, 0, false));
final com.intellij.uiDesigner.core.Spacer spacer1 = new com.intellij.uiDesigner.core.Spacer();
panel1.add(spacer1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false));
final JPanel panel2 = new JPanel();
panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
panel1.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(0, 1, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
buttonOK = new JButton();
buttonOK.setText("OK");
panel2.add(buttonOK, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_HORIZONTAL, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
plotPanel = new JPanel();
plotPanel.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new Insets(0, 0, 0, 0), -1, -1));
contentPane.add(plotPanel, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
plotPanel.add(chartPanel, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_NONE, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPane;
}
}
|
package cn.cherish.springcloud.security;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException,ServletException {
SecurityUser userDetails = (SecurityUser)authentication.getPrincipal();
log.info("【登陆成功】 用户: {} login: {}", userDetails.getUsername(), request.getContextPath());
log.info("【登陆成功】 IP: {}", getIpAddress(request));
super.onAuthenticationSuccess(request, response, authentication);
}
public String getIpAddress(HttpServletRequest request){
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
}
|
package menjacnica.gui;
import java.awt.EventQueue;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import menjacnica.Menjacnica;
import menjacnica.MenjacnicaInterface;
import menjacnica.Valuta;
public class GUIKontroler {
private static MenjacnicaGUI glavniProzor;
private static MenjacnicaInterface menjacnica;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
menjacnica=new Menjacnica();
glavniProzor=new MenjacnicaGUI();
glavniProzor.setVisible(true);
glavniProzor.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void ugasiAplikaciju() {
int opcija = JOptionPane.showConfirmDialog(glavniProzor.getContentPane(),
"Da li ZAISTA zelite da izadjete iz apliacije", "Izlazak",
JOptionPane.YES_NO_OPTION);
if (opcija == JOptionPane.YES_OPTION)
System.exit(0);
}
public static void prikaziDodajKursGUI() {
DodajKursGUI prozor = new DodajKursGUI();
prozor.setLocationRelativeTo(glavniProzor.getContentPane());
prozor.setVisible(true);
}
public static void prikaziObrisiKursGUI(Valuta valuta) {
if (valuta != null) {
ObrisiKursGUI prozor = new ObrisiKursGUI(valuta);
prozor.setLocationRelativeTo(glavniProzor.getContentPane());
prozor.setVisible(true);
}
}
public static void prikaziIzvrsiZamenuGUI(Valuta valuta) {
if (valuta != null) {
IzvrsiZamenuGUI prozor = new IzvrsiZamenuGUI(valuta);
prozor.setLocationRelativeTo(glavniProzor.getContentPane());
prozor.setVisible(true);
}
}
public static void prikaziAboutProzor(){
JOptionPane.showMessageDialog(glavniProzor.getContentPane(),
"Autor: Bojan Tomic, Verzija 1.0", "O programu Menjacnica",
JOptionPane.INFORMATION_MESSAGE);
}
public static void sacuvajUFajl() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(glavniProzor.getContentPane());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
menjacnica.sacuvajUFajl(file.getAbsolutePath());
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(glavniProzor.getContentPane(), e1.getMessage(),
"Greska", JOptionPane.ERROR_MESSAGE);
}
}
public static void ucitajIzFajla() {
try {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(glavniProzor.getContentPane());
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
menjacnica.ucitajIzFajla(file.getAbsolutePath());
glavniProzor.prikaziSveValute(menjacnica.vratiKursnuListu());
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(glavniProzor.getContentPane(), e1.getMessage(),
"Greska", JOptionPane.ERROR_MESSAGE);
}
}
public static void unesiKurs(JTextField textFieldNaziv, JTextField textFieldSkraceniNaziv,
JSpinner spinnerSifra, JTextField textFieldProdajniKurs,
JTextField textFieldKupovniKurs, JTextField textFieldSrednjiKurs) {
try {
Valuta valuta = new Valuta();
// Punjenje podataka o valuti
valuta.setNaziv(textFieldNaziv.getText());
valuta.setSkraceniNaziv(textFieldSkraceniNaziv.getText());
valuta.setSifra((Integer)(spinnerSifra.getValue()));
valuta.setProdajni(Double.parseDouble(textFieldProdajniKurs.getText()));
valuta.setKupovni(Double.parseDouble(textFieldKupovniKurs.getText()));
valuta.setSrednji(Double.parseDouble(textFieldSrednjiKurs.getText()));
// Dodavanje valute u kursnu listu
menjacnica.dodajValutu(valuta);
// Osvezavanje glavnog prozora
glavniProzor.prikaziSveValute(menjacnica.vratiKursnuListu());
} catch (Exception e1) {
JOptionPane.showMessageDialog(glavniProzor.getContentPane(), e1.getMessage(),
"Greska", JOptionPane.ERROR_MESSAGE);
}
}
public static void prikaziValutu(JTextField textFieldNaziv, JTextField textFieldSkraceniNaziv,
JTextField textFieldSifra, JTextField textFieldProdajniKurs, JTextField textFieldKupovniKurs,
JTextField textFieldSrednjiKurs, Valuta valuta) {
// Prikaz podataka o valuti
textFieldNaziv.setText(valuta.getNaziv());
textFieldSkraceniNaziv.setText(valuta.getSkraceniNaziv());
textFieldSifra.setText(""+valuta.getSifra());
textFieldProdajniKurs.setText(""+valuta.getProdajni());
textFieldKupovniKurs.setText(""+valuta.getKupovni());
textFieldSrednjiKurs.setText(""+valuta.getSrednji());
}
public static void izvrsiZamenu(Valuta valuta, boolean isSelected, String iznos, JTextField konIznos){
try{
double konacniIznos =
menjacnica.izvrsiTransakciju(valuta,isSelected, Double.parseDouble(iznos));
konIznos.setText(""+konacniIznos);
} catch (Exception e1) {
JOptionPane.showMessageDialog(glavniProzor.getContentPane(), e1.getMessage(),
"Greska", JOptionPane.ERROR_MESSAGE);
}
}
public static void obrisiValutu(Valuta valuta) {
try{
menjacnica.obrisiValutu(valuta);
glavniProzor.prikaziSveValute(menjacnica.vratiKursnuListu());
glavniProzor.dispose();
} catch (Exception e1) {
JOptionPane.showMessageDialog(glavniProzor.getContentPane(), e1.getMessage(),
"Greska", JOptionPane.ERROR_MESSAGE);
}
}
}
|
/*
* @(#) AbstractUnitText.java 2015年4月24日
*
* Copyright 2010 NetEase.com, Inc. All rights reserved.
*/
package blog;
/**
*
* @author hzdingyong
* @version 2015年4月24日
*/
public class AbstractUnitTest {
}
|
package gui1;
import javax.swing.*;
public class TencentFream {
private JPanel mainPanel;
private JPanel topPanel;
public static void main(String[] args)throws Exception {
//根据系统设置swing的外观
String lookAndFeel = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(lookAndFeel);
JFrame frame = new JFrame("TencentFream");
frame.setContentPane(new TencentFream().mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1391,794);
//frame.pack();
frame.setVisible(true);
}
}
|
/**
* Contains a variant of the application context interface for web applications,
* and the ContextLoaderListener that bootstraps a root web application context.
*/
@NonNullApi
@NonNullFields
package org.springframework.web.context;
import org.springframework.lang.NonNullApi;
import org.springframework.lang.NonNullFields;
|
package com.allmsi.sys.service.impl;
public class BaseService {
}
|
package com.joda.tentatime;
import java.util.List;
import com.google.gson.annotations.SerializedName;
/**
* Created by daniel on 8/7/13.
*
* @author Daniel Kristoffersson
*
* Copyright (c) Joseph Hejderup & Daniel Kristoffersson, All rights reserved.
* See License.txt in the project root for license information.
*/
public class SearchResponse {
@SerializedName("exams")
private List<ExamResult> results;
public List<ExamResult> getResults() {
return results;
}
public void setResults(List<ExamResult> results) {
this.results = results;
}
}
|
package info.zhiqing.tinypiratebay.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.arlib.floatingsearchview.FloatingSearchView;
import com.arlib.floatingsearchview.suggestions.model.SearchSuggestion;
import info.zhiqing.tinypiratebay.R;
import info.zhiqing.tinypiratebay.entities.SearchHistory;
import info.zhiqing.tinypiratebay.util.ConfigUtil;
import info.zhiqing.tinypiratebay.util.SearchUtil;
public class SearchActivity extends AppCompatActivity implements FloatingSearchView.OnSearchListener {
public static final String TAG = "SearchActivity";
public static final String EXTRA_URL = "info.zhiqing.tinybay.SearchActivity.EXTRA_URL";
public static final String EXTRA_TITLE = "info.zhiqing.tinybay.SearchActivity.EXTRA_TITLE";
private FloatingSearchView floatingSearchView;
private String title = "";
private String baseUrl = ConfigUtil.BASE_URL + "/search/hello";
private String searchUrl;
public static void actionStart(Context context, String url, String title) {
Intent intent = new Intent(context, SearchActivity.class);
intent.putExtra(EXTRA_URL, url);
intent.putExtra(EXTRA_TITLE, title);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
initView();
}
private void init() {
baseUrl = getIntent().getStringExtra(EXTRA_URL);
title = getIntent().getStringExtra(EXTRA_TITLE);
searchUrl = ConfigUtil.BASE_URL + "/search/";
}
private void initView() {
setContentView(R.layout.activity_search);
floatingSearchView = (FloatingSearchView) findViewById(R.id.floating_search);
floatingSearchView.setSearchText(title);
floatingSearchView.setOnHomeActionClickListener(new FloatingSearchView.OnHomeActionClickListener() {
@Override
public void onHomeClicked() {
onBackPressed();
}
});
SearchUtil.swapHistory(floatingSearchView);
floatingSearchView.setOnSearchListener(new FloatingSearchView.OnSearchListener() {
@Override
public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
SearchHistory history = (SearchHistory) searchSuggestion;
SearchUtil.addToHistory(SearchActivity.this, history.getTitle());
}
@Override
public void onSearchAction(String currentQuery) {
SearchUtil.addToHistory(SearchActivity.this, currentQuery);
getSupportFragmentManager().beginTransaction()
.replace(R.id.torrents_content, TorrentListFragment.newInstance(searchUrl + currentQuery))
.commit();
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
floatingSearchView.setSearchFocused(true);
}
});
getSupportFragmentManager().beginTransaction()
.replace(R.id.torrents_content, TorrentListFragment.newInstance(baseUrl))
.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSuggestionClicked(SearchSuggestion searchSuggestion) {
}
@Override
public void onSearchAction(String currentQuery) {
}
}
|
package com.my.learn.core_java2.ch1;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Created by tianzy on 5/27/14.
*/
public class RandomFileTest {
public static void main(String[] args) throws FileNotFoundException {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15);
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15);
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("employee.dat"));
for (Employee e : staff) {
e.writeData(out);
}
out.close();
RandomAccessFile in = new RandomAccessFile("employee.dat", "r");
int n = (int) (in.length() / Employee.RECORD_SIZE);
Employee[] newStaff = new Employee[n];
for (int i = n - 1; i >=0 ; i --) {
newStaff[i] = new Employee();
in.seek(i * Employee.RECORD_SIZE);
newStaff[i].readData(in);
}
in.close();
for (Employee e : newStaff) {
System.out.println(e);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Employee {
public Employee() {}
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
GregorianCalendar calendar = new GregorianCalendar(year, month-1, day);
hireDay = calendar.getTime();
}
public String toString() {
return getClass().getName() +
"[name=" + name
+ ",salary=" + salary
+ ",hireDay=" + hireDay
+ "]";
}
public void writeData(DataOutput output) throws IOException {
DataIO.writeFixedString(name, NAME_SIZE, output);
output.writeDouble(salary);
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(hireDay);
output.writeInt(calendar.get(Calendar.YEAR));
output.writeInt(calendar.get(Calendar.MONTH));
output.writeInt(calendar.get(Calendar.DAY_OF_MONTH));
}
public void readData(DataInput in) throws IOException {
name = DataIO.readFixedString(NAME_SIZE, in);
salary = in.readDouble();
int y = in.readInt();
int m = in.readInt();
int d = in.readInt();
GregorianCalendar calendar = new GregorianCalendar(y, m-1, d);
hireDay = calendar.getTime();
}
public static final int NAME_SIZE = 40;
public static final int RECORD_SIZE = 2 * NAME_SIZE + 8 + 4 + 4 + 4;
private String name;
private double salary;
private Date hireDay;
}
class DataIO {
public static String readFixedString(int size, DataInput in) throws IOException {
StringBuilder sb = new StringBuilder(size);
int i = 0;
boolean more = true;
while (more && i < size) {
char ch = in.readChar();
i ++;
if (ch == 0) {
more = false;
}
else {
sb.append(ch);
}
}
in.skipBytes(2 * (size - i));
return sb.toString();
}
public static void writeFixedString(String s, int size, DataOutput out) throws IOException {
for (int i = 0; i < size; i ++) {
char ch = 0;
if (i < s.length()) ch = s.charAt(i);
out.writeChar(ch);
}
}
} |
import java.util.ArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompactadorFixo {
public static void main(String[] args) {
long inicio = System.currentTimeMillis();
int numeroThreads = Integer.parseInt(args[0]);
int count = 0;
String saida = args[args.length - 1];
ExecutorService executor = Executors.newFixedThreadPool(numeroThreads);
ArrayList<String> argumentos = new ArrayList<>();
for (int i = 1; i < args.length - 1; i++) {
argumentos.add(args[i]);
}
while (!argumentos.isEmpty()) {
executor.execute(new CompactadorThread(argumentos.remove(0), saida + "/saida" + (count++) + ".zip"));
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("tempo total: " + (System.currentTimeMillis() - inicio));
}
}
|
/*
* EXI Testing Task Force Measurement Suite: http://www.w3.org/XML/EXI/
*
* Copyright © [2006] World Wide Web Consortium, (Massachusetts Institute of
* Technology, European Research Consortium for Informatics and Mathematics,
* Keio University). All Rights Reserved. This work is distributed under the
* W3C® Software License [1] 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.
*
* [1] http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
*/
package org.w3c.exi.ttf.parameters;
import com.sun.japex.Params;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.Set;
/**
* TTFMS test case parameters.
*
* @author AgileDelta
* @author Sun
*
*/
public final class TestCaseParameters {
/**
* The input file parameter.
*/
static public final String INPUT_FILE = "japex.inputFile";
static public final String PARAM_RECORDDECODEDEVENTS
= "org.w3c.exi.ttf.recordDecodedEvents";
/**
* The preserve parameter
*/
static public final String PRESERVE = "org.w3c.exi.ttf.preserve";
static public final String IGNORE_FIDELITY_SETTINGS = "org.w3c.exi.ttf.ignoreFidelitySettings";
/**
* The schema location parameter
*/
static public final String SCHEMA_LOCATION = "org.w3c.exi.ttf.schemaLocation";
static public final String USE_CASES = "org.w3c.exi.ttf.useCases";
static public final String SCHEMA_DEVIATIONS = "org.w3c.exi.ttf.schemaDeviations";
static public final String FRAGMENTS = "org.w3c.exi.ttf.fragments";
public final Params params;
public final Set<PreserveParam> preserves;
public boolean ignoreFidelitySettings;
public final String schemaLocation;
public final String xmlFile;
public final String xmlSystemId;
/**
* Inidcate whether the read test record parse events or not.
*/
public boolean traceRead;
/**
* Are deviations from the schema allowed?
*/
public boolean schemaDeviations;
/**
* Are document fragments allowed?
*/
public boolean fragments;
public TestCaseParameters(Params params, DriverParameters driverParams) {
this.params = params;
xmlFile = params.getParam(INPUT_FILE);
if (xmlFile == null)
throw new RuntimeException(INPUT_FILE + " not specified");
xmlSystemId = new File(xmlFile).toURI().toString();
ignoreFidelitySettings = params.getBooleanParam(IGNORE_FIDELITY_SETTINGS);
if (ignoreFidelitySettings)
params.setParam(PRESERVE, "");
preserves = PreserveParam.createPreserveSet(params.getParam(PRESERVE));
String workingSchemaLocation = params.getParam(SCHEMA_LOCATION);
// Communicate schema in all cases. In Neither and Document modes
// the resulting encoding MUST not be schema dependent
if (workingSchemaLocation != null && workingSchemaLocation.length() == 0) {
workingSchemaLocation = null;
}
schemaLocation = workingSchemaLocation;
traceRead = params.getBooleanParam(PARAM_RECORDDECODEDEVENTS);
schemaDeviations = params.getBooleanParam(SCHEMA_DEVIATIONS);
fragments = params.getBooleanParam(FRAGMENTS);
}
public InputStream getXmlInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(xmlFile));
}
}
|
package objetos.proyectiles;
import movimiento.Posicion;
import movimiento.patrones.Rectas;
import objetos.*;
import org.jdom.*;
import vistas.FactoryVistas;
import ar.uba.fi.algo3.titiritero.ControladorJuego;
import ar.uba.fi.algo3.titiritero.vista.Imagen;
import auxiliares.Vector;
/*
* Clase que modela los torpedos adaptables.
*/
public class Adaptable extends Proyectil {
public Adaptable(ObjetoMovil origen) {
super(origen);
setPoder(new Danio(0));
}
public Adaptable(ObjetoMovil origen, Posicion posicion) {
this(origen);
setPosicion(posicion);
}
public Adaptable(ObjetoMovil origen, int x, int y) {
this(origen, new Posicion(x, y));
}
@Override
public void daniarObjetoMovil(ObjetoMovil aeronave) {
/*
* Los adaptables hacen un da�o igual a la mitad de la energia de la
* aeronave
*/
this.setPoder(new Danio(aeronave.getCantidadEnergia() / 2));
super.daniarObjetoMovil(aeronave);
}
@Override
public Imagen darVista(ControladorJuego controlador) {
return FactoryVistas.crearVista(this, controlador);
}
/* Persistencia */
/* Constructor a partir de nodoXML */
public Adaptable(Element nodo) {
super();
setTamanio(5);
setPatron(new Rectas());
int pX = Integer.parseInt(nodo.getAttributeValue("posicionX"));
int pY = Integer.parseInt(nodo.getAttributeValue("posicionY"));
this.setPosicion(new Posicion(pX, pY));
int vX = Integer.parseInt(nodo.getAttributeValue("velocidadX"));
int vY = Integer.parseInt(nodo.getAttributeValue("velocidadY"));
setVelocidad(new Vector(vX, vY));
}
/* NodoXML a partir de instancia */
@Override
public Element obtenerNodo() {
Element nodo = new Element("adaptable");
nodo.setAttribute(new Attribute("posicionX", Integer.toString(this
.getPosicion().getEnX())));
nodo.setAttribute(new Attribute("posicionY", Integer.toString(this
.getPosicion().getEnY())));
nodo.setAttribute(new Attribute("velocidadX", Integer.toString(this
.getVelocidad().getComponenteX())));
nodo.setAttribute(new Attribute("velocidadY", Integer.toString(this
.getVelocidad().getComponenteY())));
return nodo;
}
}
|
/*
* Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.translation.in;
import java.util.Date;
import pl.edu.icm.unity.types.EntityScheduledOperation;
/**
* Describes entity status change prescribed by the profile.
* @author K. Benedyczak
*/
public class EntityChange
{
private EntityScheduledOperation scheduledOperation;
private Date scheduledTime;
public EntityChange(EntityScheduledOperation scheduledOperation, Date scheduledTime)
{
this.scheduledOperation = scheduledOperation;
this.scheduledTime = scheduledTime;
}
public EntityScheduledOperation getScheduledOperation()
{
return scheduledOperation;
}
public Date getScheduledTime()
{
return scheduledTime;
}
}
|
package bd.edu.httpdaffodilvarsity.jobtrack.JobManagement;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
import bd.edu.httpdaffodilvarsity.jobtrack.Database.DatabaseHelper;
import bd.edu.httpdaffodilvarsity.jobtrack.R;
import bd.edu.httpdaffodilvarsity.jobtrack.ui.login.TaskManagement;
public class CreateEmployeeJob extends AppCompatActivity {
DatabaseHelper myDB;
Button btnJobSave;
EditText edittextCreateJobTittle, edittextCreateJobDescription, edittextCreateJobDeadline, edittextCreateJobAssignto;
CheckBox checkboxCreateJobHadDeadline;
//Spinner edittextCreateJobAccessAbility;
//Spinner edittextCreateJobPriority;
//Spinner edittextCreateStatus;
//Spinner edittextCreateJobDepartment;
//Spinner edittextCreateJobRole;
EditText editTextJobDeadCreate;
//Button btn;
int year_x,month_x,day_x;
Spinner spinnerEmployeeJobAccessibility, spinnerEmployeeJobProgress, spinnerEmployeeJobPriority,
spinnerEmployeeJobStatus, spinnerEmployeejobDepartment, getSpinnerEmployeeJobRole;
ArrayAdapter<CharSequence> empJobAccessibilityAdapter, empJobProgressAdapter, empJobPriorityAdapter,
empJobStatusAdapter, empJobDepartmentAdapter, empJobRoleAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_employee_job);
myDB = new DatabaseHelper(this);
edittextCreateJobTittle = (EditText) findViewById(R.id.edit_text_job_title_create);
edittextCreateJobDescription = (EditText) findViewById(R.id.edit_text_job_description_create);
checkboxCreateJobHadDeadline = (CheckBox) findViewById(R.id.checkBox_job_had_deadline_create);
edittextCreateJobDeadline = (EditText) findViewById(R.id.edit_text_job_dead_create);
edittextCreateJobAssignto = (EditText) findViewById(R.id.edit_text_job_asign_to_create);
btnJobSave = (Button) findViewById(R.id.btn_job_save);
editTextJobDeadCreate = (EditText) findViewById(R.id.edit_text_job_dead_create);
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
/* calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);*/
showDate(year_x, month_x+1, day_x);
spinnerEmployeeJobAccessibility = (Spinner) findViewById(R.id.spinner_job_Accesibility_create);
empJobAccessibilityAdapter = ArrayAdapter.createFromResource(this,
R.array.employee_task_accessability, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
empJobAccessibilityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinnerEmployeeJobAccessibility.setAdapter(empJobAccessibilityAdapter);
spinnerEmployeeJobProgress = (Spinner) findViewById(R.id.spinner_job_progress_create);
empJobProgressAdapter = ArrayAdapter.createFromResource(this, R.array.employee_task_progress,
android.R.layout.simple_spinner_item);
empJobProgressAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEmployeeJobProgress.setAdapter(empJobProgressAdapter);
spinnerEmployeeJobPriority = (Spinner) findViewById(R.id.spinner_job_priority_create);
empJobPriorityAdapter = ArrayAdapter.createFromResource(this, R.array.employee_task_priority,
android.R.layout.simple_spinner_item);
empJobPriorityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEmployeeJobPriority.setAdapter(empJobPriorityAdapter);
spinnerEmployeeJobStatus = (Spinner) findViewById(R.id.spinner_job_status_create);
empJobStatusAdapter = ArrayAdapter.createFromResource(this, R.array.employee_task_status,
android.R.layout.simple_spinner_item);
empJobStatusAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEmployeeJobStatus.setAdapter(empJobStatusAdapter);
spinnerEmployeejobDepartment = (Spinner) findViewById(R.id.spinner_job_department_create);
empJobDepartmentAdapter = ArrayAdapter.createFromResource(this, R.array.employee_department,
android.R.layout.simple_spinner_item);
empJobDepartmentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerEmployeejobDepartment.setAdapter(empJobDepartmentAdapter);
getSpinnerEmployeeJobRole = (Spinner) findViewById(R.id.spinner_job_role_create);
empJobRoleAdapter = ArrayAdapter.createFromResource(this, R.array.employee_task_role,
android.R.layout.simple_spinner_item);
empJobRoleAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
getSpinnerEmployeeJobRole.setAdapter(empJobRoleAdapter);
//addJobManagement();
}
private void showDate(int year, int month, int day) {
editTextJobDeadCreate.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
@SuppressWarnings("deprecation")
public void showDatePicDialog(View view) {
showDialog(999);
//Toast.makeText(getApplicationContext(), "ca", Toast.LENGTH_SHORT).show();
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year_x,month_x,day_x);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
/* arg1 = year;
arg2 = month;
arg3 = day;*/
showDate(arg1, arg2+1, arg3);
}
};
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
/*public void addJobManagement(){
btnJobSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDB.insertJobManagement(edittextCreateJobTittle.getText().toString(),
edittextCreateJobDescription.getText().toString(), Integer.parseInt(checkboxCreateJobHadDeadline.getText().toString()),
edittextCreateJobDeadline.getText(), spinnerEmployeeJobAccessibility.getSelectedItem().toString(),
spinnerEmployeeJobProgress.getSelectedItem().toString(),spinnerEmployeeJobPriority.getSelectedItem().toString(),
spinnerEmployeeJobStatus.getSelectedItem().toString(), spinnerEmployeejobDepartment.getSelectedItem().toString(),
edittextCreateJobAssignto.getText().toString(), getSpinnerEmployeeJobRole.getSelectedItem().toString());
if (isInserted == true)
Toast.makeText(CreateEmployeeJob.this, "Data Inserted", Toast.LENGTH_SHORT).show();
else
Toast.makeText(CreateEmployeeJob.this, "Data is not Inserted", Toast.LENGTH_SHORT).show();
}
});
}*/
public void jobBack(View view){
Intent taskBack = new Intent(CreateEmployeeJob.this, TaskManagement.class);
startActivity(taskBack);
}
}
|
package com.design.pattern.visitor;
/**
* @Author: 98050
* @Time: 2019-01-21 22:08
* @Feature:
*/
public class Mouse implements ComputerPart {
@Override
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
|
package Àüº´¹Î_201702068_½Ç½À10;
public class Student {
private int _scoreKor;
private int _scoreEng;
private int _scoreCom;
private char score2Grade(int aScore) {
if (aScore >= 90) {
return 'A' ;
}
else if (aScore < 90 && aScore >= 80) {
return 'B' ;
}
else if (aScore < 80 && aScore >= 70) {
return 'C' ;
}
else if (aScore < 70 && aScore >= 60) {
return 'D' ;
}
else {
return 'F' ;
}
}
private double grade2Point (char aGrade) {
if (aGrade == 'A') {
return 4.0 ;
}
else if (aGrade == 'B') {
return 3.0 ;
}
else if (aGrade == 'C') {
return 2.0 ;
}
else if (aGrade == 'D') {
return 1.0 ;
}
else {
return 0.0 ;
}
}
public Student() {
this._scoreKor = 0 ;
this._scoreEng = 0 ;
this._scoreCom = 0 ;
}
public void setScoreKor (int aScore) {
this._scoreKor = aScore ;
}
public int scoreKor() {
return this._scoreKor;
}
public char gradeKor() {
return this.score2Grade(this._scoreKor) ;
}
public double pointKor() {
return this.grade2Point(gradeKor()) ;
}
public void setScoreEng (int aScore) {
this._scoreEng = aScore ;
}
public int scoreEng() {
return this._scoreEng;
}
public char gradeEng() {
return this.score2Grade(this._scoreEng) ;
}
public double pointEng() {
return this.grade2Point(gradeEng()) ;
}
public void setScoreCom (int aScore) {
this._scoreCom = aScore ;
}
public int scoreCom() {
return this._scoreCom;
}
public char gradeCom() {
return this.score2Grade(this._scoreCom) ;
}
public double pointCom() {
return this.grade2Point(gradeCom()) ;
}
public double gpa () {
double gradePointKor, gradePointEng, gradePointCom ;
gradePointKor = this.grade2Point(gradeKor());
gradePointEng = this.grade2Point(gradeEng());
gradePointCom = this.grade2Point(gradeCom());
return (gradePointKor + gradePointEng + gradePointCom) / 3.0 ;
}
}
|
import javax.swing.JPanel;
public class BattlefieldViewer extends JPanel{
}
|
package com.meizu.scriptkeeper.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import com.meizu.scriptkeeper.constant.URL;
import com.meizu.scriptkeeper.preferences.DefaultPreference;
import com.meizu.scriptkeeper.preferences.Preferences;
import com.meizu.scriptkeeper.utils.Log;
import com.meizu.scriptkeeper.utils.json.compile.JarCompiler;
import java.util.List;
/**
* Author: jinghao
* Date: 2015-04-10
* Package: com.meizu.anonymous.service
*/
public class WifiLockService extends Service {
public static final String SSID_INWEB_5 = "Inweb5";
public static final String PWD_INWEB_5 = "inwebtest";
private SharedPreferences pref_default;
public WifiManager wifiManager;
public void clearWifiConfig() {
try { //连接前先清除下当前连接
List<WifiConfiguration> configs = wifiManager.getConfiguredNetworks();
if (null == configs) {
Log.e("begin removeNetwork(), configs is null");
return;
}
for (WifiConfiguration config : configs) {
if(!config.SSID.equals(("\""+ pref_default.getString(DefaultPreference.WIFI_SSID, "Inweb5") +"\""))){
wifiManager.removeNetwork(config.networkId);
}
}
wifiManager.saveConfiguration();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
this.pref_default = this.getSharedPreferences(Preferences.DEFAULT_PREF, MODE_MULTI_PROCESS);
this.wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
new Thread(new Runnable() {
@Override
public void run() {
connectToNet();
}
}).start();
Log.e("Wifi lock on start command.");
return START_NOT_STICKY;
}
public void connectToNet(){
clearWifiConfig();
while (!isWifiConnected() || !this.wifiManager.isWifiEnabled() || !("\""+ pref_default.getString(DefaultPreference.WIFI_SSID, "Inweb5") +"\"").equals(wifiManager.getConnectionInfo().getSSID())){
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + pref_default.getString(DefaultPreference.WIFI_SSID, SSID_INWEB_5) + "\"";
config.preSharedKey = "\"" + pref_default.getString(DefaultPreference.WIFI_PWD, PWD_INWEB_5) + "\"";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.status = WifiConfiguration.Status.ENABLED;
int netId = wifiManager.addNetwork(config);
wifiManager.saveConfiguration();
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
this.wifiManager.setWifiEnabled(true);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Runnable() {
@Override
public void run() {
try {
JarCompiler compiler = new JarCompiler(WifiLockService.this, URL.QUERY_JAR_COMPILE);
} catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
}
private boolean isWifiConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
}
return false;
}
}
|
package com.sims.dao;
import com.sims.model.SalesHeader;
/**
*
* @author dward
*
*/
public interface SalesHeaderDao {
boolean save(SalesHeader entity);
boolean update(SalesHeader entity);
boolean delete(SalesHeader entity);
SalesHeader getEntityByTransNo(String transNo);
SalesHeader findById(int criteria);
long getTotalCount();
}
|
package com.zd.christopher.transceiver;
import android.os.Handler;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class ActionRequest extends StringRequest
{
Handler handler = new Handler();
private final static Listener<String> LISTENER = new Response.Listener<String>()
{
public void onResponse(String response)
{
}
};
private final static ErrorListener ERROR_LISTENER = new Response.ErrorListener()
{
public void onErrorResponse(VolleyError error)
{
}
};
public ActionRequest(String url)
{
//http:192.168.1.104:8181/Christopher/userAction_login.action?{......}
super(url, ActionRequest.LISTENER, ActionRequest.ERROR_LISTENER);
}
}
|
package dwz.framework.context;
import dwz.framework.user.User;
/**
* @Author: LCF
* @Date: 2020/1/8 16:38
* @Package: dwz.framework.context
*/
public class DefaultAppContext implements AppContext {
private User user = null;
public DefaultAppContext() {
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
}
|
package com.nextLevel.hero.humanResource.model.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.nextLevel.hero.humanResource.model.dao.HumanResourceMapper;
import com.nextLevel.hero.humanResource.model.dto.MyPageDTO;
import com.nextLevel.hero.member.model.dto.FindPwdDTO;
@Service("humanResourceService")
public class HumanResourceServiceImpl implements HumanResourceService {
private final HumanResourceMapper humanResourceMapper;
@Autowired
public HumanResourceServiceImpl(HumanResourceMapper humanResourceMapper) {
this.humanResourceMapper = humanResourceMapper;
}
@Override
public int updatePassword(int companyNo, FindPwdDTO findPwdDTO) { //비밀번호 변경
int updatePasswordResult = humanResourceMapper.updatePassword(companyNo, findPwdDTO);
return updatePasswordResult;
}
@Override
public int selectMemberNo(int companyNo, int idNo) { //memberNo 조회
int memberNo = humanResourceMapper.selectMemberNo(companyNo, idNo);
return memberNo;
}
@Override
public int selectjobNo(int companyNo, int idNo) { //jobNo 조회
int jobNo = humanResourceMapper.selectjobNo(companyNo, idNo);
return jobNo;
}
@Override
public MyPageDTO selectMypage(int companyNo, int idNo, int memberNo, int jobNo) { //mypage 유저 정보 조회
MyPageDTO MypageList = humanResourceMapper.selectMypage(companyNo, idNo, memberNo, jobNo);
return MypageList;
}
@Override
public int updateEmp(int companyNo, int idNo, MyPageDTO myPageDTO) { //mypage 유저 정보 수정
int EmpResult = humanResourceMapper.updateEmp(companyNo, idNo, myPageDTO);
return EmpResult;
}
@Override
public int updateMyPage(int companyNo, int idNo, MyPageDTO myPageDTO) { //mypage 유저 정보 수정
int MypageResult = humanResourceMapper.updateMypage(companyNo, idNo, myPageDTO);
return MypageResult;
}
}
|
package com.goldenasia.lottery.game;
import android.view.LayoutInflater;
import android.widget.TextView;
import com.goldenasia.lottery.R;
import com.goldenasia.lottery.data.Method;
import com.goldenasia.lottery.pattern.PickNumber;
import com.google.gson.JsonArray;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* 11选5“定单双, SDDDS”
* Created by User on 2016/2/23.
*/
public class SdddsGame extends Game {
private TextView lastClick;
public SdddsGame(Method method) {
super(method);
}
@Override
public void onInflate() {
LayoutInflater.from(topLayout.getContext()).inflate(R.layout.sddds, topLayout, true);
ButterKnife.bind(this, topLayout);
}
@Override
public void reset() {
if (lastClick != null) {
lastClick.setSelected(false);
}
notifyListener();
}
@OnClick({R.id.sddds_0, R.id.sddds_1, R.id.sddds_2, R.id.sddds_3, R.id.sddds_4, R.id.sddds_5})
public void onTextClick(TextView view) {
if (lastClick != null) {
lastClick.setSelected(false);
}
if (lastClick != view) {
view.setSelected(true);
lastClick = view;
} else {
lastClick = null;
}
notifyListener();
}
public void onRandomCodes() {
ArrayList<Integer> textid = random(0, 6, 1);
if (lastClick != null) {
lastClick.setSelected(false);
}
switch (textid.get(0)) {
case 0:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_0);
lastClick.setSelected(true);
break;
case 1:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_1);
lastClick.setSelected(true);
break;
case 2:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_2);
lastClick.setSelected(true);
break;
case 3:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_3);
lastClick.setSelected(true);
break;
case 4:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_4);
lastClick.setSelected(true);
break;
case 5:
lastClick = (TextView) topLayout.findViewById(R.id.sddds_5);
lastClick.setSelected(true);
break;
}
notifyListener();
}
@Override
public String getWebViewCode() {
JsonArray jsonArray = new JsonArray();
jsonArray.add(lastClick == null ? "" : lastClick.getText().toString());
return jsonArray.toString();
}
@Override
public String getSubmitCodes() {
return lastClick == null ? "" : lastClick.getText().toString();
}
public void onClearPick(Game game) {
if (lastClick != null) {
lastClick.setSelected(false);
}
notifyListener();
}
}
|
package com.amplify.ap.services.templates;
import com.amplify.ap.domain.Template;
import org.eclipse.jgit.api.CheckoutCommand;
import org.eclipse.jgit.api.FetchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.errors.GitAPIException;
import org.eclipse.jgit.errors.RepositoryNotFoundException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.revwalk.RevSort;
import org.eclipse.jgit.revwalk.RevTree;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.transport.RefSpec;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilter;
import org.eclipse.jgit.treewalk.filter.TreeFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Manages the connection to the git repository containing the {@link Template} files
* and adds/creates any metadata in the DB associated with these
*/
public class GitScanner implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(GitScanner.class);
private String gitDirectory;
private String gitRepositoryUri;
private String gitBranch;
private TemplateService templateService;
private Git gitRepository;
public GitScanner(String gitDirectory, String gitRepositoryUri, String gitBranch, TemplateService templateService) {
this.gitDirectory = gitDirectory;
this.gitRepositoryUri = gitRepositoryUri;
this.gitBranch = gitBranch;
this.templateService = templateService;
}
/**
* Open the git repository ready to be scanned
* if the repository doesn't currently exist then clone it
*
* @throws IOException
* @throws GitAPIException
*/
public void openGitRepo() throws IOException, GitAPIException {
try {
LOGGER.info("Opening the git repository {}", gitDirectory);
gitRepository = Git.open(new File(gitDirectory));
} catch (RepositoryNotFoundException e) {
// Need to clone the repo first
LOGGER.info("Cloning the git repository {}", gitRepositoryUri);
gitRepository = Git.cloneRepository()
.setURI(gitRepositoryUri)
.setDirectory(new File(gitDirectory))
.call();
}
}
/**
* Close the connection to the git repository in a controlled way
*/
public void closeGitRepo() {
LOGGER.info("Closing the git repository");
gitRepository.close();
}
@Override
public void run() {
scanGitRepository();
}
/**
* Scan the git repository for any template files.
* When a template is found this is checked against the
* existing database metadata and any additional information
* or templates detected since the last scan are added.
*/
public void scanGitRepository() {
try {
openGitRepo();
LOGGER.info("Fetching latest updates from git");
gitFetch();
LOGGER.info("Beginning scan of git repository");
// Make sure the correct branch is chacked out before parsing the files
CheckoutCommand checkout = gitRepository.checkout();
Ref branchRef = checkout.setName(gitBranch).call();
// HARD reset the branch to ensure it matches the remote
gitRepository.reset().setMode(ResetCommand.ResetType.HARD).setRef("origin/" + gitBranch).call();
// a RevWalk allows to walk over commits based on some filtering that is defined
try (RevWalk walk = new RevWalk(gitRepository.getRepository())) {
RevCommit commit = walk.parseCommit(branchRef.getObjectId());
RevTree tree = commit.getTree();
// now use a TreeWalk to iterate over all files in the Tree recursively
// you can set Filters to narrow down the results if needed
TreeWalk treeWalk = new TreeWalk(gitRepository.getRepository());
treeWalk.addTree(tree);
treeWalk.setRecursive(true);
while (treeWalk.next()) {
String templateFilePath = treeWalk.getPathString();
LOGGER.info("File found in git repository: " + templateFilePath);
RevCommit lastCommit = getLastCommitForFile(templateFilePath);
Template nextTemplate = new Template(templateFilePath,
null,
lastCommit.getAuthorIdent().getName(),
lastCommit.getAuthorIdent().getEmailAddress(),
lastCommit.getCommitterIdent().getName(),
lastCommit.getCommitterIdent().getEmailAddress(),
lastCommit.getFullMessage(),
lastCommit.getCommitTime());
templateService.updateTemplate(nextTemplate);
}
}
} catch (IOException | GitAPIException e) {
LOGGER.error("Error scanning git repository: " + e.getMessage());
} finally {
closeGitRepo();
}
}
/**
* Get the latest {@link RevCommit} from the git repository for the provided file path
*
* @param templateFilePath {@link String} containing the file path
* @return {@link RevCommit} the latest commit information for the file
* @throws IOException
*/
private RevCommit getLastCommitForFile(String templateFilePath) throws IOException {
try (RevWalk revWalk = new RevWalk(gitRepository.getRepository())) {
Ref headRef = gitRepository.getRepository().exactRef(Constants.HEAD);
RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId());
revWalk.markStart(headCommit);
revWalk.sort(RevSort.COMMIT_TIME_DESC);
revWalk.setTreeFilter(AndTreeFilter.create(PathFilter.create(templateFilePath), TreeFilter.ANY_DIFF));
return revWalk.next();
}
}
/**
* Perform a fetch on the git repo to get all the latest commits
*
* @throws {@link GitAPIException}
*/
private void gitFetch() throws GitAPIException {
FetchCommand fetch = gitRepository.fetch();
List<RefSpec> specs = new ArrayList<>();
specs.add(new RefSpec("+refs/heads/*:refs/remotes/origin/*"));
specs.add(new RefSpec("+refs/tags/*:refs/tags/*"));
specs.add(new RefSpec("+refs/notes/*:refs/notes/*"));
fetch.setRefSpecs(specs);
fetch.call();
}
}
|
package com.lize.pachong.service;
import com.lize.pachong.model.JdongBook;
import com.lize.pachong.parse.JdParse;
import com.lize.pachong.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
* 通过URL和客户端(client)处理请求返回的数据
*/
public class URLHandle {
public static List<JdongBook> urlParser(HttpClient client, String url) throws ParseException, IOException {
List<JdongBook> data = new ArrayList<>();
//获取响应资源
HttpResponse response = HttpUtils.getHtml(client, url);
//获取响应状态码
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){//内容获取成功
//获取响应实体内容,并且将其转换为utf-8形式的字符串编码
String entity = EntityUtils.toString(response.getEntity(), "utf-8");
data = JdParse.getData(entity);
}else {
//释放资源实体
EntityUtils.consume(response.getEntity());
}
return data;
}
}
|
package us.gibb.dev.gwt.command.results;
import us.gibb.dev.gwt.command.Result;
public class LongResult implements Result {
private static final long serialVersionUID = -1877901402004848760L;
private Long o;
LongResult() {
}
public LongResult(Long o) {
this.o = o;
}
public Long getLong() {
return o;
}
}
|
package com.goeuro;
import com.goeuro.client.HttpClient;
import com.goeuro.client.PositionRestClient;
import com.goeuro.csv.config.CsvConfiguration;
import com.goeuro.domain.GoEuroCity;
import com.goeuro.domain.GoEuroCsvInformationMapping;
import java.io.File;
import java.net.URI;
public class Task {
private URI url = URI.create("http://api.goeuro.com/api/v2/position/suggest/en");
private HttpClient client = new PositionRestClient(url);
private CsvConfiguration csvConfig = createCsvConfgiuratioForGoEuroCity();
public void run(String cityName) {
TransformGoEuroCity transform = new TransformGoEuroCity(client,csvConfig);
transform.transformation(cityName);
}
private CsvConfiguration createCsvConfgiuratioForGoEuroCity() {
return new CsvConfiguration(
GoEuroCity.class,
new File("cities.csv"),
GoEuroCsvInformationMapping.header,
GoEuroCsvInformationMapping.fieldMapping
);
}
}
|
package com.pengo.common.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("account_tbl")
public class Account
{
private Integer id;
private String userId;
private Integer money;
}
|
package com.joalib.board.action;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.joalib.DTO.ActionForward;
import com.joalib.board.svc.BoardPostHitupService;
public class BoardPostHitupAction implements dbAction {
@Override
public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
ActionForward forward = new ActionForward();
ServletContext context = request.getServletContext();
int board_no = Integer.parseInt(request.getParameter("board_no"));
BoardPostHitupService svc = new BoardPostHitupService();
boolean isSuccess = svc.boardHitup(board_no);
if(isSuccess) {
System.out.println("조회수 증가");
forward = new ActionForward();
forward.setRedirect(true);
forward.setPath("boardReadPage.bo?board_num="+board_no);
}
return forward;
}
}
|
package com.adt.guakebao.server.model;
public class Course {
private int courseId;
private String universityName;
private String collegeName;
private String majorName;
private int courseGrade;
private String courseTerm;
private String courseType;
private String courseName;
private String courseTeacher;
private float courseCredit;
private double compensationRate;
private double maxInsureSum;
public Course(int courseId, String universityName, String collegeName, String majorName, int courseGrade,
String courseTerm, String courseType, String courseName, String courseTeacher, float courseCredit,
double compensationRate, double maxInsureSum) {
super();
this.courseId = courseId;
this.universityName = universityName;
this.collegeName = collegeName;
this.majorName = majorName;
this.courseGrade = courseGrade;
this.courseTerm = courseTerm;
this.courseType = courseType;
this.courseName = courseName;
this.courseTeacher = courseTeacher;
this.courseCredit = courseCredit;
this.compensationRate = compensationRate;
this.maxInsureSum = maxInsureSum;
}
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
public String getUniversityName() {
return universityName;
}
public void setUniversityName(String universityName) {
this.universityName = universityName;
}
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
public String getMajorName() {
return majorName;
}
public void setMajorName(String majorName) {
this.majorName = majorName;
}
public int getCourseGrade() {
return courseGrade;
}
public void setCourseGrade(int courseGrade) {
this.courseGrade = courseGrade;
}
public String getCourseTerm() {
return courseTerm;
}
public void setCourseTerm(String courseTerm) {
this.courseTerm = courseTerm;
}
public String getCourseType() {
return courseType;
}
public void setCourseType(String courseType) {
this.courseType = courseType;
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseTeacher() {
return courseTeacher;
}
public void setCourseTeacher(String courseTeacher) {
this.courseTeacher = courseTeacher;
}
public float getCourseCredit() {
return courseCredit;
}
public void setCourseCredit(float courseCredit) {
this.courseCredit = courseCredit;
}
public double getCompensationRate() {
return compensationRate;
}
public void setCompensationRate(double compensationRate) {
this.compensationRate = compensationRate;
}
public double getMaxInsureSum() {
return maxInsureSum;
}
public void setMaxInsureSum(double maxInsureSum) {
this.maxInsureSum = maxInsureSum;
}
}
|
package lessom16;
import java.util.Objects;
public class Tovar implements Comparable<Tovar>{
private int buyCount;
private int price;
private String name;
private int reiting;
private int view;
private int review;
public Tovar() {
}
public Tovar(int buyCount, int price, String name, int reiting, int view, int review) {
this.buyCount = buyCount;
this.price = price;
this.name = name;
this.reiting = reiting;
this.view = view;
this.review = review;
}
public int getBuyCount() {
return buyCount;
}
public void setBuyCount(int buyCount) {
this.buyCount = buyCount;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getReiting() {
return reiting;
}
public void setReiting(int reiting) {
this.reiting = reiting;
}
public int getView() {
return view;
}
public void setView(int view) {
this.view = view;
}
public int getReview() {
return review;
}
public void setReview(int review) {
this.review = review;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tovar tovar = (Tovar) o;
return buyCount == tovar.buyCount &&
price == tovar.price &&
reiting == tovar.reiting &&
view == tovar.view &&
review == tovar.review &&
Objects.equals(name, tovar.name);
}
@Override
public int hashCode() {
return Objects.hash(buyCount, price, name, reiting, view, review);
}
@Override
public String toString() {
return "Tovar{" +
"buyCount = " + buyCount +
", price = " + price +
", name = '" + name + '\'' +
", reiting = " + reiting +
", view = " + view +
", review = " + review +
'}';
}
@Override
public int compareTo(Tovar o) {
if(this.price != o.price){
return this.price - o.price;
}
if(this.buyCount != o.buyCount){
return this.buyCount - o.buyCount;
}
if(this.reiting != o.reiting){
return this.reiting - o.reiting;
}
if(this.view != o.view){
return this.view - o.view;
}
if(this.review != o.review){
return this.review - o.review;
}
return this.name.compareTo(o.name);
}
}
|
package algorithms.strings.tries.practice200201;
import org.junit.Test;
public class TernarySearchTrieTest {
@Test
public void testPutGet() {
TernarySearchTrie<Integer> trieST = newSt();
System.out.println(trieST.get("she"));
System.out.println(trieST.get("sell"));
System.out.println(trieST.get("sea"));
System.out.println(trieST.get("shells"));
System.out.println(trieST.get("shellsa"));
}
@Test
public void testKeys() {
TernarySearchTrie<Integer> trieST = newSt();
for (String key : trieST.keys()) {
System.out.println(key);
}
System.out.println();
for (String key : trieST.keysWithPrefix("se")) {
System.out.println(key);
}
}
@Test
public void testLongestPrefix() {
TernarySearchTrie<Integer> trieST = newSt();
System.out.println(trieST.longestPrefixOf("abc"));
System.out.println(trieST.longestPrefixOf("shells"));
System.out.println(trieST.longestPrefixOf("shellsabc"));
}
@Test
public void testKeysThatMatch() {
TernarySearchTrie<Integer> trieST = newSt();
System.out.println(trieST.keysThatMatch("sh."));
System.out.println(trieST.keysThatMatch("sh.lls"));
System.out.println(trieST.keysThatMatch("s.."));
System.out.println(trieST.keysThatMatch("s..a"));
}
private TernarySearchTrie<Integer> newSt() {
TernarySearchTrie<Integer> trieST = new TernarySearchTrie<>();
trieST.put("she", 1);
trieST.put("sell", 2);
trieST.put("sea", 3);
trieST.put("shells", 4);
return trieST;
}
}
|
/**
* This class is generated by jOOQ
*/
package schema.tables.records;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record5;
import org.jooq.Row5;
import org.jooq.impl.UpdatableRecordImpl;
import schema.tables.SubmissionsStudentitem;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.8.4"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SubmissionsStudentitemRecord extends UpdatableRecordImpl<SubmissionsStudentitemRecord> implements Record5<Integer, String, String, String, String> {
private static final long serialVersionUID = -424032186;
/**
* Setter for <code>bitnami_edx.submissions_studentitem.id</code>.
*/
public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>bitnami_edx.submissions_studentitem.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>bitnami_edx.submissions_studentitem.student_id</code>.
*/
public void setStudentId(String value) {
set(1, value);
}
/**
* Getter for <code>bitnami_edx.submissions_studentitem.student_id</code>.
*/
public String getStudentId() {
return (String) get(1);
}
/**
* Setter for <code>bitnami_edx.submissions_studentitem.course_id</code>.
*/
public void setCourseId(String value) {
set(2, value);
}
/**
* Getter for <code>bitnami_edx.submissions_studentitem.course_id</code>.
*/
public String getCourseId() {
return (String) get(2);
}
/**
* Setter for <code>bitnami_edx.submissions_studentitem.item_id</code>.
*/
public void setItemId(String value) {
set(3, value);
}
/**
* Getter for <code>bitnami_edx.submissions_studentitem.item_id</code>.
*/
public String getItemId() {
return (String) get(3);
}
/**
* Setter for <code>bitnami_edx.submissions_studentitem.item_type</code>.
*/
public void setItemType(String value) {
set(4, value);
}
/**
* Getter for <code>bitnami_edx.submissions_studentitem.item_type</code>.
*/
public String getItemType() {
return (String) get(4);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record5 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, String, String, String, String> fieldsRow() {
return (Row5) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row5<Integer, String, String, String, String> valuesRow() {
return (Row5) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field1() {
return SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM.ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field2() {
return SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM.STUDENT_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field3() {
return SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM.COURSE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field4() {
return SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM.ITEM_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field5() {
return SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM.ITEM_TYPE;
}
/**
* {@inheritDoc}
*/
@Override
public Integer value1() {
return getId();
}
/**
* {@inheritDoc}
*/
@Override
public String value2() {
return getStudentId();
}
/**
* {@inheritDoc}
*/
@Override
public String value3() {
return getCourseId();
}
/**
* {@inheritDoc}
*/
@Override
public String value4() {
return getItemId();
}
/**
* {@inheritDoc}
*/
@Override
public String value5() {
return getItemType();
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord value1(Integer value) {
setId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord value2(String value) {
setStudentId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord value3(String value) {
setCourseId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord value4(String value) {
setItemId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord value5(String value) {
setItemType(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public SubmissionsStudentitemRecord values(Integer value1, String value2, String value3, String value4, String value5) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached SubmissionsStudentitemRecord
*/
public SubmissionsStudentitemRecord() {
super(SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM);
}
/**
* Create a detached, initialised SubmissionsStudentitemRecord
*/
public SubmissionsStudentitemRecord(Integer id, String studentId, String courseId, String itemId, String itemType) {
super(SubmissionsStudentitem.SUBMISSIONS_STUDENTITEM);
set(0, id);
set(1, studentId);
set(2, courseId);
set(3, itemId);
set(4, itemType);
}
}
|
package edu.jak.dummymailers.converter;
import java.util.ArrayList;
import java.util.List;
import edu.jak.dummymailers.model.eb.Mail;
import edu.jak.dummymailers.model.eb.MailAddress;
import edu.jak.dummymailers.model.pojo.MailResponse;
public class MailConverter {
public static MailResponse convert(Mail mail) {
MailResponse response = new MailResponse();
if (mail != null) {
// List<String> mailBCC = new ArrayList<String>();
// if (mail.getRecipientBCC() != null) {
// for (MailAddress mailAddress : mail.getRecipientBCC()) {
// mailBCC.add(mailAddress.getEmail());
// }
// response.setMailBCC(mailBCC);
// }
//
//
// if (mail.getRecipientCC() != null) {
// List<String> mailCC = new ArrayList<String>();
// for (MailAddress mailAddress : mail.getRecipientCC()) {
// mailCC.add(mailAddress.getEmail());
// }
// response.setMailCC(mailCC);
//
// }
//
// if (mail.getRecipientTo() != null) {
// List<String> mailTo = new ArrayList<String>();
// for (MailAddress mailAddress : mail.getRecipientTo()) {
// mailTo.add(mailAddress.getEmail());
// }
// response.setMailTo(mailTo);
//
// }
if (mail.getAddressList() != null) {
List<String> mailFrom = new ArrayList<String>();
List<String> mailBCC = new ArrayList<String>();
List<String> mailCC = new ArrayList<String>();
List<String> mailTo = new ArrayList<String>();
List<String> mailReplyTo = new ArrayList<String>();
for (MailAddress mailAddress : mail.getAddressList()) {
if (mailAddress.getType().equals("TO")) {
mailTo.add(mailAddress.getEmail());
} else if (mailAddress.getType().equals("CC")) {
mailCC.add(mailAddress.getEmail());
} else if (mailAddress.getType().equals("BCC")) {
mailBCC.add(mailAddress.getEmail());
}else if(mailAddress.getType().equals("FROM")){
mailFrom.add(mailAddress.getEmail());
}else if(mailAddress.getType().equals("REPLY_TO")){
mailReplyTo.add(mailAddress.getEmail());
}
}
response.setReplyMailTo(mailReplyTo);
response.setMailBCC(mailBCC);
response.setMailCC(mailCC);
response.setMailTo(mailTo);
response.setMailFrom(mailFrom);
}
response.setMailId(mail.getRemoteId());
response.setMailSubject(mail.getSubject());
response.setMailBody(mail.getBody());
response.setMailSentDate(mail.getSentDate().toString());
}
return response;
}
}
|
package proeza.sah.radio;
import org.apache.log4j.Logger;
import com.digi.xbee.api.XBeeDevice;
import com.digi.xbee.api.exceptions.TimeoutException;
import com.digi.xbee.api.exceptions.XBeeException;
import com.digi.xbee.api.listeners.IDataReceiveListener;
public class DummyRadio implements ILocalRadio {
private static final Logger log = Logger.getLogger(DummyRadio.class);
@Override
public void addDataListener(IDataReceiveListener dataReceiveListener) {
}
@Override
public void removeDataListeners() {
}
@Override
public void openConnection() throws XBeeException {
log.info("Opening connection");
}
@Override
public void closeConnection() throws XBeeException {
log.info("Closing connection");
}
@Override
public XBeeDevice getXbeeDevice() {
return null;
}
@Override
public void sendBroadcast(byte[] data) throws TimeoutException, XBeeException {
log.info("Sending broadcast");
}
} |
package com.test.dubbo;
import java.util.List;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import lombok.Getter;
import lombok.Setter;
/**
*
* Jmeter dubbo test plugin
*
* @author wangpeihu
* @date 2017/10/12 16:43
*/
@Getter
@Setter
public class DubboTestInvoker extends AbstractJavaSamplerClient {
private static final Logger log = LoggerFactory
.getLogger(DubboTestInvoker.class);
private String parameter;
private String ip;
private String service;
private String method;
private String port;
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
SpringConfiguration.class);
@Override
public SampleResult runTest(JavaSamplerContext param) {
SampleResult results = new SampleResult();
log.info("==========================================================");
log.info("param:{}", ToStringBuilder.reflectionToString(param, ToStringStyle.JSON_STYLE));
log.info("==========================================================");
// check parameter
prepareParameter(param);
// convert parameter
try {
results.sampleStart();
// invoke target
DubboClient client = context.getBean("dubboClient", DubboClient.class);
List<String> params = ParameterUtil.getRequestBodyList(parameter);
String url = "dubbo://" + ip + ":" + port;
ApiResponse invoke = client.invoke(url, service, method, params);
results.setResponseData(JSON.toJSONString(invoke.getOriginalResponse()), "UTF-8");
results.setSuccessful(true);
results.setResponseMessage(invoke.getRespText());
} catch (Exception e) {
results.setSuccessful(false);
results.setResponseMessage(e.toString());
} finally {
results.sampleEnd();
}
log.info("invoke over. ");
return results;
}
private void prepareParameter(JavaSamplerContext param) {
this.parameter = param.getParameter("parameter");
this.ip = param.getParameter("ip");
this.service = param.getParameter("service");
this.method = param.getParameter("method");
this.port = param.getParameter("port");
}
@Override
public Arguments getDefaultParameters() {
Arguments param = new Arguments();
param.addArgument("parameter", this.parameter);
param.addArgument("ip", this.ip);
param.addArgument("service", this.service);
param.addArgument("method", this.method);
param.addArgument("port", this.port);
return param;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.