text
stringlengths 10
2.72M
|
|---|
package house.greysap.shardpay.service;
import house.greysap.shardpay.dto.PaymentDto;
import java.math.BigDecimal;
import java.util.List;
public interface PaymentService {
void saveAll(List<PaymentDto> paymentDtos);
BigDecimal getTotalAmount(Long payer);
}
|
package com.tencent.mm.plugin.webview.model;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import com.tencent.mm.plugin.webview.model.z.b;
import com.tencent.mm.plugin.webview.stub.d;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
public final class z$c {
public static boolean a(String str, String str2, int i, d dVar, z.d dVar2, b bVar, int i2) {
if (dVar == null) {
x.e("MicroMsg.OauthAuthorizeLogic", "doOauthAuthorize invoker null");
return false;
}
x.i("MicroMsg.OauthAuthorizeLogic", "doOauthAuthorize scene: %d", new Object[]{Integer.valueOf(i)});
dVar2.c(new 1(dVar2, bVar));
Bundle bundle = new Bundle();
bundle.putString("oauth_url", str);
bundle.putString("biz_username", str2);
bundle.putInt("scene", i);
bundle.putInt("webview_binder_id", i2);
try {
bVar.add(1254);
dVar.s(1254, bundle);
return true;
} catch (RemoteException e) {
x.w("MicroMsg.OauthAuthorizeLogic", "invoker.doScene exp : %s", new Object[]{e.getLocalizedMessage()});
return false;
}
}
static void a(d dVar, String str, int i, ArrayList<String> arrayList, b bVar, boolean z, int i2) {
if (dVar == null) {
x.e("MicroMsg.OauthAuthorizeLogic", "doOauthAuthorizeConfirm invoker null");
return;
}
Bundle bundle = new Bundle();
bundle.putString("oauth_url", str);
bundle.putInt("opt", i);
bundle.putStringArrayList("scopes", arrayList);
bundle.putInt("webview_binder_id", i2);
if (z) {
try {
bVar.add(1373);
} catch (RemoteException e) {
x.w("MicroMsg.OauthAuthorizeLogic", "doOauthAuthorizeConfirm doScene exp : %s", new Object[]{e.getLocalizedMessage()});
return;
}
}
dVar.s(1373, bundle);
}
public static boolean b(String str, d dVar) {
if (z.bUd() == null && !z.bUe()) {
try {
Bundle g = dVar.g(94, new Bundle());
String str2 = null;
if (g != null) {
str2 = g.getString("oauth_host_paths");
}
if (bi.oW(str2)) {
str2 = "open.weixin.qq.com/connect/oauth2/authorize";
}
z.B(str2.split(";"));
z.yU();
} catch (RemoteException e) {
x.w("MicroMsg.OauthAuthorizeLogic", "isOauthHost exp:%s", new Object[]{e.getLocalizedMessage()});
return false;
}
}
if (z.bUd() == null || z.bUd().length == 0) {
x.i("MicroMsg.OauthAuthorizeLogic", "isOauthHost sOauthHostPaths nil");
return false;
}
Uri parse = Uri.parse(str);
String str3 = parse.getAuthority() + parse.getPath();
if (bi.oW(str3)) {
x.i("MicroMsg.OauthAuthorizeLogic", "isOauthHost target nil");
return false;
}
x.d("MicroMsg.OauthAuthorizeLogic", "isOauthHost target:%s", new Object[]{str3});
for (String equalsIgnoreCase : z.bUd()) {
if (str3.equalsIgnoreCase(equalsIgnoreCase)) {
return true;
}
}
return false;
}
public static boolean a(d dVar) {
try {
Bundle g = dVar.g(93, new Bundle());
if (g != null) {
return g.getBoolean("is_oauth_native");
}
x.w("MicroMsg.OauthAuthorizeLogic", "shouldNativeOauthIntercept Bundle isOauthNative null");
return false;
} catch (RemoteException e) {
x.w("MicroMsg.OauthAuthorizeLogic", "shouldNativeOauthIntercept exp:%s", new Object[]{e.getLocalizedMessage()});
return false;
}
}
public static String Qj(String str) {
if (bi.oW(str)) {
return null;
}
try {
String queryParameter = Uri.parse(str).getQueryParameter("appid");
if (!bi.oW(queryParameter)) {
return queryParameter;
}
x.i("MicroMsg.OauthAuthorizeLogic", "parseAppId try case not sensitive, oauthUrl:%s", new Object[]{str});
return Uri.parse(str.toLowerCase()).getQueryParameter("appid");
} catch (Exception e) {
return null;
}
}
}
|
package com.srikanth.functional.Functions;
import com.srikanth.functional.Functions.interfaces.NoArgFunction;
import com.srikanth.functional.Functions.interfaces.TriFunction;
import java.util.function.BiFunction;
public class C_BiFunctions {
public static void main(String[] args) {
// BiFunction unlike Function takes 2 arguments
BiFunction<Integer, Integer, Integer> sumOf = (x, y) -> x + y;
System.out.println(sumOf.apply(3, 5));
// How about functions for greater than 2 arguments?
// Implement own interface - Refer to interfaces package
TriFunction<Integer, Integer, Integer, Integer> addThree = (x, y, z) -> x + y + z;
System.out.println(addThree.apply(2, 3, 4));
NoArgFunction<String> sayHello = () -> "Hello!";
System.out.println(sayHello.apply());
}
}
|
package random;
// so finally block executes even after a return.. but what's the order of execution?
// finally block has to execute first, before it returns to its caller so this will actually sleep 1s before printing 5;
// but note that everything up to the return statement executes..
// this is why jcip listing 13.4-5 is correct since msg is already sent before returning flag
public class FinallyBlockExecuteAfterOrBeforeReturn {
public static void main(String[] args) throws InterruptedException {
System.out.println(getX());
}
private static int getX() throws InterruptedException {
try {
System.out.println("Will print before finally block");
return 5;
} finally {
Thread.sleep(1000);
System.out.println("finally block");
}
}
}
|
package stubs;
import org.apache.log4j.Logger;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
/**
* TopNDriver: assumes that all K's are unique for all given (K,V) values.
* Uniqueness of keys can be achieved by using AggregateByKeyDriver job.
*
* @author Mahmoud Parsian
*
*/
public class CountHighLowDriver extends Configured implements Tool {
private static Logger THE_LOGGER = Logger.getLogger(CountHighLowDriver.class);
public int run(String[] args) throws Exception {
FileSystem fs = FileSystem.get(getConf());
// Check if output path (args[1])exist or not
if (fs.exists(new Path(args[1]))) {
// If exist delete the output path
fs.delete(new Path(args[1]), true);
}
Job job = new Job(getConf());
job.setJobName("CountHighLowDriver");
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.setMapperClass(CountHighLowMapper.class);
job.setReducerClass(CountHighLowReducer.class);
job.setNumReduceTasks(1);
// // map()'s output (K,V)
// job.setMapOutputKeyClass(NullWritable.class);
// job.setMapOutputValueClass(Text.class);
// reduce()'s output (K,V)
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
// args[1] = input directory
// args[2] = output directory
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
boolean status = job.waitForCompletion(true);
THE_LOGGER.info("run(): status=" + status);
return status ? 0 : 1;
}
/**
* The main driver for "Top N" program. Invoke this method to submit the
* map/reduce job.
*
* @throws Exception
* When there is communication problems with the job tracker.
*/
public static void main(String[] args) throws Exception {
// Make sure there are exactly 3 parameters
if (args.length != 2) {
THE_LOGGER.warn("usage CountHighLowDriver <input> <output>");
System.exit(1);
}
THE_LOGGER.info("inputDir=" + args[0]);
THE_LOGGER.info("outputDir=" + args[1]);
int returnStatus = ToolRunner.run(new CountHighLowDriver(), args);
System.exit(returnStatus);
}
}
|
package com.example.taskb_ar;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
public class CameraOverlayView extends View {
private Location mDeviceLocation = null;
private ArrayList<TargetInfo> mTargetLocations = null;
private CameraOrientation mCameraOrientation = null;
private static final String TAG = CameraOverlayView.class.getSimpleName();
Bitmap up;
Bitmap bottom;
Bitmap left;
Bitmap right;
Bitmap target;
private static final float EPSILON = 67.0f; // ���(mm)
private final static float MILLI_PER_INCH = 25.4f; // 1 inch = 0.0254 meter
private static float DENSITY = 6.30f; // 1mm�(dot/mm)
private static float LEFTUPLIMIT = 5.1f;
private static float LEFTDOWNLIMIT = 3.1f;
private static float RIGHTDOWNLIMIT = 2.9f;
private static float RIGHTUPLIMIT = 0.2f;
private static final float DISPLAY_THRESHOLD = 0.01f;
public CameraOverlayView(Context context) {
super(context);
Resources r = context.getResources();
DisplayMetrics metrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay()
.getMetrics(metrics);
DENSITY = metrics.densityDpi / MILLI_PER_INCH;
// init picture
up = BitmapFactory.decodeResource(r, R.drawable.up);
bottom = BitmapFactory.decodeResource(r, R.drawable.down);
left = BitmapFactory.decodeResource(r, R.drawable.left);
right = BitmapFactory.decodeResource(r, R.drawable.right);
target = BitmapFactory.decodeResource(r, R.drawable.my_park_1);
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
//Log.i(TAG, "onDraw");
// int canvasWidth = canvas.getWidth();
// int canvasHeight = canvas.getHeight();
if ((mDeviceLocation != null) && (mTargetLocations != null)
&& (mTargetLocations.size() != 0)
&& (mCameraOrientation != null)) {
//Log.d(TAG, "Drawing Target.");
// Paint paint3 = new Paint();
// paint3.setColor(Color.rgb(236, 187, 60));
// paint3.setStrokeWidth(6.0f);
// paint3.setTextSize(10.0f);
//
// StringBuilder myDistance = new StringBuilder();
//
for (int i = 0; i < mTargetLocations.size(); i++) {
//Log.d(TAG, "Target:" + i);
DisplayInfo displayInfo = getDisplayPoint(mDeviceLocation,
mTargetLocations.get(i).getLocation(),
mCameraOrientation);
updateNumber(canvas);
try {
Thread.sleep(30);
} catch (InterruptedException e) {
}
// show distance
// myDistance.append("角度: " + mCameraOrientation.theta + "\n");
// myDistance.append("\n");
// myDistance.append("現在目標距離約 " + mCameraOrientation.distance /
// 1000 + " 公里" + "\n");
// myDistance.append("\n");
// myDistance.append("你現在的速度約 " + mCameraOrientation.speed *
// 3600 / 1000 + " 公里" + "\n");
// myDistance.append("\n");
// myDistance.append("預計到達時間 " + (mCameraOrientation.distance /
// 1000) / (mCameraOrientation.speed * 3600 / 1000) + " 小時" +
// "\n");
//
// canvas.drawText(String.valueOf(myDistance), 0, canvasHeight -
// 400, paint2);
if (displayInfo != null) {
//
updateLoc(canvas, displayInfo, i);
// float textSize = this.getFontSize(mDeviceLocation,
// mTargetLocations.get(i).getLocation());
// if (textSize == 0)
// continue;
// paint.setTextSize(textSize);
// canvas.drawText(mTargetLocations.get(i).getName(),
// canvasWidth / 2 + displayInfo.point.x, canvasHeight
// / 2 - displayInfo.point.y, paint);
}
else {
/* */
// canvas.drawText(mTargetLocations.get(i).getName()+": Behind your back.",
// canvasWidth/2,height+=LINEHEIGHT,paint2);
}
}
} else {
if (this.mDeviceLocation == null) {
Log.e(TAG, "mDeviceLocation is null");
}
if (this.mTargetLocations == null) {
Log.e(TAG, "mTargetLocations is null");
}
if (this.mCameraOrientation == null) {
Log.e(TAG, "mCameraOrientation is null");
}
}
}
private void updateNumber(Canvas canvas) {
Paint paint2 = new Paint();
paint2.setColor(Color.rgb(236, 187, 60));
paint2.setStrokeWidth(6.0f);
paint2.setTextSize(35.0f);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
canvas.drawText(
String.valueOf("角度: " + mCameraOrientation.theta + "\n"), 0,
canvasHeight - 400, paint2);
canvas.drawText(
String.valueOf("現在目標距離約 "
+ (int) Math.round(mCameraOrientation.distance) / 1000
+ " 公里" + "\n"), 0, canvasHeight - 430, paint2);
canvas.drawText(
String.valueOf("你現在的速度約 " + mCameraOrientation.speed * 3600
/ 1000 + " 公里" + "\n"), 0, canvasHeight - 460, paint2);
if (mCameraOrientation.speed != 0) {
canvas.drawText(String.valueOf("預計到達時間 "
+ (int) Math.round((mCameraOrientation.distance / 1000)
/ (mCameraOrientation.speed * 3600 / 1000)) + " 小時"
+ "\n"), 0, canvasHeight - 490, paint2);
} else {
canvas.drawText(String.valueOf("預計到達時間 "
+ ((int) Math
.round((mCameraOrientation.distance / 1000) / 3))
+ " 小時" + "\n"), 0, canvasHeight - 490, paint2);
}
paint2.setColor(Color.GREEN);
paint2.setStrokeWidth(10.0f);
paint2.setTextSize(35.0f);
switch (mCameraOrientation.direction) {
case (CameraOrientation.LEFT):
canvas.drawText(String.valueOf("請往右走"), 0, canvasHeight - 520,
paint2);
canvas.drawBitmap(right, canvasWidth - 150, canvasHeight/2, paint2); // replace x,y,and
// mPaint with whatever
// you need to.
break;
case (CameraOrientation.RIGHT):
canvas.drawText(String.valueOf("請往左走"), 0, canvasHeight - 520,
paint2);
canvas.drawBitmap(left, 0+100, canvasHeight/2, paint2);
break;
case (CameraOrientation.UP):
canvas.drawText(String.valueOf("請繼續直走"), 0, canvasHeight - 520,
paint2);
canvas.drawBitmap(up, canvasWidth/2 - 50, 0+20, paint2);
break;
default:
break;
}
if (Math.round(mCameraOrientation.distance) == 0){
canvas.drawText(
String.valueOf("你已經到達目的地!!!"), canvasWidth/2 - 100, canvasHeight/2, paint2);
}
}
private void updateLoc(Canvas canvas, DisplayInfo displayInfo, int index) {
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(6.0f);
paint.setTextSize(30.0f);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
float textSize = this.getFontSize(mDeviceLocation, mTargetLocations
.get(index).getLocation());
int[] ratio = this.getImageRatio(mDeviceLocation, mTargetLocations
.get(index).getLocation());
if (textSize == 0)
return;
else {
paint.setTextSize(textSize);
canvas.drawText(mTargetLocations.get(index).getName(), canvasWidth
/ 2 + displayInfo.point.x, canvasHeight / 2
- displayInfo.point.y, paint);
// int nh = (int) (target.getHeight() * (512.0 / (target.getWidth())));
//
// Bitmap scaled = Bitmap.createScaledBitmap(target, 512, nh,true);
Bitmap vB2 = Bitmap.createScaledBitmap( target, ratio[0], ratio[1], true);
canvas.drawBitmap(vB2, canvasWidth
/ 2 + displayInfo.point.x, canvasHeight / 2
- displayInfo.point.y, paint);
}
// bitmap = MediaStore.Images.Media.getBitmap(
// getApplicationContext().getContentResolver(),
// outputFileUri);
// ImageView ivTest1 = (ImageView) findViewById(R.id.imageView1);
//
// int nh = (int) (bitmap.getHeight() * (512.0 / bitmap
// .getWidth()));
// Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh,
// true);
}
private int[] getImageRatio(Location me, Location dest) {
int width;
int height;
float dist = me.distanceTo(dest);
if (dist < 5000) {
width = target.getWidth() * 2/3;
height = target.getHeight() * 2/3;
} else if (dist < 25000) {
width = target.getWidth() * 1/3;
height = target.getHeight() * 1/3;;
} else if (dist < 75000) {
width = target.getWidth() * 1/5;
height = target.getHeight() * 1/5;;
} else {
width = 0;
height = 0;
}
return new int[] {width, height};
}
private float getFontSize(Location me, Location dest) {
float ret = 0.0f;
float dist = me.distanceTo(dest);
if (dist < 5000) {
ret = 30.0f;
} else if (dist < 25000) {
ret = 20.0f;
} else if (dist < 75000) {
ret = 10.0f;
} else {
ret = 0.0f;
}
return ret;
}
private DisplayInfo getDisplayPoint(Location deviceLocation,
Location targetLocation, CameraOrientation cameraOrientation) {
// parameter log
// logd("device Location:"+deviceLocation.toString());
// logd("target Location:"+targetLocation.toString());
// logd("Camera Orientation:"+cameraOrientation.toString());
// variant
double x, z = 0;
// Return Values
DisplayInfo info = new DisplayInfo();
Point point = new Point();
// Distance
double distance = deviceLocation.distanceTo(targetLocation);
cameraOrientation.distance = distance;
// speed
double initSpeed = deviceLocation.getSpeed();
cameraOrientation.speed = initSpeed;
/* ��height 0 */
double height = targetLocation.getAltitude()
- deviceLocation.getAltitude();
cameraOrientation.height = height;
// Azimuth
double cameraAzimuth = cameraOrientation.Azimuth;
/* targetAzimuth */
// double targetAzimuth = Math.atan2(
// targetLocation.getLongitude()-deviceLocation.getLongitude(),
// targetLocation.getLatitude()-deviceLocation.getLatitude()
// );
/* Android API Location.bearintTo */
double targetAzimuth = Math.toRadians(deviceLocation
.bearingTo(targetLocation));
// cameraOrientation.targetAzimuth = (float)
// Math.toDegrees(deviceLocation
// .bearingTo(targetLocation));
cameraOrientation.targetAzimuth = targetAzimuth;
//Log.d(TAG, "targetAzimuth=" + Double.toString(targetAzimuth));
double theta = targetAzimuth - cameraAzimuth;
cameraOrientation.theta = -theta;
// cameraOrientation.theta = (float) Math.toDegrees(targetAzimuth -
// cameraOrientation.Azimuth);
// check direction
// use theta's angel to figure out up, down, left and right
// determine left or right direction
if ((cameraOrientation.theta >= LEFTDOWNLIMIT && cameraOrientation.theta <= LEFTUPLIMIT)
|| cameraOrientation.theta <= (-0.21f)) {
cameraOrientation.direction = CameraOrientation.LEFT;
} else if (cameraOrientation.theta <= RIGHTDOWNLIMIT
&& cameraOrientation.theta >= RIGHTUPLIMIT) {
cameraOrientation.direction = CameraOrientation.RIGHT;
} else {
cameraOrientation.direction = CameraOrientation.UP;
}
if (Math.cos(theta) < 0) {
return null;
}
x = EPSILON * Math.tan(theta);
z = (EPSILON * height) / (distance * Math.cos(theta));
// Pitch
double cameraPitch = -cameraOrientation.Pitch;
double y_ = Math.cos(-cameraPitch) * EPSILON + Math.sin(-cameraPitch)
* z;
double z_ = -Math.sin(-cameraPitch) * EPSILON + Math.cos(-cameraPitch)
* z;
if (y_ == 0) {
return null;
}
double z__ = (EPSILON / y_) * z_;
// Roll
double cameraRoll = cameraOrientation.Roll;
double x_ = Math.cos(-cameraRoll) * x + Math.sin(-cameraRoll) * z__;
double z___ = -Math.sin(-cameraRoll) * x + Math.cos(-cameraRoll) * z__;
point.x = (int) ((float) DENSITY * x_);
point.y = (int) ((float) DENSITY * z___);
info.point = point;
// Matrix
Matrix matrix = new Matrix();
matrix.setRotate((float) (-Math.toDegrees(cameraRoll)));
info.matrix = matrix;
// distance
info.distance = (float) distance;
// return
//Log.d(TAG, info.toString());
return info;
}
public void setDeviceLocation(Location location) {
if (location == null)
Log.d(TAG, "set null location!");
mDeviceLocation = location;
invalidate();
}
public void setCameraOrientation(CameraOrientation cameraOrientation) {
// Log.d(TAG,"setCameraDirection");
if ((mCameraOrientation == null)
|| checkCameraOrientation(cameraOrientation)) {
mCameraOrientation = cameraOrientation;
invalidate();
}
}
private boolean checkCameraOrientation(CameraOrientation cameraOrientation) {
boolean ret = true;
float diffAzimuth = cameraOrientation.Azimuth
- mCameraOrientation.Azimuth;
float diffPitch = cameraOrientation.Pitch - mCameraOrientation.Pitch;
float diffRoll = cameraOrientation.Roll - mCameraOrientation.Roll;
double a = Math.abs(Math.sin(diffAzimuth));
double p = Math.abs(Math.sin(diffPitch));
double r = Math.abs(Math.sin(diffRoll));
if (Math.max(Math.max(a, p), r) < DISPLAY_THRESHOLD) {
ret = false;
}
return ret;
}
public void setTargetInfoList(ArrayList<TargetInfo> infoList) {
Log.d(TAG, "setTargetInfoList");
mTargetLocations = infoList;
}
class CameraOrientation {
public float Azimuth = 0; // in radian
public float Pitch = 0; // in radian
public float Roll = 0; // in radian
double distance = 0;
public String toString() {
return new String("Azimuth=" + Math.toDegrees(Azimuth) + ",Pitch="
+ Math.toDegrees(Pitch) + ",Roll=" + Math.toDegrees(Roll));
}
double speed = 0;
double targetAzimuth = 0;
double theta = 0;
double height = 0;
int direction;
static final int UP = 1;
static final int DOWN = 2;
static final int LEFT = 3;
static final int RIGHT = 4;
}
class DisplayInfo {
public Point point = null;
public float distance = -1.0f;
public Matrix matrix = null;
public String toString() {
return new String("Point:" + point.toString() + ",distance:"
+ Float.toString(distance) + ",Matrix:"
+ matrix.toShortString());
}
}
}
|
package core.java.lab2;
import java.util.Arrays;
import java.util.Scanner;
public class Alphabeticalorder {
public static void main(String[] args) {
// TODO Auto-generated method stub
Alphabeticalorder .sortStrings();
}
public static void sortStrings() {
Scanner scan = new Scanner(System.in);
Scanner scan1 = new Scanner(System.in);
// Declare array size
int n;
System.out.print("Enter number of elements : ");
// Initialize array size
n = scan.nextInt();
String arr[] = new String[n];
System.out.println("Enter the String : ");
for (int i = 0; i < n; i++) {
arr[i] = scan1.nextLine();
}
Arrays.sort(arr); // Sort the array in alphabetical order
System.out.println(Arrays.toString(arr)); // Display the array
scan.close();
scan1.close();
}
}
|
package com.tencent.mm.plugin.ipcall.a.a;
public final class d {
public int dpx;
public int kpU;
public int kpx;
public final String toString() {
return String.format("IPCallUserInfo, userStatus: %d, syncKey: %d, memberId: %d", new Object[]{Integer.valueOf(this.dpx), Integer.valueOf(this.kpx), Integer.valueOf(this.kpU)});
}
}
|
package ro.tuc.dsrl.ds.handson.assig.one.server.entities;
/**
* Created by Rares on 10/15/2017.
*/
public class StudentId {
private int id;
public StudentId() {
}
public StudentId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
|
package com.examples.course.needone.adapter;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.examples.course.needone.R;
import com.examples.course.needone.model.Request;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by Jialu on 12/19/14.
*/
public class RequestAdapter extends BaseAdapter {
private FragmentActivity activity;
private LayoutInflater inflater;
private List<Request> requestItems;
//ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public RequestAdapter(FragmentActivity activity, List<Request> requestItems) {
this.activity = activity;
this.requestItems = requestItems;
}
@Override
public int getCount() {
return requestItems.size();
}
@Override
public Object getItem(int index) {
return requestItems.get(index);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.request_list_row, null);
// if (imageLoader == null)
// imageLoader = AppController.getInstance().getImageLoader();
// NetworkImageView thumbNail = (NetworkImageView) convertView
// .findViewById(R.id.thumbnail);
//TextView subject = (TextView) convertView.findViewById(R.id.subject);
TextView user = (TextView) convertView.findViewById(R.id.user);
TextView location = (TextView) convertView.findViewById(R.id.location);
TextView time = (TextView) convertView.findViewById(R.id.time);
TextView exptime = (TextView)convertView.findViewById(R.id.exptime);
TextView credit = (TextView) convertView.findViewById(R.id.credit);
TextView content = (TextView) convertView.findViewById(R.id.content);
Request m = requestItems.get(position);
// // thumbnail image
// thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);
//subject.setText("Subject: " + m.getSubject());
user.setText("User: " + m.getUser());
location.setText("Location: " + m.getLocation());
time.setText("Time: " + m.getTime());
exptime.setText("Expire time: " + m.getExptime());
credit.setText("Credit: " + m.getCredit());
content.setText("Content: " + m.getContent());
return convertView;
}
}
|
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import javax.swing.JOptionPane;
import net.proteanit.sql.DbUtils;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Angel
*/
public class GUI extends javax.swing.JFrame
{
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
//Objects
Bookings bookings = new Bookings();
Magician magician = new Magician();
WaitingList waitingList = new WaitingList();
/**
* Creates new form GUI
*/
public GUI()
{
initComponents();
connection = DBConnection.ConnectDB();
FillHolidayComboBox();
FillMagicianComboBox();
}
private void FillHolidayComboBox()
{
try
{
String HOLIDAY_QUERY = "SELECT * FROM Holiday";
preparedStatement = connection.prepareStatement(HOLIDAY_QUERY);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
String holidayName = resultSet.getString("Name");
HolidayComboBox.addItem(holidayName);
}
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}
private void FillMagicianComboBox()
{
try
{
String MAGICIAN_QUERY = "SELECT * FROM Magician";
preparedStatement = connection.prepareStatement(MAGICIAN_QUERY);
resultSet = preparedStatement.executeQuery();
while(resultSet.next())
{
String magicianName = resultSet.getString("Name");
MagicianStatusComboBox.addItem(magicianName);
}
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents()
{
jButton1 = new javax.swing.JButton();
TitleLabel = new javax.swing.JLabel();
InfoLabel1 = new javax.swing.JLabel();
InfoLabel2 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
CustomerNameLabel = new javax.swing.JLabel();
SelectHolidayLabel = new javax.swing.JLabel();
BookButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
BookingsTable = new javax.swing.JTable();
BookingsButton = new javax.swing.JButton();
WaitingListButton = new javax.swing.JButton();
HolidayComboBox = new javax.swing.JComboBox();
InfoLabel4 = new javax.swing.JLabel();
MagicianStatusComboBox = new javax.swing.JComboBox();
MagicianStatusButton = new javax.swing.JButton();
HolidayStatusComboBox = new javax.swing.JComboBox();
HolidayStatusButton = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
StatusTable = new javax.swing.JTable();
CustomerNameTextField = new javax.swing.JTextField();
jButton1.setText("jButton1");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
TitleLabel.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
TitleLabel.setText("Welcome to Book a Magician Corporation!");
InfoLabel1.setText("Thank you for choosing to make business with us! ");
InfoLabel2.setText("Please provide us with your name, magician you want to book, and the holiday you wish to book");
CustomerNameLabel.setText("Customer Name");
SelectHolidayLabel.setText("Select Holiday");
SelectHolidayLabel.setToolTipText("");
BookButton.setText("Book!");
BookButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
BookButtonActionPerformed(evt);
}
});
BookingsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]
{
},
new String []
{
"Customer", "Magician", "Holiday", "Time Stamp"
}
));
jScrollPane1.setViewportView(BookingsTable);
BookingsButton.setText("Check Bookings");
BookingsButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
BookingsButtonActionPerformed(evt);
}
});
WaitingListButton.setText("Check Waiting List");
WaitingListButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
WaitingListButtonActionPerformed(evt);
}
});
HolidayComboBox.setModel(HolidayComboBox.getModel());
InfoLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N
InfoLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
InfoLabel4.setText("Check Magician or Holiday Status");
MagicianStatusComboBox.setModel(MagicianStatusComboBox.getModel());
MagicianStatusComboBox.setSelectedItem(MagicianStatusComboBox);
MagicianStatusButton.setText("Magician Status");
MagicianStatusButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
MagicianStatusButtonActionPerformed(evt);
}
});
HolidayStatusComboBox.setModel(HolidayComboBox.getModel());
HolidayStatusButton.setText("Holiday Status");
HolidayStatusButton.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(java.awt.event.ActionEvent evt)
{
HolidayStatusButtonActionPerformed(evt);
}
});
StatusTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][]
{
},
new String []
{
"Customer", "Magician", "Holiday", "TimeStamp"
}
));
jScrollPane2.setViewportView(StatusTable);
CustomerNameTextField.setText("Enter your name");
CustomerNameTextField.addFocusListener(new java.awt.event.FocusAdapter()
{
public void focusGained(java.awt.event.FocusEvent evt)
{
CustomerNameTextFieldFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt)
{
CustomerNameTextFieldFocusLost(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(476, 476, 476)
.addComponent(BookingsButton, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(WaitingListButton, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(180, 180, 180))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(47, 47, 47)
.addComponent(BookButton, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(15, 15, 15)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel7)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(CustomerNameLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SelectHolidayLabel))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(HolidayComboBox, 0, 142, Short.MAX_VALUE)
.addComponent(CustomerNameTextField))))
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(MagicianStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(MagicianStatusButton)
.addGap(58, 58, 58)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(HolidayStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HolidayStatusButton))
.addGap(88, 88, 88)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 658, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane2))
.addGap(107, 107, 107))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(InfoLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 347, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(380, 380, 380)
.addComponent(TitleLabel)))
.addGroup(layout.createSequentialGroup()
.addGap(276, 276, 276)
.addComponent(InfoLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 643, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(InfoLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 359, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(TitleLabel)
.addGap(18, 18, 18)
.addComponent(InfoLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(InfoLabel2)
.addGap(49, 49, 49)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(CustomerNameLabel)
.addComponent(CustomerNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(26, 26, 26)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SelectHolidayLabel)
.addComponent(HolidayComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(BookButton, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(BookingsButton)
.addComponent(WaitingListButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 83, Short.MAX_VALUE)
.addComponent(InfoLabel4)
.addGap(2, 2, 2)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(MagicianStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(HolidayStatusComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(80, 80, 80)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(MagicianStatusButton)
.addComponent(HolidayStatusButton)))
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(64, 64, 64))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BookingsButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_BookingsButtonActionPerformed
{//GEN-HEADEREND:event_BookingsButtonActionPerformed
String BOOKINGS_QUERY = "SELECT * FROM Bookings";
try
{
preparedStatement = connection.prepareStatement(BOOKINGS_QUERY);
resultSet = preparedStatement.executeQuery();
BookingsTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}//GEN-LAST:event_BookingsButtonActionPerformed
private void WaitingListButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_WaitingListButtonActionPerformed
{//GEN-HEADEREND:event_WaitingListButtonActionPerformed
String WAITING_LIST_QUERY = "SELECT * FROM WaitingList";
try
{
preparedStatement = connection.prepareStatement(WAITING_LIST_QUERY);
resultSet = preparedStatement.executeQuery();
BookingsTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}//GEN-LAST:event_WaitingListButtonActionPerformed
private void BookButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_BookButtonActionPerformed
{//GEN-HEADEREND:event_BookButtonActionPerformed
String customerName = CustomerNameTextField.getText();
String holidayName = (String) HolidayComboBox.getSelectedItem();
String[] magicianName = Magician.checkForAvailableMagician(holidayName);
Bookings.setTimeStamp(new Timestamp (Calendar.getInstance().getTime().getTime()));
if(magician.checkForAvailableMagician(holidayName).length > 0 && (!"Enter your name".equals(customerName) && !"".equals(customerName)))
{
bookings.addBooking(customerName, magicianName[0], holidayName, bookings.getTimestamp());
JOptionPane.showMessageDialog(GUI.this, String.format("Book sucessfully done!\nYou have been assigned " + magicianName[0] +
" for " + holidayName + "\nPlease check Bookings for confirmation",
evt.getActionCommand()));
}
else if(magician.checkForAvailableMagician(holidayName).length == 0 && (!"Enter your name".equals(customerName) && !"".equals(customerName)))
{
waitingList.addToWaitingList(customerName, holidayName, bookings.getTimestamp());
JOptionPane.showMessageDialog(GUI.this, String.format("No available magicians for " + holidayName +
"\nYou have entered the waiting list\nCheck waiting list for confirmation",
evt.getActionCommand()));
}
else
JOptionPane.showMessageDialog(GUI.this, "Please enter your name", "Error!", JOptionPane.ERROR_MESSAGE);
CustomerNameTextField.setText("Enter your name");
}//GEN-LAST:event_BookButtonActionPerformed
private void MagicianStatusButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_MagicianStatusButtonActionPerformed
{//GEN-HEADEREND:event_MagicianStatusButtonActionPerformed
String MAGICIAN_STATUS_QUERY = "SELECT Customer, Holiday, TimeStamp FROM Bookings WHERE Magician = ?";
try
{
preparedStatement = connection.prepareStatement(MAGICIAN_STATUS_QUERY);
preparedStatement.setString(1, (String) MagicianStatusComboBox.getSelectedItem());
resultSet = preparedStatement.executeQuery();
StatusTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}//GEN-LAST:event_MagicianStatusButtonActionPerformed
private void HolidayStatusButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_HolidayStatusButtonActionPerformed
{//GEN-HEADEREND:event_HolidayStatusButtonActionPerformed
String HOLIDAY_STATUS_QUERY = "SELECT Customer, Magician, TimeStamp FROM Bookings WHERE Holiday = ?";
try
{
preparedStatement = connection.prepareStatement(HOLIDAY_STATUS_QUERY);
preparedStatement.setString(1, (String) HolidayStatusComboBox.getSelectedItem());
resultSet = preparedStatement.executeQuery();
StatusTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
catch(SQLException sqlException)
{
sqlException.printStackTrace();
}
}//GEN-LAST:event_HolidayStatusButtonActionPerformed
private void CustomerNameTextFieldFocusGained(java.awt.event.FocusEvent evt)//GEN-FIRST:event_CustomerNameTextFieldFocusGained
{//GEN-HEADEREND:event_CustomerNameTextFieldFocusGained
CustomerNameTextField.setText("");
}//GEN-LAST:event_CustomerNameTextFieldFocusGained
private void CustomerNameTextFieldFocusLost(java.awt.event.FocusEvent evt)//GEN-FIRST:event_CustomerNameTextFieldFocusLost
{//GEN-HEADEREND:event_CustomerNameTextFieldFocusLost
String customerName = CustomerNameTextField.getText();
CustomerNameTextField.setText(customerName);
if("".equals(customerName))
CustomerNameTextField.setText("Enter your name");
}//GEN-LAST:event_CustomerNameTextFieldFocusLost
/**
* @param args the command line arguments
*/
public static void main(String args[])
{
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try
{
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName()))
{
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(GUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new GUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BookButton;
private javax.swing.JButton BookingsButton;
private javax.swing.JTable BookingsTable;
private javax.swing.JLabel CustomerNameLabel;
private javax.swing.JTextField CustomerNameTextField;
private javax.swing.JComboBox HolidayComboBox;
private javax.swing.JButton HolidayStatusButton;
private javax.swing.JComboBox HolidayStatusComboBox;
private javax.swing.JLabel InfoLabel1;
private javax.swing.JLabel InfoLabel2;
private javax.swing.JLabel InfoLabel4;
private javax.swing.JButton MagicianStatusButton;
private javax.swing.JComboBox MagicianStatusComboBox;
private javax.swing.JLabel SelectHolidayLabel;
private javax.swing.JTable StatusTable;
private javax.swing.JLabel TitleLabel;
private javax.swing.JButton WaitingListButton;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel7;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
// End of variables declaration//GEN-END:variables
}
|
package Fructe;
/**
* This class is used for agregation
*/
public class TaraProducere {
private String denumire; //denumire tara de producere
private String denumireCompanie;
/**
* @param denumire The name of import country
* @param denumireCompanie The name of import country
*/
public TaraProducere(String denumire, String denumireCompanie) {
this.denumire = denumire;
this.denumireCompanie = denumireCompanie;
}
/**
* @return This return the name of import country
*/
public String getDenumire() {
return denumire;
}
/**
* @return This returns the name of import company
*/
public String getDenumireCompanie() {
return denumireCompanie;
}
}
|
package org.fao.unredd.api.model.geostore;
import it.geosolutions.geostore.core.model.Resource;
import it.geosolutions.unredd.geostore.model.UNREDDLayerUpdate;
import org.fao.unredd.api.json.LayerUpdateRepresentation;
import org.fao.unredd.api.model.LayerUpdate;
public class GeostoreLayerUpdate extends AbstractGeostoreElement implements
LayerUpdate {
public GeostoreLayerUpdate(Resource resource) {
super(resource);
}
public LayerUpdateRepresentation getJSON() {
return new LayerUpdateRepresentation(Long.toString(resource.getId()),
resource.getName(), getAttribute(
UNREDDLayerUpdate.Attributes.LAYER.getName())
.getTextValue(), getAttribute(
UNREDDLayerUpdate.Attributes.YEAR.getName())
.getTextValue(), getAttribute(
UNREDDLayerUpdate.Attributes.MONTH.getName())
.getTextValue(), getAttribute(
UNREDDLayerUpdate.Attributes.DAY.getName())
.getTextValue(), getAttribute(
UNREDDLayerUpdate.Attributes.PUBLISHED.getName())
.getTextValue());
}
}
|
package com.bigdata.app.bolt;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Collection;
import java.util.ArrayList;
import java.util.*;
import java.lang.Double;
//import java.lang.Calendar;
import java.text.*;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import com.google.common.base.Splitter;
import javax.json.*;
/**
* Breaks each tweet into words and gets the location of each tweet and
* assocaites its value to hashtag
*
* @author - centos
*/
public final class MilestonesBolt extends BaseRichBolt {
private static final Logger LOGGER = LoggerFactory
.getLogger(MilestonesBolt.class);
private static final long serialVersionUID = -5094673458112835122L;
private OutputCollector collector;
private String path;
public MilestonesBolt() {
LOGGER.info("milestones bolt is initialized...........");
}
private Map<String, Integer> afinnSentimentMap = new HashMap<String, Integer>();
public final void prepare(final Map map,
final TopologyContext topologyContext,
final OutputCollector collector) {
this.collector = collector;
}
public final void declareOutputFields(
final OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(new Fields("count", "hour", "day", "month", "year", "hashtag"));
}
public final void execute(final Tuple input) {
try {
String hashtag = (String) input.getValueByField("hashtag");
String dateStr = (String) input.getValueByField("created_at");
System.out.println("..... date .... " + dateStr);
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
int year = cal.get(Calendar.YEAR);
int hour = cal.get(Calendar.HOUR_OF_DAY);
System.out.println("..... date, month, year .... " + day + month + year);
collector.emit(new Values(1L, hour, day, month, year, hashtag));
this.collector.ack(input);
} catch (Exception exception) {
exception.printStackTrace();
this.collector.fail(input);
}
}
}
|
package com.bowlong.third.poi.excel.hss;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Vector;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.poifs.filesystem.POIFSFileSystem;
import com.bowlong.json.MyJson;
import com.bowlong.lang.NumEx;
import com.bowlong.lang.StrEx;
import com.bowlong.objpool.StringBufPool;
import com.bowlong.third.poi.PoiEx;
import com.bowlong.util.MapEx;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HSS extends PoiEx{
public static final HSSFWorkbook openWorkbook(final FileInputStream stream)
throws Exception {
POIFSFileSystem fs = openFS(stream);
HSSFWorkbook wb = new HSSFWorkbook(fs);
return wb;
}
public static final int sheetNum(final HSSFWorkbook wb) {
return wb.getNumberOfSheets();
}
public static final HSSFSheet getSheet(final HSSFWorkbook wb,
final String name) {
HSSFSheet sheet = wb.getSheet(name);
return sheet;
}
public static final Map<String, HSSFSheet> getSheetMaps(
final HSSFWorkbook wb) {
Map<String, HSSFSheet> ret = new HashMap<String, HSSFSheet>();
HSSFSheet[] sheets = sheets(wb);
for (HSSFSheet sheet : sheets) {
ret.put(sheet.getSheetName(), sheet);
}
return ret;
}
public static final HSSFSheet[] sheets(final HSSFWorkbook wb) {
int sheetNum = sheetNum(wb);
HSSFSheet[] r2 = new HSSFSheet[sheetNum];
for (int i = 0; i < sheetNum; i++) {
HSSFSheet sheet = wb.getSheetAt(i);
if (sheet == null)
break;
r2[i] = sheet;
}
return r2;
}
// //////////////////////
public static final int estimateSize(final HSSFSheet sheet) {
int r2 = 8;
List<Map<String, String>> headers = readHeaders(sheet);
for (Map<String, String> map : headers) {
String sType = getValue(map);
sType = sType.toLowerCase();
if (sType.equals("int")) {
r2 += 4;
} else if (sType.equals("boolean")) {
r2 += 1;
} else if (sType.equals("double")) {
r2 += 8;
} else if (sType.equals("int")) {
r2 += 4;
} else if (sType.equals("long")) {
r2 += 8;
} else if (sType.equals("string")) {
r2 += 64;
} else {
r2 += 8;
}
}
return r2;
}
public static final List<Map<String, String>> readHeaders(
final HSSFSheet sheet) {
List<Map<String, String>> r2 = new ArrayList<Map<String, String>>();
for (int i = 0; i < 1024; i++) {
String sName = getString(sheet, LINE_NAME, i);
String sType = getString(sheet, LINE_TYPE, i);
if (StrEx.isEmpty(sName) || StrEx.isEmpty(sType))
break;
Map<String, String> e = new HashMap<String, String>();
e.put(sName, sType);
r2.add(e);
}
return r2;
}
public static final int nameCol(final HSSFSheet sheet, final String name) {
for (int i = 0; i < 255; i++) {
String str = getName(sheet, i);
if (str != null && str.equals(name))
return i;
}
return -1;
}
public static final String getName(final HSSFSheet sheet, final int col) {
String sName = getString(sheet, LINE_NAME, col);
return sName;
}
public static final List<String> getNames(final HSSFSheet sheet) {
List<String> r2 = new ArrayList<>();
for (int i = 0; i < 255; i++) {
String str = getName(sheet, i);
if (str == null)
return r2;
r2.add(str);
}
return r2;
}
public static final String getType(final HSSFSheet sheet, int col) {
String sName = getString(sheet, LINE_TYPE, col);
return sName.toLowerCase();
}
public static final String getType(final HSSFSheet sheet, final String name) {
int col = nameCol(sheet, name);
if (col < 0)
return TYPE_UNKNOW;
return getType(sheet, col);
}
public static final String getCName(final HSSFSheet sheet, int col) {
String sName = getString(sheet, LINE_CNAME, col);
return sName;
}
public static final String getCName(final HSSFSheet sheet, final String name) {
int col = nameCol(sheet, name);
if (col < 0)
return "";
return getCName(sheet, col);
}
public static final String getMemo(final HSSFSheet sheet, int col) {
String sName = getString(sheet, LINE_MEMO, col);
return sName;
}
public static final String getMemo(final HSSFSheet sheet, final String name) {
int col = nameCol(sheet, name);
if (col < 0)
return "";
return getMemo(sheet, col);
}
public static final List<String> readIndexs(final HSSFSheet sheet) {
List<String> r2 = new ArrayList<String>();
for (int i = 0; i < 1024; i++) {
String sName = getString(sheet, 0, i);
String sComment = getComment(sheet, 1, i);
if (sComment == null || sComment.isEmpty())
continue;
r2.add(sName);
}
return r2;
}
public static final String[][] readAll2D(final HSSFSheet sheet)
throws Exception {
List<String[]> datas = new ArrayList<String[]>();
int col = 0;
int row = 1;
for (row = 0; row < LINE_DATA_MAX; row++) {
String[] rd = readRow(sheet, row);
if (rd == null || rd.length <= 0)
break;
if (col <= 0)
col = rd.length;
datas.add(rd);
}
String[][] r2 = new String[row][col];
int i = 0;
for (String[] ss : datas) {
r2[i] = ss;
i++;
}
return r2;
}
public static final String[] readRow(final HSSFSheet sheet, final int row)
throws Exception {
List<String> list = new Vector<String>();
for (int i = 0; i < 1024; i++) {
String str = getString(sheet, row, i);
if (StrEx.isEmpty(str))
break;
list.add(str);
}
return toArray(list);
}
public static final String[] toArray(List<String> list) {
String[] r2 = new String[list.size()];
int i = 0;
for (String s : list) {
r2[i] = s;
i++;
}
return r2;
}
public static final List<List<Map<String, Object>>> readData(
final HSSFSheet sheet, final List<Map<String, String>> headers)
throws Exception {
List<List<Map<String, Object>>> r2 = new ArrayList<List<Map<String, Object>>>();
for (int row = LINE_DATA_MIN; row < LINE_DATA_MAX; row++) {
String dockId = getString(sheet, row, 0);
if (StrEx.isEmpty(dockId))
break;
final List<Map<String, Object>> rowData = readRow(sheet, headers,
row);
r2.add(rowData);
}
return r2;
}
public static final List<Map<String, Object>> readRow(
final HSSFSheet sheet, final List<Map<String, String>> headers,
final int row) throws Exception {
int column = 0;
List<Map<String, Object>> row2 = new ArrayList<Map<String, Object>>();
for (Map<String, String> t : headers) {
String name = MapEx.getKey(t);
String type = MapEx.getValue(t);
Object obj = getObject(sheet, type, row, column);
Map<String, Object> e = new HashMap<String, Object>();
e.put(name, obj);
row2.add(e);
column++;
}
return row2;
}
public static final String upperN(final String s, final int p) {
int len = s.length();
if (len <= 0)
return "";
StringBuffer sb = StringBufPool.borrowObject();
try {
sb.append(s);
sb.replace(p, p + 1, s.substring(p, p + 1).toUpperCase());
return sb.toString();
} finally {
StringBufPool.returnObject(sb);
}
}
public static final Object getObject(final HSSFSheet sheet,
final String type, final int row, final int column) {
String type2 = type.toLowerCase();
if (type2.equals(TYPE_BOOLEAN)) {
return getBool(sheet, row, column);
} else if (type2.equals(TYPE_STRING)) {
return getString(sheet, row, column);
} else if (type2.equals(TYPE_INT)) {
return getInt(sheet, row, column);
} else if (type2.equals(TYPE_LONG)) {
return getLong(sheet, row, column);
} else if (type2.equals(TYPE_DOUBLE)) {
return getDouble(sheet, row, column);
} else if (type2.equals(TYPE_JSON)) {
return getJSON(sheet, row, column);
}
return getString(sheet, row, column);
}
public static final String getString(final HSSFSheet sheet, final int row,
final int column) {
try {
HSSFRow c = sheet.getRow(row);
if (c == null)
return "";
HSSFCell v = c.getCell(column);
if (v == null)
return "";
int cellType = v.getCellType();
if (cellType == HSSFCell.CELL_TYPE_NUMERIC) {
return "" + v.getNumericCellValue();
} else if (cellType == HSSFCell.CELL_TYPE_BLANK) {
return "";
} else if (cellType == HSSFCell.CELL_TYPE_STRING) {
return v.getStringCellValue().trim();
} else if (cellType == HSSFCell.CELL_TYPE_BOOLEAN) {
return "" + v.getBooleanCellValue();
} else if (cellType == HSSFCell.CELL_TYPE_FORMULA) {
String result = "";
try {
result = "" + v.getStringCellValue().trim();
} catch (Exception e) {
result = "" + v.getNumericCellValue();
}
return result;
}
return v.getStringCellValue().trim();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static final String getComment(final HSSFSheet sheet, final int row,
final int column) {
try {
HSSFRow c = sheet.getRow(row);
if (c == null)
return "";
HSSFCell v = c.getCell(column);
if (v == null)
return "";
HSSFComment comment = v.getCellComment();
if (comment == null)
return "";
HSSFRichTextString rich = comment.getString();
if (rich == null)
return "";
return rich.getString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static int getInt(final HSSFSheet sheet, final int row,
final int column) {
try {
double v = getDouble(sheet, row, column);
return (int) v;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static long getLong(final HSSFSheet sheet, final int row,
final int column) {
try {
double v = getDouble(sheet, row, column);
return (long) v;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static double getDouble(final HSSFSheet sheet, final int row,
final int column) {
try {
String v = getString(sheet, row, column);
return NumEx.stringToDouble(v, 0);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static boolean getBoolean(final HSSFSheet sheet, final int row,
final int column) {
return getBool(sheet, row, column);
}
public static boolean getBool(final HSSFSheet sheet, final int row,
final int column) {
try {
String v = getString(sheet, row, column);
return v.toLowerCase().equals("true");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static final Object getJSON(final HSSFSheet sheet, final int row,
final int column) {
try {
String str = getString(sheet, row, column);
return MyJson.parse(str);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static final <T> T getKey(Map map) {
if (map == null || map.isEmpty())
return null;
Entry<Object, Object> E = ((Map<Object, Object>) map).entrySet()
.iterator().next();
return (T) E.getKey();
}
public static final <T> T getValue(Map map) {
if (map == null || map.isEmpty())
return null;
Entry<Object, Object> E = ((Map<Object, Object>) map).entrySet()
.iterator().next();
return (T) E.getValue();
}
public static void main(String[] args) throws Exception {
String f = "Clash of Clans 3.25 Revision.xlsx";
FileInputStream stream = new FileInputStream(f);
HSSFWorkbook wb = openWorkbook(stream);
HSSFSheet[] sheets = sheets(wb);
String[][] d = readAll2D(sheets[0]);
System.out.println(toString(d));
stream.close();
System.exit(1);
}
public static String toString(String[][] str) {
StringBuffer sb = StringBufPool.borrowObject();
for (String[] ss : str) {
for (String s : ss) {
sb.append(s).append(", ");
}
StrEx.removeRight(sb, 2);
sb.append("\r\n");
}
String r2 = sb.toString();
StringBufPool.returnObject(sb);
return r2;
}
}
|
package backjoon.bfsdfs;
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
// row, col 인덱스를 저장하는 클래스
class Location{
int row, col;
public Location(int row, int col) {this.row = row; this.col = col;}
}
public class Backjoon2178 {
static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static int arr[][];
static int isVisit[][];
static int n, m;
public static void main(String[] args) throws IOException {
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new int[n + 1][m + 1];
isVisit = new int[n + 1][m + 1];
// 입력 값을 배열에 초기화
for(int i = 1; i <= n; i++){
String input = br.readLine();
for(int j = 1; j <= m; j++) {
arr[i][j] = input.charAt(j - 1) - '0';
}
}
bfs();
}
// bfs method
public static void bfs(){
Queue<Location> queue = new LinkedList<>();
// 큐에 시작점을 추가한다..
queue.add(new Location(1,1));
// 상하좌우 칸을 표현하는데 사용할 배열
int[] xArr = {-1, 0, 1, 0};
int[] yArr = {0, 1, 0, -1};
// 추가한 노드 방문처리
isVisit[1][1] = 1;
while(!queue.isEmpty()){
// 큐에서 노드를 poll
Location location = queue.poll();
int row = location.row;
int col = location.col;
// 상하좌우 4방향 노드에 대한 작업
for(int i = 0 ; i < 4; i++){
int x = row + xArr[i];
int y = col + yArr[i];
if(checkLocation(x, y)){
// 큐에 인접 노드 추가
queue.add(new Location(x, y));
// 추가한 노드까지의 거리 = 현재 노드까지의 거리 + 1
isVisit[x][y] = isVisit[row][col] + 1;
}
}
}
System.out.println(isVisit[n][m]);
}
public static boolean checkLocation(int row, int col){
// 노드가 범위 밖인 경우
if(row < 1 || row > n || col < 1 || col > m) return false;
// 이미 방문한 노드인 경우
if(isVisit[row][col] != 0 || arr[row][col] == 0) return false;
return true;
}
}
|
package jp.co.disney.spplogin.controller;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import java.net.URI;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import jp.co.disney.spplogin.Application;
import jp.co.disney.spplogin.service.CoreWebApiService;
import jp.co.disney.spplogin.web.LoginController;
import jp.co.disney.spplogin.web.model.Guest;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class LoginControllerTest {
private static final String USER_AGENT = "Mozilla /5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B5110e Safari/601.1";
private static final String DSPP = "m3eK3TpVRrFhKgx92Kn9TlEgdpU6uHA2LdCUbU/tMLA=";
@Rule
public final MockitoRule rule = MockitoJUnit.rule();
private MockMvc mockMvc;
@Autowired
private Guest guest;
@Autowired
private MockHttpSession mockHttpSession;
@Autowired
private WebApplicationContext wac;
@Mock
@Autowired
private CoreWebApiService coreWebApiService;
@InjectMocks
@Autowired
private LoginController controller;
@Before
public void setUp() {
//this.mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
//mockHttpSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());
}
@Test
public void ログインフォーム表示() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.get("/Login")
.param("dspp", DSPP)
.param("service_name", "%E3%83%87%E3%82%A3%E3%82%BA%E3%83%8B%E3%83%BC%E3%82%B7%E3%82%A7%E3%82%A2")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(view().name(is("login/login")));
assertThat(guest.getServiceName(), is("ディズニーシェア"));
assertThat(guest.getDspp(), is(DSPP));
}
@Test
public void ログイン_login_or_registerパラメータが未設定() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("memberNameOrEmailAddr", "")
.param("password", "pass"))
//.andDo(MockMvcResultHandlers.print())
.andExpect(status().is4xxClientError());
}
@Test
public void ログイン_バリデーションエラー_必須項目未入力() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "")
.param("password", ""))
//.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrorCode("loginForm", "memberNameOrEmailAddr", "NotBlank"))
.andExpect(model().attributeHasFieldErrorCode("loginForm", "password", "NotBlank"))
.andExpect(model().attribute("hasErrorForLogin", is(true)));
}
@Test
public void ログイン_バリデーションエラー_メンバー名文字数上限オーバー() throws Exception {
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
.param("password", "pass"))
//.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrorCode("loginForm", "memberNameOrEmailAddr", "Size"))
.andExpect(model().attribute("hasErrorForLogin", is(true)));
}
@Test
public void SPP3会員ログイン成功() throws Exception {
ログインフォーム表示();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI("http://dev2.ssopen.disney.co.jp/auidauth/SessionKeyInfoUpd/?access_token=QrS8-2zCE_2ZUhvDlA3_i7RPGCopMpEr9_XgvX9mi-_5brRKk-VUR5wrSeIHqDweJ70woENHNICiXWrMv0v9Oa4YQcLZmqCnDS57fqLw35XXfUk1DlEficvDNyRPRU9QItmj-NlKiZjNsKydaJiRKj8LGHuhyTWUXhx-QbASHVD-aMl1f9l0ifAVlqLkpRUCGDMhvd701MOsIENokLBCQ1YnTGq39V3QWENSSrRX4U_3qLfxespDqoXkRnHzX3qZlvIkEIx52UytUY2E-JCEus3okBcXyrjfLCv1KHZldwevQJteCaaxR1CW3BovrYKnmzOJP2aPezkBLQuVkPt_JQ&did_token=eyJhY2Nlc3NfdG9rZW4iOiJpS2R0aTBKMERDcy02UmpMaGpzOW9RIiwiY2xpZW50SWQiOiJXREktSlAuSkEuU1BQLkdDLVNUQUdFIiwicmVmcmVzaF90b2tlbiI6IlV1akNRWldXTjR6Yzh4QUVKcFVWQ2ciLCJzd2lkIjoiNDlFMkY1MUUtQ0ExQS00RDNCLTkyQUMtQUM1MEFEQzIwNTE3IiwidHRsIjo3MjAwfQ&id_token=eyJhbGciOiJSUzI1NiIsICJ0eXAiOiJKV1QifQ.eyJhcHAiOm51bGwsImF0X2hhc2giOiJRclM4LTJ6Q0VfMlpVaHZEIiwiYXVkIjoiZHNoYXJfYUw3Zm9SMnlFbiIsImJkIjpudWxsLCJjYXJyaWVyIjpudWxsLCJkdmlkIjpudWxsLCJleHAiOjE0NjU5ODAwNDIsImlhdCI6MTQ2Mjk1NjA0MiwiaWNjaWQiOm51bGwsImltZWkiOm51bGwsImlzcyI6Imh0dHBzOi8vc3NvcGVuLmRpc25leS5jby5qcC8iLCJtb2RlbCI6ImlQaG9uZSIsIm5vbmNlIjoibi0wUzZfV3pBMk1qIiwib3BlIjowLCJvcyI6Ik9TIDlfMSIsInNwcGlkIjoiMDI0MDAwMDAyIiwic3VpZCI6bnVsbCwic3dpZCI6IjQ5RTJGNTFFLUNBMUEtNEQzQi05MkFDLUFDNTBBREMyMDUxNyIsInVzZXJfaWQiOiIwMjQwMDAwMDIiLCJ1dWlkIjpudWxsfQ.UJm5UEasRLKfnW6Ew5iBBtlVyW2FaDm11YCoKsF45mieqRBYA5EIJJPX2V-ErZQVXE8DLrGXKdr4YQJIqlTJZA&description=eyJlbWFpbF9hZGRyZXNzX2V4aXN0IjpmYWxzZSwiaXNfYm91bmNlZCI6ZmFsc2UsImlzX2luY29tcGxldGUiOmZhbHNlLCJpc19teW1lbnVfaW1vZGVfbGVmdCI6ZmFsc2UsImlzX215bWVudV9sZWZ0IjpmYWxzZSwibG9naW4iOiJzcHAzIiwibG9naW5fc3RhdHVzIjoiTUFSS0VUSU5HX1JFUVVJUkVEX0ZPQiJ9&state=m3eK3TpVRrFhKgx92Kn9TlEgdpU6uHA2LdCUbU%2FtMLA%3D&token_type=Bearer"));
HttpStatus status = HttpStatus.FOUND;
ResponseEntity<String> response = new ResponseEntity<>(null, headers, status);
Mockito.when(coreWebApiService.authorize("test@gmail.com", "123456", USER_AGENT, DSPP)).thenReturn(response);
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "test@gmail.com")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isFound());
}
@Test
public void ログイン失敗_メンバー名が正しくない() throws Exception {
ログインフォーム表示();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI("http://dev2.ssopen.disney.co.jp/auidauth/SessionKeyInfoUpd/?error_description=010667&state=m3eK3TpVRrFhKgx92Kn9TlEgdpU6uHA2LdCUbU%2FtMLA%3D&error=invalid_request"));
HttpStatus status = HttpStatus.UNAUTHORIZED;
ResponseEntity<String> response = new ResponseEntity<>(null, headers, status);
Mockito.when(coreWebApiService.authorize("test@gmail.com", "123456", USER_AGENT, DSPP)).thenReturn(response);
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "test@gmail.com")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(view().name(is("login/login")))
.andExpect(model().attribute("apiLoginFailed", is(true)));
}
@Test
public void ログイン失敗_パスワードが正しくない() throws Exception {
ログインフォーム表示();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI("http://dev2.ssopen.disney.co.jp/auidauth/SessionKeyInfoUpd/?error_description=010101&state=m3eK3TpVRrFhKgx92Kn9TlEgdpU6uHA2LdCUbU%2FtMLA%3D&error=invalid_request"));
HttpStatus status = HttpStatus.UNAUTHORIZED;
ResponseEntity<String> response = new ResponseEntity<>(null, headers, status);
Mockito.when(coreWebApiService.authorize("test@gmail.com", "123456", USER_AGENT, DSPP)).thenReturn(response);
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "test@gmail.com")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isOk())
.andExpect(view().name(is("login/login")))
.andExpect(model().attribute("apiLoginFailed", is(true)));
}
@Test
public void ログイン失敗_アカウント状態不正_MASE() throws Exception {
ログインフォーム表示();
HttpHeaders headers = new HttpHeaders();
headers.setLocation(new URI("http://dev2.ssopen.disney.co.jp/auidauth/SessionKeyInfoUpd/?error_description=010102&state=m3eK3TpVRrFhKgx92Kn9TlEgdpU6uHA2LdCUbU%2FtMLA%3D&error=invalid_request"));
HttpStatus status = HttpStatus.BAD_REQUEST;
ResponseEntity<String> response = new ResponseEntity<>(null, headers, status);
Mockito.when(coreWebApiService.authorize("test@gmail.com", "123456", USER_AGENT, DSPP)).thenReturn(response);
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.header("User-Agent", USER_AGENT)
.param("login", "")
.param("memberNameOrEmailAddr", "test@gmail.com")
.param("password", "123456")
.session(mockHttpSession))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/OneidStatus"));
}
@Test
public void はじめて登録される方はこちら_正常系() throws Exception {
ログインフォーム表示();
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.param("register", "")
.param("birthdayYear", "1975")
.param("birthdayMonth", "12")
.param("birthdayDay", "25")
.session(mockHttpSession))
.andExpect(status().isFound())
.andExpect(redirectedUrl("/Login/emptymail"));
}
@Test
public void はじめて登録される方はこちら_バリデーションエラー_誕生日日付不正() throws Exception {
ログインフォーム表示();
this.mockMvc.perform(MockMvcRequestBuilders.post("/Login")
.param("register", "")
.param("birthdayYear", "1975")
.param("birthdayMonth", "2")
.param("birthdayDay", "29")
.session(mockHttpSession))
//.andDo(MockMvcResultHandlers.print())
.andExpect(status().isOk())
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrorCode("emptyMailForm", "validDate", "AssertTrue"))
.andExpect(model().attribute("hasErrorForRegister", is(true)))
.andExpect(view().name(is("login/login")));
}
}
|
package rainbowsort;
import java.util.Arrays;
public class Solutiontest {
public static void main(String []args){
Solution s = new Solution();
int [] array0 = {};
int [] array1 = {0};
int [] array2 = {1,0};
int [] array3 = {1,-1,0,1};
array0 = s.rainbowsort(array0);
array1 = s.rainbowsort(array1);
array2 = s.rainbowsort(array2);
array3 = s.rainbowsort(array3);
System.out.println(Arrays.toString(array0));
System.out.println(Arrays.toString(array1));
System.out.println(Arrays.toString(array2));
System.out.println(Arrays.toString(array3));
}
}
|
/**
* Copyright 2015-2016 the original author or authors.
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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 sample.mybatis;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import sample.mybatis.tx.service.TxService;
import javax.annotation.Resource;
@MapperScan("sample.mybatis.tx.mapper")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class TxApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(TxApplication.class, args);
}
@Resource
private TxService txService;
@Override
public void run(String... args) throws Exception {
new Thread(new Runnable() {
@Override
public void run() {
// txService.txWithCode();
// txService.txWithAnnotation();
}
}).start();
}
}
|
package com.tfjybj.integral.provider;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author quinn
* @version 创建时间:2018/10/10 16:53
*/
public abstract class TestBase {
protected static final Logger logger = LoggerFactory.getLogger(TestBase.class);
@Rule
public TestExecTimeWatcher watcher = new TestExecTimeWatcher();
public void logDebug(Object obj) {
if (logger.isDebugEnabled()) {
logger.debug(GlobalSetting.toDisplay(obj));
}
}
public void logDebug(String msg, Object obj) {
if (logger.isDebugEnabled()) {
logger.debug(msg);
logger.debug(GlobalSetting.toDisplay(obj));
}
}
public void logInfo(Object obj) {
logger.info(GlobalSetting.toDisplay(obj));
}
public void logInfo(String msg, Object obj) {
logger.info(msg);
logger.info(GlobalSetting.toDisplay(obj));
}
public void logWarn(Object obj) {
logger.warn(GlobalSetting.toDisplay(obj));
}
public void logWarn(String msg, Object obj) {
logger.warn(msg);
logger.warn(GlobalSetting.toDisplay(obj));
}
public void logInfoRaw(Object obj) {
logger.info(GlobalSetting.toDisplay(obj));
}
public void logWarnRaw(Object obj) {
logger.warn(GlobalSetting.toDisplay(obj));
}
public void logError(String msg, Exception ex) {
logger.error(msg, ex);
}
/**
* 此方法只会在运行所有单元测试前执行一次,
* 通常用來获取数据库连接,Spring管理的Bean等等
*/
//@BeforeClass
public static void placeholderBeforeClass() {
}
/**
* 此方法运行每个单元测试前都会执行,
* 通常用来准备数据或获取单元测试依赖的数据或对象
*/
// @Before
public void placeHolderSetUp() {
}
/**
* 请注意注解上的experced,使用该参数代表可以认为
* 这个单元测试方法会抛出Exception的异常,若然没有视为不通过
*/
// @Test(expected = Exception.class)
public void placeHolderTestExpectedException() {
// throw new Exception("placeholder");
}
/**
* 请注意注解上的timeout,使用该参数代表该单元测试需要
* 在1000毫秒内完成,否则视为不通过,可以用做简单的性能测试
*/
@Test(timeout = 1000)
public void placeHolderTestTimeout() {
}
/**
* 此方法运行每个单元测试后都会执行,
* 主要用来和setUp对应,清理获取的资源
*/
// @After
public void placeHolderTearDown() {
}
/**
* 此方法会在运行所有单元测试后执行一次,
* 通常用来释放资源,例如数据库连接,IO流等等
*/
// @AfterClass
public static void placeHolderDestroy() {
}
}
|
package com.github.swapnil.LabFolderProject.model;
/**
*
* The model for LabNotebook persisted in DB
*
* @author Swap
*
*/
public class LabNotebook {
private Long id;
private String name;
private String data;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
|
package com.hyty.tree.treejiegou.controller;
import com.alibaba.fastjson.JSON;
import com.hyty.tree.treejiegou.entity.Personnel;
import com.hyty.tree.treejiegou.service.PsersonnelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by czy on 2019/3/25.
*/
@RestController
@RequestMapping(value = "/per")
public class PersonnelController {
@Autowired
PsersonnelService psersonnelService;
/**
* 保存员工实体
*
* @param personnel 员工实体
* @return JSON
*/
@RequestMapping(value = "/save", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public Object savePersonnel(Personnel personnel) {
Map<String, Object> resultMap = new HashMap<>();
try {
psersonnelService.savePesersonnel(personnel);
resultMap.put("result", "true");
resultMap.put("msg", "保存成功");
return JSON.toJSONString(resultMap);
} catch (Exception e) {
e.printStackTrace();
resultMap.put("result", "false");
resultMap.put("msg", "保存失败");
return JSON.toJSONString(resultMap);
}
}
/**
* 查询员工组织结构
*
* @param id 员工ID
* @return JSON
*/
@RequestMapping(value = "/select", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
public Object selectPersonnel(String id) {
Map<String, Object> resultMap = new HashMap<>();
try {
List<String> list = psersonnelService.selectPesersonnle(id);
resultMap.put("result", "true");
resultMap.put("msg", "查询成功");
resultMap.put("value", list);
return JSON.toJSONString(resultMap);
} catch (Exception e) {
e.printStackTrace();
resultMap.put("result", "false");
resultMap.put("msg", "保存失败");
return JSON.toJSONString(resultMap);
}
}
}
|
package app;
import java.util.Scanner;
public class Start {
QuestionManager questionManager = new QuestionManager();
public void startApp () throws InterruptedException {
Scanner scanner = new Scanner(System.in);
Player player1 = new Player();
Player player2 = new Player();
System.out.println("---------WELCOME---------");
System.out.println("[1] PLAY");
System.out.println("[2] QUIZ OPTIONS");
System.out.println("[3] EXIT PROGRAM");
String input = scanner.nextLine();
switch (input) {
case "1":
player1 = Player.createPlayer("1");
player2 = Player.createPlayer("2");
QuizManager.startTheQuiz(player1, player2);
Thread.sleep(1000);
player1.addPlayed_Games();
player2.addPlayed_Games();
QuizManager.comparePoints(player1, player2);
player1.showStats();
player2.showStats();
System.out.println();
playAgain(player1, player2);
break;
case "2":
System.out.println("[1] ADD QUESTION");
System.out.println("[2] DELETE QUESTION");
System.out.println("[3] LIST ALL QUESTIONS ");
int inputNumber = scanner.nextInt();
if (inputNumber == 1) {
questionManager.load();
questionManager.addQuestion();
questionManager.save();
startApp();
}
if (inputNumber == 2) {
QuestionManager.deleteQuestion();
startApp();
break;
}
if (inputNumber == 3) {
questionManager.load();
questionManager.printAllQuestions();
startApp();
break;
}
case "3":
System.exit(0);
break;
default:
System.out.println("Invalid input, try again");
}
}
public void playAgain (Player player1, Player player2) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
System.out.println("-------------------------");
System.out.println("[1] PLAY AGAIN");
System.out.println("[2] QUIZ OPTIONS");
System.out.println("[3] RETURN TO MAIN MENU");
System.out.println("[4] EXIT PROGRAM");
String input = scanner.nextLine();
switch (input) {
case "1":
QuizManager.startTheQuiz(player1, player2);
Thread.sleep(1000);
player1.addPlayed_Games();
player2.addPlayed_Games();
QuizManager.comparePoints(player1, player2);
player1.showStats();
player2.showStats();
System.out.println();
playAgain(player1, player2);
break;
case "2":
System.out.println("[1] ADD QUESTION");
System.out.println("[2] DELETE QUESTION");
System.out.println("[3] LIST ALL QUESTIONS ");
int inputNumber = scanner.nextInt();
if (inputNumber == 1) {
questionManager.load();
questionManager.addQuestion();
questionManager.save();
playAgain(player1, player2);
}
if (inputNumber == 2) {
QuestionManager.deleteQuestion();
playAgain(player1, player2);
break;
}
if (inputNumber == 3) {
questionManager.load();
questionManager.printAllQuestions();
playAgain(player1, player2);
break;
}
case "3":
startApp();
break;
case "4":
System.exit(0);
break;
default:
System.out.println("Invalid input, try again");
}
}
}
|
package com.example.demo.service;
import com.example.demo.entity.PageQuery;
import com.example.demo.entity.Project;
import java.io.IOException;
import java.util.List;
import org.apache.lucene.queryparser.classic.ParseException;
public interface ILuceneService {
public void synProjectCreateIndex() throws IOException;
public PageQuery<Project> searchProject(PageQuery<Project> pageQuery) throws IOException, ParseException;
public List<Project> searchByName(String name) throws IOException, ParseException;
}
|
package com.example.hp.bookshop;
/**
* Created by HP on 7/29/2017.
*/
public class Books {
public String bookID;
public String bookAuthor;
public String bookRating;
public Double ratingTwo;
Books(String id,String author,String rating,Double ratingOne)
{
bookRating=rating;
bookAuthor=author;
bookID=id;
ratingTwo=ratingOne;
}
public String getBookID()
{
return bookID;
}
public String getBookAuthor()
{
return bookAuthor;
}
public String getBookRating()
{
return bookRating;
}
public Double getRatingTwo()
{
return ratingTwo;
}
}
|
package com.ibm.ive.tools.japt;
/**
* Thrown when a class, method or field identifier is invalid.
* @author sfoley
*
*/
public class InvalidIdentifierException extends Exception {
Identifier identifier;
public InvalidIdentifierException(Identifier identifier) {
this.identifier = identifier;
}
public InvalidIdentifierException(Identifier identifier, String detailMessage) {
super(detailMessage);
this.identifier = identifier;
}
public Identifier getIdentifier() {
return identifier;
}
}
|
package category.bitOperation;
/***
* example: 1100 1110 0001 0101 1010 0100 1011 0100
* result : 1100 1101 0010 1010 0101 1000 0111 1000
*
* mask : 1010 1010 1010 1010 1010 1010 1010 1010
* = AAAA AAAA
* logic: build a new number with all odd bits and another number with all even bits
* example:
* odd: 1000 1010 0000 0000 1010 0000 1010 0000
* even: 0100 0100 0001 0101 0000 0100 0001 0100
*
* nodd: 0 1000 1010 0000 0000 1010 0000 1010 000
* neven: 100 0100 0001 0101 0000 0100 0001 0100 0
* then odd = odd >> 1, even = even << 1
* finally: result = odd | even
*
* @author Meng
*/
public class ReverseOddEven {
public static int reverse(int num){
int mask = 0xAAAAAAAA;
int odd = mask & num;
int even = (mask >> 1) & num;
return odd >> 1 | even << 1;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class bid extends a {
public LinkedList<arp> siQ = new LinkedList();
public boolean siR;
public boolean siS;
public boolean siT;
public boolean siU;
public boolean siV;
protected final int a(int i, Object... objArr) {
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
aVar.d(1, 8, this.siQ);
aVar.av(2, this.siR);
aVar.av(3, this.siS);
aVar.av(4, this.siT);
aVar.av(5, this.siU);
aVar.av(6, this.siV);
return 0;
} else if (i == 1) {
return (((((f.a.a.a.c(1, 8, this.siQ) + 0) + (f.a.a.b.b.a.ec(2) + 1)) + (f.a.a.b.b.a.ec(3) + 1)) + (f.a.a.b.b.a.ec(4) + 1)) + (f.a.a.b.b.a.ec(5) + 1)) + (f.a.a.b.b.a.ec(6) + 1);
} else {
byte[] bArr;
if (i == 2) {
bArr = (byte[]) objArr[0];
this.siQ.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (int a = a.a(aVar2); a > 0; a = a.a(aVar2)) {
if (!super.a(aVar2, this, a)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
bid bid = (bid) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
switch (intValue) {
case 1:
LinkedList IC = aVar3.IC(intValue);
int size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
arp arp = new arp();
f.a.a.a.a aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (boolean z = true; z; z = arp.a(aVar4, arp, a.a(aVar4))) {
}
bid.siQ.add(arp);
}
return 0;
case 2:
bid.siR = aVar3.cJQ();
return 0;
case 3:
bid.siS = aVar3.cJQ();
return 0;
case 4:
bid.siT = aVar3.cJQ();
return 0;
case 5:
bid.siU = aVar3.cJQ();
return 0;
case 6:
bid.siV = aVar3.cJQ();
return 0;
default:
return -1;
}
}
}
}
}
|
package com.apk.clima;
public class WeatherForecast {
private String list;
private String main;
private String temp;
private String tempMin;
private String tempMax;
private String weather;
private String icon;
private String dttxt;
public WeatherForecast() {
super();
}
public String getList() {
return list;
}
public void setList(String list) {
this.list = list;
}
public String getMain() {
return main;
}
public void setMain(String main) {
this.main = main;
}
public String getTemp() {
return temp;
}
public void setTemp(String temp) {
this.temp = temp;
}
public String getTempMin() {
return tempMin;
}
public void setTempMin(String tempMin) {
this.tempMin = tempMin;
}
public String getTempMax() {
return tempMax;
}
public void setTempMax(String tempMax) {
this.tempMax = tempMax;
}
public String getWeather() {
return weather;
}
public void setWeather(String weather) {
this.weather = weather;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getDttxt() {
return dttxt;
}
public void setDttxt(String dttxt) {
this.dttxt = dttxt;
}
}
|
package sample;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import model.*;
import view.BoardView;
public class Controller {
private Board board;
private BoardView boardView;
private boolean isGameOver;
private boolean play;
private Button button;
public Controller(final Board board, final BoardView boardView){
this.board = board;
this.boardView = boardView;
isGameOver = false;
play = false;
button = new Button("Rejouer");
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
board.commit();
boardView.reset();
isGameOver = false;
play = false;
}
});
}
public void directionPressed(String direction){
if (!isGameOver){
if (direction=="LEFT" || direction=="RIGHT") {
board.packIntoDirection(Board.Direction.valueOf(direction));
}
else if(direction=="UP"){
board.packIntoDirection(Board.Direction.TOP);
}
else if(direction=="DOWN"){
board.packIntoDirection(Board.Direction.BOTTOM);
}
else{
return;
}
isGameOver = board.commit();
}
if (isGameOver && !play){
boardView.displayGameOver(button);
play = true;
}
else if(!isGameOver){
boardView.update();
}
}
}
|
package com.mega.mvc06;
public class ArrayError {
public static void main(String[] args) throws IndexOutOfBoundsException{
try {
int[] num = {1, 2, 3};
num[3] = 4;
} catch (IndexOutOfBoundsException e) {
System.out.println("인덱스 에러");
} catch (Exception e) {
System.out.println("다른 에러 발생");
} finally {
System.out.println("배열에 문제가 사라지게 해결했어요");
}
// 1 배열의 IndexOutOfBoundsException이면 "인덱스 에러!"라고 출력
// 2 다른 에러이면 "다른 에러 발생"이라고 출력
// 3 에러가 발생하든 안하든 상관없이.."배열에 문제가 사라지게 해결했어요"를 출력
}
}
|
package com.sunteam.library.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sunteam.common.menu.MenuActivity;
import com.sunteam.common.menu.MenuConstant;
import com.sunteam.common.menu.menulistadapter.ShowView;
import com.sunteam.common.menu.menuview.OnMenuKeyListener;
import com.sunteam.common.utils.Tools;
import com.sunteam.library.R;
import com.sunteam.library.asynctask.GetAudioChapterAsyncTask;
import com.sunteam.library.asynctask.GetEbookAsyncTask;
import com.sunteam.library.asynctask.GetEbookChapterAsyncTask;
import com.sunteam.library.asynctask.GetVideoChapterAsyncTask;
import com.sunteam.library.entity.EbookNodeEntity;
import com.sunteam.library.utils.LibraryConstant;
/**
* @Destryption 资源列表;电子书、有声书、口述影像共用一个界面
* @Author Jerry
* @Date 2017-2-4 下午3:47:01
* @Note
*/
public class ResourceList extends MenuActivity implements OnMenuKeyListener, ShowView {
private String categoryCode; //分类编码
private int dataType = 0; // 数据类别:电子书、有声书、口述影像
private int bookCount = 0; // 当前类资源总数,在分页加载时,需要使用该值
private String fatherPath; //父目录路径
private ArrayList<EbookNodeEntity> mEbookNodeEntityList;
private Tools mTools;
public void onCreate(Bundle savedInstanceState) {
initView();
super.onCreate(savedInstanceState);
mMenuView.setShowView(this);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
}
@Override
protected void onResume() {
super.onResume();
mMenuView.setMenuKeyListener(this);
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Activity.RESULT_OK != resultCode || null == data) { // 在子菜单中回传的标志
return;
}
}
@Override
public void setResultCode(int resultCode, int selectItem, String menuItem) {
String dbCode;
String sysId;
String identifier;
dbCode = mEbookNodeEntityList.get(selectItem).dbCode;
sysId = mEbookNodeEntityList.get(selectItem).sysId;
identifier = mEbookNodeEntityList.get(selectItem).identifier;
switch(dataType){
case LibraryConstant.LIBRARY_DATATYPE_EBOOK:
new GetEbookChapterAsyncTask(this, fatherPath, menuItem).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dbCode, sysId, mTitle, identifier, categoryCode );
break;
case LibraryConstant.LIBRARY_DATATYPE_AUDIO:
new GetAudioChapterAsyncTask(this, fatherPath, menuItem).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dbCode, sysId, mTitle, identifier, categoryCode);
break;
case LibraryConstant.LIBRARY_DATATYPE_VIDEO:
new GetVideoChapterAsyncTask(this, fatherPath, menuItem).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dbCode, sysId, mTitle, identifier, categoryCode);
break;
default:
break;
}
}
private void initView() {
Intent intent = getIntent();
mTitle = intent.getStringExtra(MenuConstant.INTENT_KEY_TITLE);
//mEbookNodeEntityList = (ArrayList<EbookNodeEntity>) intent.getSerializableExtra(MenuConstant.INTENT_KEY_LIST);
mEbookNodeEntityList = GetEbookAsyncTask.mEbookNodeEntityList;
dataType = intent.getIntExtra(LibraryConstant.INTENT_KEY_TYPE, 0);
mMenuList = getListFromEbookNodeEntity(mEbookNodeEntityList);
bookCount = mMenuList.size();
bookCount = intent.getIntExtra(LibraryConstant.INTENT_KEY_BOOKCOUNT, bookCount);
fatherPath = intent.getStringExtra(LibraryConstant.INTENT_KEY_FATHER_PATH);
categoryCode = intent.getStringExtra(LibraryConstant.INTENT_KEY_CATEGORY_CODE);
mTools = new Tools(this);
}
private ArrayList<String> getListFromEbookNodeEntity(ArrayList<EbookNodeEntity> listSrc) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < listSrc.size(); i++) {
list.add(listSrc.get(i).title);
}
return list;
}
@Override
public void onMenuKeyCompleted(int selectItem, String menuItem) {
Intent intent = new Intent();
// String title = getResources().getString(R.string.common_functionmenu); // 功能菜单
// String[] list = getResources().getStringArray(R.array.library_resource_function_menu_list);
// intent.putExtra(MenuConstant.INTENT_KEY_TITLE, title); // 菜单名称
// intent.putExtra(MenuConstant.INTENT_KEY_LIST, list); // 菜单列表
intent.putExtra(MenuConstant.INTENT_KEY_TITLE, mTitle); // 分类名称
intent.putExtra(LibraryConstant.INTENT_KEY_RESOURCE, menuItem);
intent.putExtra(LibraryConstant.INTENT_KEY_TYPE, dataType); // 数据类别:电子书、有声书、口述影像
intent.putExtra(LibraryConstant.INTENT_KEY_FATHER_PATH, fatherPath); // 父目录
intent.putExtra(LibraryConstant.INTENT_KEY_CATEGORY_CODE, categoryCode); //分类编码
intent.putExtra(LibraryConstant.INTENT_KEY_DBCODE, mEbookNodeEntityList.get(selectItem).dbCode); //数据编码
switch( dataType )
{
case LibraryConstant.LIBRARY_DATATYPE_EBOOK: //电子图书
intent.putExtra(LibraryConstant.INTENT_KEY_SYSID, mEbookNodeEntityList.get(selectItem).identifier); //书本d
break;
default:
intent.putExtra(LibraryConstant.INTENT_KEY_SYSID, mEbookNodeEntityList.get(selectItem).sysId); //系统id
break;
}
intent.setClass(this, ResourceFunctionMenu.class);
// 如果希望启动另一个Activity,并且希望有返回值,则需要使用startActivityForResult这个方法,
// 第一个参数是Intent对象,第二个参数是一个requestCode值,如果有多个按钮都要启动Activity,则requestCode标志着每个按钮所启动的Activity
startActivityForResult(intent, selectItem);
}
@Override
public View getView(Context context, final int position, View convertView, ViewGroup parent) {
ViewHolder vh = null;
if (null == convertView) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.library_menu_item, null);
vh.tvIcon = (TextView) convertView.findViewById(R.id.library_menu_item_icon);
vh.tvMenu = (TextView) convertView.findViewById(R.id.library_menu_item_childs);
// vh.tvMenu.setOnClickListener(this);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
vh.tvMenu.setTag(String.valueOf(position));
int fontSize = mTools.getFontSize();
vh.tvIcon.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel()); // 图标占用一个汉字宽度,随汉字字体大小而伸缩
vh.tvIcon.setHeight(mTools.convertSpToPixel(fontSize));
vh.tvIcon.setBackgroundResource(R.drawable.text);
vh.tvMenu.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTools.getFontPixel());
vh.tvMenu.setHeight(mTools.convertSpToPixel(fontSize));
if (getSelectItem() == position) {
convertView.setBackgroundColor(mTools.getHighlightColor());
vh.tvMenu.setSelected(true);
} else {
convertView.setBackgroundColor(mTools.getBackgroundColor());
vh.tvMenu.setSelected(false);
}
if (!TextUtils.isEmpty((CharSequence) mMenuList.get(position))) {
vh.tvMenu.setText((CharSequence) mMenuList.get(position));
} else {
vh.tvMenu.setText("");
}
vh.tvMenu.setTextColor(mTools.getFontColor());
return convertView;
}
private class ViewHolder {
TextView tvIcon = null; // 图标
TextView tvMenu = null; // 菜单项
}
}
|
package Lab02.Zad2;
public interface Codec {
void codec();
}
|
package com.mes.cep.meta.materialModel;
/**
* @author Stephen·Wen
* @email 872003894@qq.com
* @date 2017年5月2日
* @Chinesename 材料批次属性
*/
public class MaterialLotProperty {
}
|
package subjects.medium;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @description: 给定一个可包含重复数字的序列,返回所有不重复的全排列。
* <p>
* 示例:
* <p>
* 输入: [1,1,2]
* 输出:
* [
* [1,1,2],
* [1,2,1],
* [2,1,1]
* ]
* <p>
* <p>
* (i > 0 && nums[i] == nums[i - 1] && !vis[i - 1]) 萌新疑问,为什么最后还要判断前一个数字没有访问过?
* 我的理解是,如果 nums[i]和nums[i-1]相等,就在所有的全排列里,固定两个相等的数相对的访问顺序,每次必须先访问nums[i-1]再nums[i],这样就不会产生重复的。 比如【1 1 2 3】, 1的下标分别是0和1, 那么【1 2 1 3】 和【1 2 3 1】两个排列里的两个【1 1】,必须是按nums[0],nums[1]这样的顺序。 如果你把!vis[i - 1] 改成 vis[i - 1] 结果应该也是一样的, 不过因为回溯多,运行时间会久一点
* @author: dsy
* @date: 2020/9/18 18:48
*/
public class M47 {
static boolean[] vis;
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> perm = new ArrayList<Integer>();
vis = new boolean[nums.length];
Arrays.sort(nums);
backtrack(nums, ans, 0, perm);
return ans;
}
public static void backtrack(int[] nums, List<List<Integer>> ans, int idx, List<Integer> perm) {
if (idx == nums.length) {
ans.add(new ArrayList<Integer>(perm));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (vis[i] || (i > 0 && nums[i] == nums[i - 1] && !vis[i - 1])) {
continue;
}
perm.add(nums[i]);
vis[i] = true;
backtrack(nums, ans, idx + 1, perm);
vis[i] = false;
perm.remove(idx);
}
}
public static void main(String[] args) {
int[] nums = {2, 7, 11};
System.out.println(permuteUnique(nums));
}
}
|
public class Programmer extends Employee{
Programmer(String name){
super(name);
}
}
|
package com.verbovskiy.finalproject.controller;
import com.verbovskiy.finalproject.controller.command.PageType;
import com.verbovskiy.finalproject.controller.command.RequestParameter;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
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.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
/**
* The {@code UploadController} class represents file upload controller.
*
* @author Verbovskiy Sergei
* @version 1.0
*/
@WebServlet(urlPatterns = "/upload_controller", name = "uploadController")
@MultipartConfig(maxFileSize = 1024 * 1024 * 10, maxRequestSize = 1024 * 1024 * 50)
public class UploadController extends HttpServlet {
private static final String UPLOAD_LOCATION = "upload.location";
private static final String EXPANSION_START = ".";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String applicationFileDirectory = request.getServletContext().getInitParameter(UPLOAD_LOCATION);
Path path = Paths.get(applicationFileDirectory);
StringBuilder folderBuilder = new StringBuilder();
folderBuilder.append(applicationFileDirectory);
folderBuilder.append(File.separator);
Path fullFolderPath = Paths.get(folderBuilder.toString());
if (Files.notExists(path)) {
Files.createDirectory(path);
}
request.getParts().forEach(part -> {
try {
String fileName = part.getSubmittedFileName();
if (fileName.isEmpty()) {
request.setAttribute(RequestParameter.IS_IMAGE_SELECTED, false);
} else {
String randFilename = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(EXPANSION_START));
StringBuilder imagePathBuilder = new StringBuilder();
imagePathBuilder.append(fullFolderPath);
imagePathBuilder.append(File.separator);
imagePathBuilder.append(randFilename);
String imagePath = imagePathBuilder.toString();
part.write(imagePath);
request.setAttribute(RequestParameter.IS_IMAGE_LOADED, true);
HttpSession session = request.getSession();
session.setAttribute(RequestParameter.IMAGE_NAME, randFilename);
}
} catch (IOException e) {
request.setAttribute(RequestParameter.IS_IMAGE_LOADED, false);
}
});
request.getRequestDispatcher(PageType.ADD_CAR.getPath()).forward(request, response);
}
}
|
package cn.bs.zjzc.ui.view;
import cn.bs.zjzc.base.IBaseView;
/**
* Created by Ming on 2016/6/12.
*/
public interface IForgotPasswordView extends IBaseView {
void startCountDownTimer();
}
|
package la.foton.treinamento.dao;
import la.foton.treinamento.entities.Conta;
import javax.enterprise.inject.Default;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
@Default
//@TransactionManagement(value = TransactionManagementType.CONTAINER)//opcional
public class ContaDAOImpl implements ContaDAO {
@PersistenceContext
private EntityManager em;
@Override
public Integer geraNumero() {
TypedQuery<Integer> query = em.createQuery("select max(c.numero) from Conta c", Integer.class);
Integer numero = query.getSingleResult();
return numero != null ? numero + 1 : 1;
}
@Override
public void insere(Conta conta) {
em.persist(conta);
}
@Override
public Conta consultaPorNumero(int numero) {
return em.find(Conta.class, numero);
}
@Override
public void atualiza(Conta conta) {
em.merge(conta);
}
}
|
/*
* 版权声明 .
* 此文档的版权归通联支付网络服务有限公司所有
* Powered By [Allinpay-Boss-framework]
*/
package com.allinpay.its.boss.system.permission.service;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.allinpay.its.boss.framework.enums.EUserInfState;
import com.allinpay.its.boss.framework.utils.Page;
import com.allinpay.its.boss.framework.utils.SessionUtil;
import com.allinpay.its.boss.framework.utils.StringUtil;
import com.allinpay.its.boss.framework.utils.WebConstant;
import com.allinpay.its.boss.system.menu.service.FrameworkSysMenuServiceImpl;
import com.allinpay.its.boss.system.permission.dao.IFrameworkUserInfDao;
import com.allinpay.its.boss.system.permission.dao.impl.FrameworkUserInfDaoImpl;
import com.allinpay.its.boss.system.permission.model.FrameworkSysRole;
import com.allinpay.its.boss.system.permission.model.FrameworkUserInf;
import com.allinpay.its.boss.system.permission.model.FrameworkUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
@Service
//默认将类中的所有函数纳入事务管理.
@Transactional
public class FrameworkUserInfServiceImpl {
@Autowired
private IFrameworkUserInfDao frameworkUserInfDao;
@Resource
private FrameworkUserInfDaoImpl myBatisDao;
@Resource
private FrameworkSysRoleServiceImpl frameworkSysRoleService;
@Resource
private FrameworkUserRoleServiceImpl frameworkUserRoleService;
@Resource
private FrameworkSysMenuServiceImpl sysMenuService;
/**
* 新增
*
* @param POJO对象
* @return String
*/
public String add(FrameworkUserInf frameworkUserInf) {
// 保存申请信息
frameworkUserInf.setUserPassword(StringUtil.encodePassword(frameworkUserInf.getUserPassword()));
frameworkUserInf.setState(EUserInfState.NORMAL.getValue()+""); //操作员状态正常
frameworkUserInf.setRecUpdUsr("test");
frameworkUserInf.setRowCrtTs(new Date()); //创建时间
frameworkUserInf.setRecUpdTs(new Date()); //最后更新时间
myBatisDao.save(frameworkUserInf);
String[] roleIds = frameworkUserInf.getRoleIds();
//添加角色
if(roleIds!=null && roleIds.length>0){
for(String roleId : roleIds){
FrameworkUserRole urole = new FrameworkUserRole();
urole.setUserId(frameworkUserInf.getId());
urole.setSysRoleId(Long.valueOf(roleId));
urole.setState(WebConstant.DATA_EXIST);
urole.setCreateTime(new Date());
// urole.setCreateUserId(Long.parseLong(SessionUtil.getLoginInnerUserId()));
urole.setModifyTime(new Date());
// urole.setModifyUserId(Long.parseLong(SessionUtil.getLoginInnerUserId()));
// FrameworkSysRole role = frameworkSysRoleService.getFrameworkSysRoleByPk(Integer.parseInt(roleId));
//roleNames += role.getSysRoleName() + ",";
frameworkUserRoleService.add(urole);
}
}
return null;
}
/**
* 删除
*
* @param POJO对象
* @return String
*/
public String delete(int pk_id) {
myBatisDao.deleteById(pk_id);
return null;
}
/**
* 新增修改
* 有唯一主键,且主键自动生成不可编辑时
* @param POJO对象
* @return String
*/
// public String saveOrUpdate(FrameworkUserInf frameworkUserInf) {
//
// // 保存申请信息
// if(frameworkUserInf.getPk() != null)
// frameworkUserInfDao.update(frameworkUserInf);
// else
// frameworkUserInfDao.save(frameworkUserInf);
//
// return null;
// }
/**
* 新增修改
*
* @param POJO对象
* @return String
*/
public String update(FrameworkUserInf frameworkUserInf) {
// 修改申请信息
myBatisDao.update(frameworkUserInf);
//修改角色
String[] roleIds = frameworkUserInf.getRoleIds();
if(roleIds!=null && roleIds.length>0){
//先删除角色
frameworkUserRoleService.delUserRole(frameworkUserInf.getId());
for(String roleId : roleIds){
FrameworkUserRole urole = frameworkUserRoleService.findUserRole(frameworkUserInf.getId(), Long.valueOf(roleId));
if(urole==null || urole.getId()==null){
urole = new FrameworkUserRole();
}
urole.setUserId(frameworkUserInf.getId());
urole.setSysRoleId(Long.valueOf(roleId));
urole.setState(WebConstant.DATA_EXIST);
urole.setModifyTime(new Date());
urole.setModifyUserId(Long.parseLong("11"));
// SysRole role = bossUserRoleService.getGmacRoleById(Long.valueOf(roleId));
// roleNames += role.getSysRoleName() + ",";
if(urole==null || urole.getId()==null){
urole.setCreateTime(new Date());
urole.setCreateUserId(Long.parseLong("11"));
frameworkUserRoleService.add(urole);
}else{
frameworkUserRoleService.update(urole);
}
}
}
return null;
}
/**
* 分页查询
* @param POJO对象
* @param pageIndex 当前页页数
* @param pageSize 每页记录数
* @return Page
*/
public Page findFrameworkUserInfs(FrameworkUserInf frameworkUserInf,
int pageIndex,
int pageSize) {
return myBatisDao.pageBy(null, null, frameworkUserInf, pageIndex, pageSize);
}
/**
* 根据主键对象获取信息
*
* @param POJO对象
* @return FrameworkUserInf
*/
public List<FrameworkUserInf> getFrameworkUserInfListByObj(FrameworkUserInf frameworkUserInf) {
return frameworkUserInfDao.findListByObj(frameworkUserInf);
}
/**
* 根据主键获取信息
*
* @param POJO对象
* @return FrameworkUserInf
*/
public FrameworkUserInf getFrameworkUserInfByPk(int pk_Id) {
return frameworkUserInfDao.findByPKId(pk_Id);
}
/**
* 根据条件获取信息
*
* @param POJO对象
* @return FrameworkUserInf返回第一个符合条件的对象,适合条件能唯一定位记录的应用场景
*/
public List<FrameworkUserInf> getFrameworkUserInfListBySql(FrameworkUserInf frameworkUserInf) {
return frameworkUserInfDao.findListBySqlId("selectFrameworkUserInfs",frameworkUserInf);
}
public void toAddUserInf(Model model){
FrameworkSysRole sysRole = new FrameworkSysRole();
sysRole.setState(WebConstant.DATA_EXIST);
List<FrameworkSysRole> sysRoleList = frameworkSysRoleService.getFrameworkSysRoleListByObj(sysRole);
model.addAttribute("sysRoleList", sysRoleList);
}
public void initModifyUserInf(int pk_Id,Model springModel){
FrameworkUserInf frameworkUserInf = getFrameworkUserInfByPk(pk_Id);
FrameworkUserRole userRole = new FrameworkUserRole();
userRole.setState(WebConstant.DATA_EXIST);
userRole.setUserId(Long.parseLong(String.valueOf(pk_Id)));
//角色信息
List<FrameworkUserRole> listUserRole = frameworkUserRoleService.getFrameworkUserRoleListByObj(userRole);
StringBuffer userRoleBuffer = new StringBuffer();
for(FrameworkUserRole uRole : listUserRole){
userRoleBuffer.append(uRole.getSysRoleId()+",");
}
FrameworkSysRole sysRole = new FrameworkSysRole();
sysRole.setState(WebConstant.DATA_EXIST);
List<FrameworkSysRole> sysRoleList = frameworkSysRoleService.getFrameworkSysRoleListByObj(sysRole);
springModel.addAttribute("sysRoleList", sysRoleList);
springModel.addAttribute("userRoles",userRoleBuffer.toString());
springModel.addAttribute("infos",frameworkUserInf);
}
/**
* 功能:用户登陆信息查询. 参数:String userName,String password 返回值:FrameworkUserInf
* @param userName
* @param password
* @return
*/
public FrameworkUserInf queryUserInfoByCondition(String userName, String password) {
FrameworkUserInf userInf = new FrameworkUserInf(userName,StringUtil.encodePassword(password));
List<FrameworkUserInf> list = getFrameworkUserInfListByObj(userInf);
if (list != null && list.size() > 0) {
FrameworkUserInf userinfo = (FrameworkUserInf) list.get(0);
return userinfo;
}
return null;
}
@SuppressWarnings("unchecked")
public void initModifyMyPassword(HttpServletRequest request,Model springModel){
Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute(SessionUtil.USER_MAP);
if(map != null){
Long userId = (Long) map.get(SessionUtil.USER_ID);
String userName = (String) map.get(SessionUtil.USER_NAME);
springModel.addAttribute("v_userId", userId);
springModel.addAttribute("v_userName", userName);
}
}
/**
* 修改密码
* @param model
*/
public void modifyMyPassword(FrameworkUserInf model){
model.setUserPassword(StringUtil.encodePassword(model.getUserPassword()));
myBatisDao.update(model);
}
}
|
package org.campus02.blackjack;
public class DemoBJ {
public static void main(String[] args) {
// TODO Auto-generated method stub
Blackjack BJ = new Blackjack();
player test1 = new player("Hans","18");
System.out.println(BJ.add(test1));
System.out.println(BJ.toString());
BJ.addCard(test1, 10);
System.out.println(BJ.toString());
System.out.println(BJ.add(test1));
}
}
|
package com.fuwo.lib;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.fuwo.lib.util.AppUtil;
/**
* 下拉刷新 上拉加载
*/
public class PullRefreshLayout extends RelativeLayout implements View.OnClickListener {
public final int REFRESH_MIN = AppUtil.dip2px(60); // 最小刷新距离
public final int REFRESH_MAX = AppUtil.dip2px(150);// 最大刷新距离
public final int ROTATE_MIN = AppUtil.dip2px(42); //开始旋转的小距离
public static final int PULL_DOWN_TO_REFRESH = 1; // 下拉刷新
public static final int REFRESHING = 2; //刷新中
public static final int RELEASE_TO_REFRESH = 3; //释放刷新
public static final int PULL_UP_TO_LOAD = 4; // 上拉加载
public static final int LOADING = 5; // 加载中
public static final int RELEASE_TO_LOAD = 6; // 释放加载
private Context mContext;
private View mContentView;
private View mHeaderView;
private CircleView mHeaderCircleView;
private View mFooterView;
private CircleView mFooterCircleView;
private TextView mNoMoreTextView;
private Animation mRotateAnim;
private int mScrollY;
private float mLastX;
private float mLastY;
private boolean mPulled;
private int mPullState;
private boolean mNoMore;
private boolean mAutoLoad;
private OnRefreshListener mRefreshListener;
private OnLoadListener mLoadListener;
public PullRefreshLayout(Context context) {
super(context, null);
}
public PullRefreshLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PullRefreshLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
mRotateAnim = AnimationUtils.loadAnimation(context, R.anim.rotate);
mNoMore = false;
mAutoLoad = false;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount() > 0) {
mContentView = getChildAt(0);
mHeaderView = LayoutInflater.from(mContext).inflate(R.layout.refresh_header, this, false);
LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams();
mHeaderCircleView = (CircleView) mHeaderView.findViewById(R.id.header_pull_iv);
addView(mHeaderView, params);
mFooterView = LayoutInflater.from(mContext).inflate(R.layout.refresh_footer, this, false);
LayoutParams params1 = (LayoutParams) mFooterView.getLayoutParams();
mFooterCircleView = (CircleView) mFooterView.findViewById(R.id.footer_pull_iv);
mNoMoreTextView = (TextView) mFooterView.findViewById(R.id.footer_no_more_tv);
mNoMoreTextView.setOnClickListener(this);
addView(mFooterView, params1);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int height = b - t;
for (int i = 0, size = getChildCount(); i < size; i++) {
View child = getChildAt(i);
int top, bottom;
if (child == mHeaderView) {
top = t - height;
bottom = t;
} else if (child == mFooterView) {
top = b;
bottom = b + height;
} else {
top = t;
bottom = b;
}
child.layout(l, top + mScrollY, r, bottom + mScrollY);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downY(ev);
break;
case MotionEvent.ACTION_MOVE:
moveY(ev);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
upY(ev);
break;
case MotionEvent.ACTION_POINTER_UP:
mLastX = ev.getX(1);
mLastY = ev.getY(1);
break;
case MotionEvent.ACTION_POINTER_UP | 0x0100:
mLastX = ev.getX(0);
mLastY = ev.getY(0);
break;
default:
}
return mPulled || super.dispatchTouchEvent(ev);
}
private void downY(MotionEvent ev) {
mLastX = ev.getX();
mLastY = ev.getY();
mPulled = false;
if (mPullState != REFRESHING && mPullState != LOADING) {
if (!mNoMore) {
mScrollY = 0;
}
mHeaderCircleView.clearAnimation();
mFooterCircleView.clearAnimation();
}
}
private void moveY(MotionEvent ev) {
float moveX = ev.getX();
float moveY = ev.getY();
float y = moveY - mLastY;
mLastX = moveX;
mLastY = moveY;
if (Math.abs(y) > Math.abs(moveX - mLastX)) {
if (((IPull) mContentView).pullDown()) {
mPulled = 0 < y || mScrollY > 0;
if (mPullState != REFRESHING && mPullState != LOADING) {
mPullState = PULL_DOWN_TO_REFRESH;
}
} else if (((IPull) mContentView).pullUp()) {
if (mAutoLoad && !mNoMore) {
postLoad(false);
}
mPulled = 0 > y || mScrollY < 0;
if (mPullState != REFRESHING && mPullState != LOADING) {
mPullState = PULL_UP_TO_LOAD;
}
}
}
if (mPulled && ((Math.abs(y) > 5 || mScrollY != 0))) {
rotateView(y);
requestLayout();
setPressed(false);
}
}
private void upY(MotionEvent ev) {
if (checkRefreshState()) {
if (mPullState == RELEASE_TO_REFRESH) {
postRefresh(true);
} else if (mPullState == RELEASE_TO_LOAD) {
postLoad(true);
} else {
stopRefreshAndLoad();
}
}
//当轻微上下拉的时候,事件取消
if (mPulled) {
ev.setAction(MotionEvent.ACTION_CANCEL);
mPulled = false;
}
}
/**
* 下拉状态, 旋转图标
* 刷新状态时, 下拉高度小于刷新最小高度
*/
private void rotateView(float y) {
mScrollY += y / 2;
if (Math.abs(mScrollY) > REFRESH_MAX) {
mScrollY = mScrollY > 0 ? REFRESH_MAX : -REFRESH_MAX;
}
if (mPullState == REFRESHING || mPullState == LOADING) {
if (mScrollY > REFRESH_MIN) {
mScrollY = REFRESH_MIN;
} else if (mScrollY < -REFRESH_MIN) {
mScrollY = -REFRESH_MIN;
}
} else if (mScrollY < 0 && mNoMore) {
//没有更多 且 上拉
mScrollY += y / 2;
if (mScrollY < -REFRESH_MIN)
mScrollY = -REFRESH_MIN;
} else {
if (mScrollY > 0) {
if (mScrollY > ROTATE_MIN)
mHeaderCircleView.setDegree((int) getDegree());
} else {
if (mScrollY < -ROTATE_MIN)
mFooterCircleView.setDegree((int) getDegree());
}
}
//移动之间距离过大时, 避免下拉出现上拉现象
if (((mPullState == PULL_DOWN_TO_REFRESH || mPullState == REFRESHING) && mScrollY < 0) ||
((mPullState == PULL_UP_TO_LOAD || mPullState == LOADING) && mScrollY > 0)) {
mScrollY = 0;
}
}
private float getDegree() {
return (float) (Math.abs(mScrollY) - ROTATE_MIN) / ROTATE_MIN * 360;
}
/**
* 判断是否刷新
*/
private boolean checkRefreshState() {
boolean result = false;
if (mScrollY < 0 && mNoMore) {
result = false;
} else if (mPullState != REFRESHING && mPullState != LOADING) {
if (mScrollY >= REFRESH_MIN) {
mPullState = RELEASE_TO_REFRESH;
} else if (mScrollY <= -REFRESH_MIN) {
mPullState = RELEASE_TO_LOAD;
}
result = true;
}
return result;
}
/**
* 停止刷新
*/
public void stopRefreshAndLoad() {
if (mScrollY == 0) {
mPullState = PULL_DOWN_TO_REFRESH;
requestLayout();
return;
}
if (mScrollY < 0 && mNoMore) {
mScrollY = -REFRESH_MIN;
} else {
TranslateAnimation animation = new TranslateAnimation(0, 0, mScrollY, 0);
animation.setDuration(200);
for (int i = 0, size = getChildCount(); i < size; i++) {
View view = getChildAt(i);
view.clearAnimation();
view.startAnimation(animation);
}
if (mScrollY > 0) {
mHeaderView.clearAnimation();
mHeaderView.startAnimation(animation);
} else {
mFooterView.clearAnimation();
mFooterView.startAnimation(animation);
}
mScrollY = 0;
}
mHeaderCircleView.clearAnimation();
mHeaderCircleView.setDegree(0);
mFooterCircleView.clearAnimation();
mFooterCircleView.setDegree(0);
mPullState = PULL_DOWN_TO_REFRESH;
requestLayout();
}
/**
* 执行刷新
*/
public void postRefresh(boolean anim) {
if (mPullState == REFRESHING || mPullState == LOADING) {
return;
}
if (anim) {
mScrollY = REFRESH_MIN;
requestLayout();
}
if (mRefreshListener != null) {
setNoMore(false);
mPullState = REFRESHING;
mHeaderCircleView.clearAnimation();
mHeaderCircleView.startAnim();
mHeaderCircleView.startAnimation(mRotateAnim);
mRefreshListener.onRefresh();
} else {
stopRefreshAndLoad();
}
}
/**
* 执行加载
*/
public void postLoad(boolean anim) {
if (mPullState == REFRESHING || mPullState == LOADING) {
return;
}
if (anim) {
mScrollY = -REFRESH_MIN;
requestLayout();
}
if (mLoadListener != null) {
setNoMore(false);
mPullState = LOADING;
mFooterCircleView.clearAnimation();
mFooterCircleView.startAnim();
mFooterCircleView.startAnimation(mRotateAnim);
mLoadListener.onLoad();
} else {
stopRefreshAndLoad();
}
}
public void setNoMore(boolean noMore) {
mNoMore = noMore;
mFooterCircleView.clearAnimation();
if (noMore) {
mFooterCircleView.setVisibility(GONE);
mNoMoreTextView.setVisibility(VISIBLE);
} else {
mFooterCircleView.setVisibility(VISIBLE);
mNoMoreTextView.setVisibility(GONE);
}
}
public boolean isAutoLoad() {
return mAutoLoad;
}
public void setAutoLoad(boolean autoLoad) {
this.mAutoLoad = autoLoad;
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.footer_no_more_tv) {
postLoad(true);
}
}
public interface OnRefreshListener {
void onRefresh();
}
public void setOnRefreshListener(OnRefreshListener listener) {
this.mRefreshListener = listener;
}
public interface OnLoadListener {
void onLoad();
}
public void setOnLoadListener(OnLoadListener listener) {
this.mLoadListener = listener;
}
}
|
package dlsim.DLSim.Util;
/* Generated by Together */
public interface Observable {
void attach(Observer observer);
void detach(Observer observer);
void inform();
/**
* @link
* @shapeType PatternLink
* @pattern <{Observer}>
* @supplierRole <{Observer}>
* @hidden
*/
/*# private Observer _observer; */
}
|
package br.edu.ifpb.cadastrardados.asynctask;
import android.os.AsyncTask;
import android.util.JsonReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import br.edu.ifpb.cadastrardados.Pessoa;
/**
* Created by Henrique on 05/10/2016.
*/
public class ListarAsyncTask extends AsyncTask< String, Void, List<Pessoa> > {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected List<Pessoa> doInBackground(String... strings) {
String urlString = strings[0];
List<Pessoa> pessoas = new ArrayList<>();
try {
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
InputStream instream = connection.getInputStream();
JsonReader reader = new JsonReader(new InputStreamReader(instream, "UTF-8"));
pessoas = getPessoas(reader);
instream.close();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
return pessoas;
}
}
public List<Pessoa> getPessoas(JsonReader reader) throws IOException {
List<Pessoa> pessoas = new ArrayList<Pessoa>();
reader.beginArray();
while (reader.hasNext()) {
pessoas.add(getPessoa(reader));
}
reader.endArray();
return pessoas;
}
public Pessoa getPessoa(JsonReader reader) throws IOException {
String nome = "",email = "",endereco= "",cpf = "";
reader.beginObject();
while (reader.hasNext()) {
String obj = reader.nextName();
if (obj.equals("nome")) {
nome = reader.nextString();
} else if (obj.equals("email")) {
email = reader.nextString();
} else if (obj.equals("endereco")) {
endereco = reader.nextString();
} else if (obj.equals("user")) {
cpf = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
return new Pessoa(nome, email,endereco, cpf);
}
@Override
protected void onPostExecute(List<Pessoa> result){
super.onPostExecute(result);
}
}
|
package com.tencent.mm.plugin.collect.b;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import com.tencent.mm.plugin.collect.b.g.1;
import com.tencent.mm.sdk.platformtools.x;
class g$1$1 implements OnCompletionListener {
final /* synthetic */ 1 hUa;
g$1$1(1 1) {
this.hUa = 1;
}
public final void onCompletion(MediaPlayer mediaPlayer) {
x.i("MicroMsg.F2fRcvVoiceListener", "play done");
g.d(this.hUa.hTZ);
g.a(this.hUa.hTZ, null);
g.e(this.hUa.hTZ);
if (g.f(this.hUa.hTZ).isEmpty()) {
g.aBK();
} else {
g.g(this.hUa.hTZ);
}
}
}
|
package com.abraham.dj.service;
import com.abraham.dj.model.User;
public interface IUserService extends IBaseService{
public int checkUser(User user);
}
|
package ec.com.yacare.y4all.activities.cuenta;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import cn.pedant.SweetAlert.SweetAlertDialog;
import ec.com.yacare.y4all.activities.R;
import ec.com.yacare.y4all.asynctask.ws.DesactivarDispositivoAsyncTask;
import ec.com.yacare.y4all.lib.dto.Dispositivo;
import ec.com.yacare.y4all.lib.resources.YACSmartProperties;
import ec.com.yacare.y4all.lib.sqllite.DispositivoDataSource;
public class ListaDispositivosActivity extends Fragment {
private DispositivoDataSource datasource;
private ArrayList<Dispositivo> mAppList;
private DispositivoAdapter mAdapter;
public ListView mListView;
private String idDispositivoBorrar;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.ac_lista_dispositivo, container, false);
datasource = new DispositivoDataSource(getActivity().getApplicationContext());
datasource.open();
mAppList = datasource.getAllDispositivo();
datasource.close();
mListView = (ListView) view.findViewById(R.id.listView);
mAdapter = new DispositivoAdapter();
mListView.setAdapter(mAdapter);
return view;
}
public void actualizarLista(String respuesta){
if(!respuesta.equals(YACSmartProperties.getInstance().getMessageForKey("error.general"))){
String resultToken = null;
Boolean status = null;
JSONObject respuestaJSON = null;
try {
respuestaJSON = new JSONObject(respuesta);
status = respuestaJSON.getBoolean("statusFlag");
} catch (JSONException e) {
e.printStackTrace();
}
if(status != null && status) {
try {
resultToken = respuestaJSON.getString("resultado");
} catch (JSONException e) {
e.printStackTrace();
}
if(resultToken != null && resultToken.equals("OK")) {
datasource = new DispositivoDataSource(getActivity().getApplicationContext());
datasource.open();
datasource.deleteDispositivo(idDispositivoBorrar);
mAppList = datasource.getAllDispositivo();
datasource.close();
mAdapter = new DispositivoAdapter();
mListView.setAdapter(mAdapter);
new SweetAlertDialog(getActivity(), SweetAlertDialog.SUCCESS_TYPE)
.setTitleText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo"))
.setContentText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo.exito"))
.setConfirmText("Aceptar")
.showCancelButton(true)
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
//Llamar a ws de desactivar dispositivo
}
})
.show();
}else{
//Error
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo"))
.setContentText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo.error"))
.setCancelText("NO")
.setConfirmText("SI")
.showCancelButton(true)
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
//Llamar a ws de desactivar dispositivo
}
})
.show();
}
}
}else{
//Error
new SweetAlertDialog(getActivity(), SweetAlertDialog.ERROR_TYPE)
.setTitleText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo"))
.setContentText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo.error"))
.setCancelText("NO")
.setConfirmText("SI")
.showCancelButton(true)
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
//Llamar a ws de desactivar dispositivo
}
})
.show();
}
}
class DispositivoAdapter extends BaseAdapter {
@Override
public int getCount() {
return mAppList.size();
}
@Override
public Dispositivo getItem(int position) {
return mAppList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(getActivity().getApplicationContext(),
R.layout.li_dispositivo, null);
new ViewHolder(convertView);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
final Dispositivo dispositivo = getItem(position);
File foto = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + dispositivo.getImei() +".jpg");
if(foto.exists()){
Bitmap bmImg = BitmapFactory.decodeFile(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +"/Y4Home/" + dispositivo.getImei() +".jpg");
if(bmImg != null){
mostrarImagen(holder.iv_icon, bmImg);
}
}else {
Bitmap bitmap = ((BitmapDrawable) getResources().getDrawable(R.drawable.usuarioperfil)).getBitmap();
mostrarImagen(holder.iv_icon, bitmap);
}
Typeface fontRegular = Typeface.createFromAsset(getActivity().getAssets(), "Lato-Regular.ttf");
holder.nombreDispositivo.setText(dispositivo.getNombreDispositivo());
holder.nombreDispositivo.setTypeface(fontRegular);
holder.btnDesactivarDispositivo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE)
.setTitleText(YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo"))
.setContentText(dispositivo.getNombreDispositivo() + " " + YACSmartProperties.intance.getMessageForKey("desactivar.dispositivo.subtitulo"))
.setCancelText("NO")
.setConfirmText("SI")
.showCancelButton(true)
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
@Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
//Llamar a ws de desactivar dispositivo
idDispositivoBorrar = dispositivo.getId();
DesactivarDispositivoAsyncTask desactivarDispositivoAsyncTask = new DesactivarDispositivoAsyncTask(ListaDispositivosActivity.this, idDispositivoBorrar);
desactivarDispositivoAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
})
.show();
}
});
return convertView;
}
class ViewHolder {
ImageView iv_icon;
TextView nombreDispositivo;
ImageButton btnDesactivarDispositivo;
public ViewHolder(View view) {
iv_icon = (ImageView) view.findViewById(R.id.ivFoto);
nombreDispositivo = (TextView) view.findViewById(R.id.txtNombreDispositivo);
btnDesactivarDispositivo = (ImageButton) view.findViewById(R.id.btnDesactivarDispositivo);
view.setTag(this);
}
}
}
private void mostrarImagen(ImageView mimageView, Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 2000;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
mimageView.setImageBitmap(output);
}
}
|
package com.spbsu.flamestream.example.bl.text_classifier.model;
import com.spbsu.flamestream.example.bl.text_classifier.model.containers.ClassifierInput;
import com.spbsu.flamestream.example.bl.text_classifier.model.containers.DocContainer;
import java.util.Map;
import java.util.Set;
public class TfIdfObject implements DocContainer, ClassifierInput {
private final int number;
private final Map<String, Integer> tf;
private final Map<String, Integer> idf;
private final String docName;
private final String partitioning;
private final String label;
public Set<String> words() {
return tf.keySet();
}
public int tf(String key) {
return tf.get(key);
}
public int idf(String key) {
return idf.get(key);
}
public TfIdfObject(TfObject tfObject, IdfObject idfObject) {
this.docName = tfObject.document();
this.tf = tfObject.counts();
this.idf = idfObject.counts();
this.partitioning = tfObject.partitioning();
this.number = tfObject.number();
this.label = tfObject.label();
}
public String label() {
return label;
}
@Override
public String document() {
return docName;
}
public int number() {
return number;
}
@Override
public String partitioning() {
return partitioning;
}
@Override
public boolean labeled() {
return label != null;
}
@Override
public String toString() {
return String.format(
"<TFO> doc hash: %d, doc: %s, idf: %s, words: %s",
docName.hashCode(),
docName,
idf,
tf
);
}
}
|
package cn.canlnac.onlinecourse.presentation.presenter;
import android.support.annotation.NonNull;
import javax.inject.Inject;
import cn.canlnac.onlinecourse.data.exception.ResponseStatusException;
import cn.canlnac.onlinecourse.domain.Message;
import cn.canlnac.onlinecourse.domain.interactor.DefaultSubscriber;
import cn.canlnac.onlinecourse.domain.interactor.UseCase;
import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity;
import cn.canlnac.onlinecourse.presentation.ui.activity.MessageActivity;
@PerActivity
public class GetMessagePresenter implements Presenter {
MessageActivity getMessageActivity;
private final UseCase getMessageUseCase;
@Inject
public GetMessagePresenter(UseCase getMessageUseCase) {
this.getMessageUseCase = getMessageUseCase;
}
public void setView(@NonNull MessageActivity getMessageActivity) {
this.getMessageActivity = getMessageActivity;
}
public void initialize() {
this.getMessageUseCase.execute(new GetMessagePresenter.GetMessageSubscriber());
}
@Override
public void resume() {
}
@Override
public void pause() {
}
@Override
public void destroy() {
this.getMessageUseCase.unsubscribe();
}
private final class GetMessageSubscriber extends DefaultSubscriber<Message> {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
if (e instanceof ResponseStatusException) {
switch (((ResponseStatusException)e).code) {
case 400:
GetMessagePresenter.this.getMessageActivity.showToastMessage("参数错误");
break;
case 404:
GetMessagePresenter.this.getMessageActivity.showToastMessage("消息不存在");
break;
case 401:
GetMessagePresenter.this.getMessageActivity.toLogin();
break;
default:
GetMessagePresenter.this.getMessageActivity.showToastMessage("服务器错误:"+((ResponseStatusException)e).code);
}
} else {
GetMessagePresenter.this.getMessageActivity.showToastMessage("网络连接错误");
e.printStackTrace();
}
}
@Override
public void onNext(Message message) {
GetMessagePresenter.this.getMessageActivity.readMessage();
}
}
}
|
package collector.event;
import collector.network.ethereum.EthereumNode;
import lombok.Getter;
import lombok.Setter;
import org.web3j.protocol.core.methods.response.EthBlock.Block;
/**
* @author zacconding
* @Date 2018-12-20
* @GitHub : https://github.com/zacscoding
*/
@Getter
@Setter
public class EthBlockEvent extends EthEvent {
private String networkName;
private long blockTime;
private EthereumNode ethereumNode;
private Block block;
public EthBlockEvent(String networkName, long blockTIme, EthereumNode ethereumNode, Block block) {
super(EthereumEventType.BLOCK);
this.networkName = networkName;
this.blockTime = blockTIme;
this.ethereumNode = ethereumNode;
this.block = block;
}
@Override
public String toSimpleString() {
return String.format("network : %s / node : %s / block : %s[%s]"
, networkName, ethereumNode.getNodeName(), block.getNumber(), block.getHash());
}
}
|
/*
* 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 controlers;
import dao.PessoaDAO;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import models.Imovel;
import util.Tela;
public class TelaHomeController implements Initializable {
@FXML
private Button btnLogin;
@FXML
private Button btnCadastrar;
@FXML
private Button btnPesquisar;
@FXML
private ComboBox<Imovel> comboDormitorio;
@FXML
private ComboBox<Imovel> comboFinalidade;
@FXML
private ComboBox<Imovel> comboPreco;
private List<Imovel> imovel = new ArrayList<>();
private ObservableList<Imovel> obsimovel;
@Override
public void initialize(URL url, ResourceBundle rb) {
carregaImovel();
}
@FXML
private void btnLogin_Click(ActionEvent event) throws IOException{
Tela tela = new Tela();
tela.abrirTela("TelaLoginUsuario" );
}
@FXML
private void btnCadastrar_Click(ActionEvent event) throws IOException {
Tela tela = new Tela();
tela.abrirTela("TelaCadastro");
}
@FXML
private void btnPesquisar_Click(ActionEvent event) {
}
private void btnADM_Click(ActionEvent event) throws IOException {
Tela tela = new Tela();
tela.abrirTela("TelaLoginAdministrador");
}
public void carregaImovel(){
Imovel imovel1 = new Imovel(1, "", "", 100.000, "", "2", "", "", "");
Imovel imovel2 = new Imovel(2, "", "", 200.000, "", "4", "", "","");
Imovel imovel3 = new Imovel(3, "", "", 300.000, "", "6", "", "","");
imovel.add(imovel1);
imovel.add(imovel2);
imovel.add(imovel3);
obsimovel = FXCollections.observableArrayList(imovel);
comboDormitorio.setItems(obsimovel);
}
}
|
package com.elkattanman.farmFxml.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "capital")
public class Capital implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "balance", nullable = false)
private Double balance;
@Column(name = "current_total", nullable = false)
private Double currentTotal;
//-----------------------------------
@Column(name = "total_payments", nullable = false)
private Double totalPayments;
@Column(name = "buy", nullable = false)
private Double buy;
@Column(name = "feed", nullable = false)
private Double feed;
@Column(name = "spending", nullable = false)
private Double spending;
@Column(name = "treatment", nullable = false)
private Double treatment;
//------------------------------------------------
@Column(name = "total_gain", nullable = false)
private Double totalGain;
@Column(name = "sales", nullable = false)
private Double sales;
@Column(name = "reserve", nullable = false)
private Double reserve;
//-------------------------------------------------
}
|
package com.mysql.cj.jdbc;
import com.mysql.cj.CacheAdapter;
import com.mysql.cj.CacheAdapterFactory;
import com.mysql.cj.LicenseConfiguration;
import com.mysql.cj.Messages;
import com.mysql.cj.NativeSession;
import com.mysql.cj.NoSubInterceptorWrapper;
import com.mysql.cj.ParseInfo;
import com.mysql.cj.PreparedQuery;
import com.mysql.cj.ServerVersion;
import com.mysql.cj.Session;
import com.mysql.cj.conf.HostInfo;
import com.mysql.cj.conf.PropertyDefinitions;
import com.mysql.cj.conf.PropertyKey;
import com.mysql.cj.conf.PropertySet;
import com.mysql.cj.conf.RuntimeProperty;
import com.mysql.cj.exceptions.CJException;
import com.mysql.cj.exceptions.ExceptionFactory;
import com.mysql.cj.exceptions.ExceptionInterceptor;
import com.mysql.cj.exceptions.ExceptionInterceptorChain;
import com.mysql.cj.exceptions.UnableToConnectException;
import com.mysql.cj.interceptors.QueryInterceptor;
import com.mysql.cj.jdbc.exceptions.SQLError;
import com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping;
import com.mysql.cj.jdbc.ha.MultiHostMySQLConnection;
import com.mysql.cj.jdbc.interceptors.ConnectionLifecycleInterceptor;
import com.mysql.cj.jdbc.result.CachedResultSetMetaData;
import com.mysql.cj.jdbc.result.CachedResultSetMetaDataImpl;
import com.mysql.cj.jdbc.result.ResultSetFactory;
import com.mysql.cj.jdbc.result.ResultSetInternalMethods;
import com.mysql.cj.jdbc.result.UpdatableResultSet;
import com.mysql.cj.log.StandardLogger;
import com.mysql.cj.protocol.ColumnDefinition;
import com.mysql.cj.protocol.ProtocolEntityFactory;
import com.mysql.cj.protocol.SocksProxySocketFactory;
import com.mysql.cj.util.LRUCache;
import com.mysql.cj.util.StringUtils;
import com.mysql.cj.util.Util;
import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationHandler;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLPermission;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
public class ConnectionImpl implements JdbcConnection, Session.SessionEventListener, Serializable {
private static final long serialVersionUID = 4009476458425101761L;
private static final SQLPermission SET_NETWORK_TIMEOUT_PERM = new SQLPermission("setNetworkTimeout");
private static final SQLPermission ABORT_PERM = new SQLPermission("abort");
public String getHost() {
return this.session.getHostInfo().getHost();
}
private JdbcConnection parentProxy = null;
private JdbcConnection topProxy = null;
private InvocationHandler realProxy = null;
public static Map<?, ?> charsetMap;
public boolean isProxySet() {
return (this.topProxy != null);
}
public void setProxy(JdbcConnection proxy) {
if (this.parentProxy == null)
this.parentProxy = proxy;
this.topProxy = proxy;
this.realProxy = (this.topProxy instanceof MultiHostMySQLConnection) ? (InvocationHandler)((MultiHostMySQLConnection)proxy).getThisAsProxy() : null;
}
private JdbcConnection getProxy() {
return (this.topProxy != null) ? this.topProxy : this;
}
public JdbcConnection getMultiHostSafeProxy() {
return getProxy();
}
public JdbcConnection getMultiHostParentProxy() {
return this.parentProxy;
}
public JdbcConnection getActiveMySQLConnection() {
return this;
}
public Object getConnectionMutex() {
return (this.realProxy != null) ? this.realProxy : getProxy();
}
static class CompoundCacheKey {
final String componentOne;
final String componentTwo;
final int hashCode;
CompoundCacheKey(String partOne, String partTwo) {
this.componentOne = partOne;
this.componentTwo = partTwo;
int hc = 17;
hc = 31 * hc + ((this.componentOne != null) ? this.componentOne.hashCode() : 0);
hc = 31 * hc + ((this.componentTwo != null) ? this.componentTwo.hashCode() : 0);
this.hashCode = hc;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj != null && CompoundCacheKey.class.isAssignableFrom(obj.getClass())) {
CompoundCacheKey another = (CompoundCacheKey)obj;
if ((this.componentOne == null) ? (another.componentOne == null) : this.componentOne.equals(another.componentOne))
return (this.componentTwo == null) ? ((another.componentTwo == null)) : this.componentTwo.equals(another.componentTwo);
}
return false;
}
public int hashCode() {
return this.hashCode;
}
}
protected static final String DEFAULT_LOGGER_CLASS = StandardLogger.class.getName();
private static Map<String, Integer> mapTransIsolationNameToValue = null;
protected static Map<?, ?> roundRobinStatsMap;
private List<ConnectionLifecycleInterceptor> connectionLifecycleInterceptors;
private static final int DEFAULT_RESULT_SET_TYPE = 1003;
private static final int DEFAULT_RESULT_SET_CONCURRENCY = 1007;
private static final Random random;
private CacheAdapter<String, ParseInfo> cachedPreparedStatementParams;
static {
mapTransIsolationNameToValue = new HashMap<>(8);
mapTransIsolationNameToValue.put("READ-UNCOMMITED", Integer.valueOf(1));
mapTransIsolationNameToValue.put("READ-UNCOMMITTED", Integer.valueOf(1));
mapTransIsolationNameToValue.put("READ-COMMITTED", Integer.valueOf(2));
mapTransIsolationNameToValue.put("REPEATABLE-READ", Integer.valueOf(4));
mapTransIsolationNameToValue.put("SERIALIZABLE", Integer.valueOf(8));
random = new Random();
}
public static JdbcConnection getInstance(HostInfo hostInfo) throws SQLException {
return new ConnectionImpl(hostInfo);
}
protected static synchronized int getNextRoundRobinHostIndex(String url, List<?> hostList) {
int indexRange = hostList.size();
int index = random.nextInt(indexRange);
return index;
}
private static boolean nullSafeCompare(String s1, String s2) {
if (s1 == null && s2 == null)
return true;
if (s1 == null && s2 != null)
return false;
return (s1 != null && s1.equals(s2));
}
private String database = null;
private DatabaseMetaData dbmd = null;
private NativeSession session = null;
private boolean isInGlobalTx = false;
private int isolationLevel = 2;
private final CopyOnWriteArrayList<JdbcStatement> openStatements = new CopyOnWriteArrayList<>();
private LRUCache<CompoundCacheKey, CallableStatement.CallableStatementParamInfo> parsedCallableStatementCache;
private String password = null;
protected Properties props = null;
private boolean readOnly = false;
protected LRUCache<String, CachedResultSetMetaData> resultSetMetadataCache;
private Map<String, Class<?>> typeMap;
private String user = null;
private LRUCache<String, Boolean> serverSideStatementCheckCache;
private LRUCache<CompoundCacheKey, ServerPreparedStatement> serverSideStatementCache;
private HostInfo origHostInfo;
private String origHostToConnectTo;
private int origPortToConnectTo;
private boolean hasTriedMasterFlag = false;
private List<QueryInterceptor> queryInterceptors;
protected JdbcPropertySet propertySet;
private RuntimeProperty<Boolean> autoReconnectForPools;
private RuntimeProperty<Boolean> cachePrepStmts;
private RuntimeProperty<Boolean> autoReconnect;
private RuntimeProperty<Boolean> useUsageAdvisor;
private RuntimeProperty<Boolean> reconnectAtTxEnd;
private RuntimeProperty<Boolean> emulateUnsupportedPstmts;
private RuntimeProperty<Boolean> ignoreNonTxTables;
private RuntimeProperty<Boolean> pedantic;
private RuntimeProperty<Integer> prepStmtCacheSqlLimit;
private RuntimeProperty<Boolean> useLocalSessionState;
private RuntimeProperty<Boolean> useServerPrepStmts;
private RuntimeProperty<Boolean> processEscapeCodesForPrepStmts;
private RuntimeProperty<Boolean> useLocalTransactionState;
private RuntimeProperty<Boolean> disconnectOnExpiredPasswords;
private RuntimeProperty<Boolean> readOnlyPropagatesToServer;
protected ResultSetFactory nullStatementResultSetFactory;
private int autoIncrementIncrement;
private ExceptionInterceptor exceptionInterceptor;
private ClientInfoProvider infoProvider;
public JdbcPropertySet getPropertySet() {
return this.propertySet;
}
public void unSafeQueryInterceptors() throws SQLException {
try {
this
.queryInterceptors = (List<QueryInterceptor>)this.queryInterceptors.stream().map(u -> ((NoSubInterceptorWrapper)u).getUnderlyingInterceptor()).collect(Collectors.toList());
if (this.session != null)
this.session.setQueryInterceptors(this.queryInterceptors);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void initializeSafeQueryInterceptors() throws SQLException {
try {
this
.queryInterceptors = (List<QueryInterceptor>)Util.loadClasses(this.propertySet.getStringProperty(PropertyKey.queryInterceptors).getStringValue(), "MysqlIo.BadQueryInterceptor", getExceptionInterceptor()).stream().map(o -> new NoSubInterceptorWrapper(o.init(this, this.props, this.session.getLog()))).collect(Collectors.toList());
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public List<QueryInterceptor> getQueryInterceptorsInstances() {
return this.queryInterceptors;
}
private boolean canHandleAsServerPreparedStatement(String sql) throws SQLException {
if (sql == null || sql.length() == 0)
return true;
if (!((Boolean)this.useServerPrepStmts.getValue()).booleanValue())
return false;
boolean allowMultiQueries = ((Boolean)this.propertySet.getBooleanProperty(PropertyKey.allowMultiQueries).getValue()).booleanValue();
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue())
synchronized (this.serverSideStatementCheckCache) {
Boolean flag = (Boolean)this.serverSideStatementCheckCache.get(sql);
if (flag != null)
return flag.booleanValue();
boolean canHandle = StringUtils.canHandleAsServerPreparedStatementNoCache(sql, getServerVersion(), allowMultiQueries, this.session
.getServerSession().isNoBackslashEscapesSet(), this.session.getServerSession().useAnsiQuotedIdentifiers());
if (sql.length() < ((Integer)this.prepStmtCacheSqlLimit.getValue()).intValue())
this.serverSideStatementCheckCache.put(sql, canHandle ? Boolean.TRUE : Boolean.FALSE);
return canHandle;
}
return StringUtils.canHandleAsServerPreparedStatementNoCache(sql, getServerVersion(), allowMultiQueries, this.session
.getServerSession().isNoBackslashEscapesSet(), this.session.getServerSession().useAnsiQuotedIdentifiers());
}
public void changeUser(String userName, String newPassword) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
if (userName == null || userName.equals(""))
userName = "";
if (newPassword == null)
newPassword = "";
try {
this.session.changeUser(userName, newPassword, this.database);
} catch (CJException ex) {
if ("28000".equals(ex.getSQLState()))
cleanup((Throwable)ex);
throw ex;
}
this.user = userName;
this.password = newPassword;
this.session.configureClientCharacterSet(true);
this.session.setSessionVariables();
setupServerForTruncationChecks();
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void checkClosed() {
this.session.checkClosed();
}
public void throwConnectionClosedException() throws SQLException {
try {
SQLException ex = SQLError.createSQLException(Messages.getString("Connection.2"), "08003",
getExceptionInterceptor());
if (this.session.getForceClosedReason() != null)
ex.initCause(this.session.getForceClosedReason());
throw ex;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private void checkTransactionIsolationLevel() {
String s = this.session.getServerSession().getServerVariable("transaction_isolation");
if (s == null)
s = this.session.getServerSession().getServerVariable("tx_isolation");
if (s != null) {
Integer intTI = mapTransIsolationNameToValue.get(s);
if (intTI != null)
this.isolationLevel = intTI.intValue();
}
}
public void abortInternal() throws SQLException {
try {
this.session.forceClose();
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void cleanup(Throwable whyCleanedUp) {
try {
if (this.session != null)
if (isClosed()) {
this.session.forceClose();
} else {
realClose(false, false, false, whyCleanedUp);
}
} catch (SQLException|CJException sQLException) {}
}
@Deprecated
public void clearHasTriedMaster() {
this.hasTriedMasterFlag = false;
}
public void clearWarnings() throws SQLException {
try {
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql) throws SQLException {
try {
return clientPrepareStatement(sql, 1003, 1007);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, int autoGenKeyIndex) throws SQLException {
try {
PreparedStatement pStmt = clientPrepareStatement(sql);
((ClientPreparedStatement)pStmt).setRetrieveGeneratedKeys((autoGenKeyIndex == 1));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
try {
return clientPrepareStatement(sql, resultSetType, resultSetConcurrency, true);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, int resultSetType, int resultSetConcurrency, boolean processEscapeCodesIfNeeded) throws SQLException {
try {
checkClosed();
String nativeSql = (processEscapeCodesIfNeeded && ((Boolean)this.processEscapeCodesForPrepStmts.getValue()).booleanValue()) ? nativeSQL(sql) : sql;
ClientPreparedStatement pStmt = null;
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue()) {
ParseInfo pStmtInfo = (ParseInfo)this.cachedPreparedStatementParams.get(nativeSql);
if (pStmtInfo == null) {
pStmt = ClientPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, this.database);
this.cachedPreparedStatementParams.put(nativeSql, pStmt.getParseInfo());
} else {
pStmt = ClientPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, this.database, pStmtInfo);
}
} else {
pStmt = ClientPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, this.database);
}
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, int[] autoGenKeyIndexes) throws SQLException {
try {
ClientPreparedStatement pStmt = (ClientPreparedStatement)clientPrepareStatement(sql);
pStmt.setRetrieveGeneratedKeys((autoGenKeyIndexes != null && autoGenKeyIndexes.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, String[] autoGenKeyColNames) throws SQLException {
try {
ClientPreparedStatement pStmt = (ClientPreparedStatement)clientPrepareStatement(sql);
pStmt.setRetrieveGeneratedKeys((autoGenKeyColNames != null && autoGenKeyColNames.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement clientPrepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
try {
return clientPrepareStatement(sql, resultSetType, resultSetConcurrency, true);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void close() throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (this.connectionLifecycleInterceptors != null)
for (ConnectionLifecycleInterceptor cli : this.connectionLifecycleInterceptors)
cli.close();
realClose(true, true, false, null);
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void normalClose() {
try {
close();
} catch (SQLException e) {
ExceptionFactory.createException(e.getMessage(), e);
}
}
private void closeAllOpenStatements() throws SQLException {
SQLException postponedException = null;
for (JdbcStatement stmt : this.openStatements) {
try {
((StatementImpl)stmt).realClose(false, true);
} catch (SQLException sqlEx) {
postponedException = sqlEx;
}
}
if (postponedException != null)
throw postponedException;
}
private void closeStatement(Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException sQLException) {}
stmt = null;
}
}
public void commit() throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock<ConnectionLifecycleInterceptor> iter = new IterateBlock<ConnectionLifecycleInterceptor>(this.connectionLifecycleInterceptors.iterator()) {
void forEach(ConnectionLifecycleInterceptor each) throws SQLException {
if (!each.commit())
this.stopIterating = true;
}
};
iter.doForAll();
if (!iter.fullIteration())
return;
}
if (this.session.getServerSession().isAutoCommit())
throw SQLError.createSQLException(Messages.getString("Connection.3"), getExceptionInterceptor());
if (((Boolean)this.useLocalTransactionState.getValue()).booleanValue() &&
!this.session.getServerSession().inTransactionOnServer())
return;
this.session.execSQL(null, "commit", -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
} catch (SQLException sqlException) {
if ("08S01".equals(sqlException.getSQLState()))
throw SQLError.createSQLException(Messages.getString("Connection.4"), "08007",
getExceptionInterceptor());
throw sqlException;
} finally {
this.session.setNeedsPing(((Boolean)this.reconnectAtTxEnd.getValue()).booleanValue());
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void createNewIO(boolean isForReconnect) {
try {
synchronized (getConnectionMutex()) {
try {
if (!((Boolean)this.autoReconnect.getValue()).booleanValue()) {
connectOneTryOnly(isForReconnect);
return;
}
connectWithRetries(isForReconnect);
} catch (SQLException ex) {
throw (UnableToConnectException)ExceptionFactory.createException(UnableToConnectException.class, ex.getMessage(), ex);
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private void connectWithRetries(boolean isForReconnect) throws SQLException {
double timeout = ((Integer)this.propertySet.getIntegerProperty(PropertyKey.initialTimeout).getValue()).intValue();
boolean connectionGood = false;
Exception connectionException = null;
int attemptCount = 0;
for (; attemptCount < ((Integer)this.propertySet.getIntegerProperty(PropertyKey.maxReconnects).getValue()).intValue() && !connectionGood; attemptCount++) {
try {
boolean oldAutoCommit;
int oldIsolationLevel;
boolean oldReadOnly;
String oldDb;
this.session.forceClose();
JdbcConnection c = getProxy();
this.session.connect(this.origHostInfo, this.user, this.password, this.database, DriverManager.getLoginTimeout() * 1000, c);
pingInternal(false, 0);
synchronized (getConnectionMutex()) {
oldAutoCommit = getAutoCommit();
oldIsolationLevel = this.isolationLevel;
oldReadOnly = isReadOnly(false);
oldDb = getDatabase();
this.session.setQueryInterceptors(this.queryInterceptors);
}
initializePropsFromServer();
if (isForReconnect) {
setAutoCommit(oldAutoCommit);
setTransactionIsolation(oldIsolationLevel);
setDatabase(oldDb);
setReadOnly(oldReadOnly);
}
connectionGood = true;
break;
} catch (UnableToConnectException rejEx) {
close();
this.session.getProtocol().getSocketConnection().forceClose();
} catch (Exception EEE) {
connectionException = EEE;
connectionGood = false;
}
if (connectionGood)
break;
if (attemptCount > 0)
try {
Thread.sleep((long)timeout * 1000L);
} catch (InterruptedException interruptedException) {}
}
if (!connectionGood) {
SQLException chainedEx = SQLError.createSQLException(
Messages.getString("Connection.UnableToConnectWithRetries", new Object[] { this.propertySet.getIntegerProperty(PropertyKey.maxReconnects).getValue() }), "08001", connectionException, getExceptionInterceptor());
throw chainedEx;
}
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.paranoid).getValue()).booleanValue() && !((Boolean)this.autoReconnect.getValue()).booleanValue()) {
this.password = null;
this.user = null;
}
if (isForReconnect) {
Iterator<JdbcStatement> statementIter = this.openStatements.iterator();
Stack<JdbcStatement> serverPreparedStatements = null;
while (statementIter.hasNext()) {
JdbcStatement statementObj = statementIter.next();
if (statementObj instanceof ServerPreparedStatement) {
if (serverPreparedStatements == null)
serverPreparedStatements = new Stack<>();
serverPreparedStatements.add(statementObj);
}
}
if (serverPreparedStatements != null)
while (!serverPreparedStatements.isEmpty())
((ServerPreparedStatement)serverPreparedStatements.pop()).rePrepare();
}
}
private void connectOneTryOnly(boolean isForReconnect) throws SQLException {
Exception connectionNotEstablishedBecause = null;
try {
JdbcConnection c = getProxy();
this.session.connect(this.origHostInfo, this.user, this.password, this.database, DriverManager.getLoginTimeout() * 1000, c);
boolean oldAutoCommit = getAutoCommit();
int oldIsolationLevel = this.isolationLevel;
boolean oldReadOnly = isReadOnly(false);
String oldDb = getDatabase();
this.session.setQueryInterceptors(this.queryInterceptors);
initializePropsFromServer();
if (isForReconnect) {
setAutoCommit(oldAutoCommit);
setTransactionIsolation(oldIsolationLevel);
setDatabase(oldDb);
setReadOnly(oldReadOnly);
}
return;
} catch (UnableToConnectException rejEx) {
close();
this.session.getProtocol().getSocketConnection().forceClose();
throw rejEx;
} catch (Exception EEE) {
if ((EEE instanceof com.mysql.cj.exceptions.PasswordExpiredException || (EEE instanceof SQLException && ((SQLException)EEE)
.getErrorCode() == 1820)) &&
!((Boolean)this.disconnectOnExpiredPasswords.getValue()).booleanValue())
return;
if (this.session != null)
this.session.forceClose();
connectionNotEstablishedBecause = EEE;
if (EEE instanceof SQLException)
throw (SQLException)EEE;
if (EEE.getCause() != null && EEE.getCause() instanceof SQLException)
throw (SQLException)EEE.getCause();
if (EEE instanceof CJException)
throw (CJException)EEE;
SQLException chainedEx = SQLError.createSQLException(Messages.getString("Connection.UnableToConnect"), "08001",
getExceptionInterceptor());
chainedEx.initCause(connectionNotEstablishedBecause);
throw chainedEx;
}
}
private void createPreparedStatementCaches() throws SQLException {
synchronized (getConnectionMutex()) {
int cacheSize = ((Integer)this.propertySet.getIntegerProperty(PropertyKey.prepStmtCacheSize).getValue()).intValue();
String parseInfoCacheFactory = (String)this.propertySet.getStringProperty(PropertyKey.parseInfoCacheFactory).getValue();
try {
Class<?> factoryClass = Class.forName(parseInfoCacheFactory);
CacheAdapterFactory<String, ParseInfo> cacheFactory = (CacheAdapterFactory<String, ParseInfo>)factoryClass.newInstance();
this.cachedPreparedStatementParams = cacheFactory.getInstance(this, this.origHostInfo.getDatabaseUrl(), cacheSize, ((Integer)this.prepStmtCacheSqlLimit
.getValue()).intValue());
} catch (ClassNotFoundException|InstantiationException|IllegalAccessException e) {
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.CantFindCacheFactory", new Object[] { parseInfoCacheFactory, PropertyKey.parseInfoCacheFactory }), getExceptionInterceptor());
sqlEx.initCause(e);
throw sqlEx;
} catch (Exception e) {
SQLException sqlEx = SQLError.createSQLException(
Messages.getString("Connection.CantLoadCacheFactory", new Object[] { parseInfoCacheFactory, PropertyKey.parseInfoCacheFactory }), getExceptionInterceptor());
sqlEx.initCause(e);
throw sqlEx;
}
if (((Boolean)this.useServerPrepStmts.getValue()).booleanValue()) {
this.serverSideStatementCheckCache = new LRUCache(cacheSize);
this.serverSideStatementCache = new LRUCache<CompoundCacheKey, ServerPreparedStatement>(cacheSize) {
private static final long serialVersionUID = 7692318650375988114L;
protected boolean removeEldestEntry(Map.Entry<ConnectionImpl.CompoundCacheKey, ServerPreparedStatement> eldest) {
if (this.maxElements <= 1)
return false;
boolean removeIt = super.removeEldestEntry(eldest);
if (removeIt) {
ServerPreparedStatement ps = eldest.getValue();
ps.isCached = false;
ps.setClosed(false);
try {
ps.realClose(true, true);
} catch (SQLException sQLException) {}
}
return removeIt;
}
};
}
}
}
public Statement createStatement() throws SQLException {
try {
return createStatement(1003, 1007);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
try {
checkClosed();
StatementImpl stmt = new StatementImpl(getMultiHostSafeProxy(), this.database);
stmt.setResultSetType(resultSetType);
stmt.setResultSetConcurrency(resultSetConcurrency);
return stmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
try {
if (((Boolean)this.pedantic.getValue()).booleanValue() &&
resultSetHoldability != 1)
throw SQLError.createSQLException("HOLD_CUSRORS_OVER_COMMIT is only supported holdability level", "S1009",
getExceptionInterceptor());
return createStatement(resultSetType, resultSetConcurrency);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public int getActiveStatementCount() {
return this.openStatements.size();
}
public boolean getAutoCommit() throws SQLException {
try {
synchronized (getConnectionMutex()) {
return this.session.getServerSession().isAutoCommit();
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getCatalog() throws SQLException {
try {
synchronized (getConnectionMutex()) {
return (this.propertySet.getEnumProperty(PropertyKey.databaseTerm).getValue() == PropertyDefinitions.DatabaseTerm.SCHEMA) ? null : this.database;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getCharacterSetMetadata() {
synchronized (getConnectionMutex()) {
return this.session.getServerSession().getCharacterSetMetadata();
}
}
public int getHoldability() throws SQLException {
try {
return 2;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public long getId() {
return this.session.getThreadId();
}
public long getIdleFor() {
synchronized (getConnectionMutex()) {
return this.session.getIdleFor();
}
}
public DatabaseMetaData getMetaData() throws SQLException {
try {
return getMetaData(true, true);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private DatabaseMetaData getMetaData(boolean checkClosed, boolean checkForInfoSchema) throws SQLException {
try {
if (checkClosed)
checkClosed();
DatabaseMetaData dbmeta = DatabaseMetaData.getInstance(getMultiHostSafeProxy(), this.database, checkForInfoSchema, this.nullStatementResultSetFactory);
if (getSession() != null && getSession().getProtocol() != null) {
dbmeta.setMetadataEncoding(getSession().getServerSession().getCharacterSetMetadata());
dbmeta.setMetadataCollationIndex(getSession().getServerSession().getMetadataCollationIndex());
}
return dbmeta;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Statement getMetadataSafeStatement() throws SQLException {
try {
return getMetadataSafeStatement(0);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Statement getMetadataSafeStatement(int maxRows) throws SQLException {
Statement stmt = createStatement();
stmt.setMaxRows((maxRows == -1) ? 0 : maxRows);
stmt.setEscapeProcessing(false);
if (stmt.getFetchSize() != 0)
stmt.setFetchSize(0);
return stmt;
}
public ServerVersion getServerVersion() {
return this.session.getServerSession().getServerVersion();
}
public int getTransactionIsolation() throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (!((Boolean)this.useLocalSessionState.getValue()).booleanValue()) {
String s = this.session.queryServerVariable((
versionMeetsMinimum(8, 0, 3) || (versionMeetsMinimum(5, 7, 20) && !versionMeetsMinimum(8, 0, 0))) ? "@@session.transaction_isolation" : "@@session.tx_isolation");
if (s != null) {
Integer intTI = mapTransIsolationNameToValue.get(s);
if (intTI != null) {
this.isolationLevel = intTI.intValue();
return this.isolationLevel;
}
throw SQLError.createSQLException(Messages.getString("Connection.12", new Object[] { s }), "S1000",
getExceptionInterceptor());
}
throw SQLError.createSQLException(Messages.getString("Connection.13"), "S1000", getExceptionInterceptor());
}
return this.isolationLevel;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Map<String, Class<?>> getTypeMap() throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (this.typeMap == null)
this.typeMap = new HashMap<>();
return this.typeMap;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getURL() {
return this.origHostInfo.getDatabaseUrl();
}
public String getUser() {
return this.user;
}
public SQLWarning getWarnings() throws SQLException {
try {
return null;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean hasSameProperties(JdbcConnection c) {
return this.props.equals(c.getProperties());
}
public Properties getProperties() {
return this.props;
}
@Deprecated
public boolean hasTriedMaster() {
return this.hasTriedMasterFlag;
}
private void initializePropsFromServer() throws SQLException {
String connectionInterceptorClasses = this.propertySet.getStringProperty(PropertyKey.connectionLifecycleInterceptors).getStringValue();
this.connectionLifecycleInterceptors = null;
if (connectionInterceptorClasses != null)
try {
this
.connectionLifecycleInterceptors = (List<ConnectionLifecycleInterceptor>)Util.loadClasses(this.propertySet.getStringProperty(PropertyKey.connectionLifecycleInterceptors).getStringValue(), "Connection.badLifecycleInterceptor", getExceptionInterceptor()).stream().map(o -> o.init(this, this.props, this.session.getLog())).collect(Collectors.toList());
} catch (CJException e) {
throw SQLExceptionsMapping.translateException(e, getExceptionInterceptor());
}
this.session.setSessionVariables();
this.session.loadServerVariables(getConnectionMutex(), this.dbmd.getDriverVersion());
this.autoIncrementIncrement = this.session.getServerSession().getServerVariable("auto_increment_increment", 1);
this.session.buildCollationMapping();
try {
LicenseConfiguration.checkLicenseType(this.session.getServerSession().getServerVariables());
} catch (CJException e) {
throw SQLError.createSQLException(e.getMessage(), "08001", getExceptionInterceptor());
}
this.session.getProtocol().initServerSession();
checkTransactionIsolationLevel();
this.session.checkForCharsetMismatch();
this.session.configureClientCharacterSet(false);
handleAutoCommitDefaults();
this.session.getServerSession().configureCharacterSets();
((DatabaseMetaData)this.dbmd).setMetadataEncoding(getSession().getServerSession().getCharacterSetMetadata());
((DatabaseMetaData)this.dbmd).setMetadataCollationIndex(getSession().getServerSession().getMetadataCollationIndex());
setupServerForTruncationChecks();
}
private void handleAutoCommitDefaults() throws SQLException {
try {
boolean resetAutoCommitDefault = false;
String initConnectValue = this.session.getServerSession().getServerVariable("init_connect");
if (initConnectValue != null && initConnectValue.length() > 0) {
String s = this.session.queryServerVariable("@@session.autocommit");
if (s != null) {
this.session.getServerSession().setAutoCommit(Boolean.parseBoolean(s));
if (!this.session.getServerSession().isAutoCommit())
resetAutoCommitDefault = true;
}
} else {
resetAutoCommitDefault = true;
}
if (resetAutoCommitDefault)
try {
setAutoCommit(true);
} catch (SQLException ex) {
if (ex.getErrorCode() != 1820 || ((Boolean)this.disconnectOnExpiredPasswords.getValue()).booleanValue())
throw ex;
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isClosed() {
try {
return this.session.isClosed();
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isInGlobalTx() {
return this.isInGlobalTx;
}
public boolean isMasterConnection() {
return false;
}
public boolean isReadOnly() throws SQLException {
try {
return isReadOnly(true);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isReadOnly(boolean useSessionStatus) throws SQLException {
try {
if (useSessionStatus && !this.session.isClosed() && versionMeetsMinimum(5, 6, 5) && !((Boolean)this.useLocalSessionState.getValue()).booleanValue() && ((Boolean)this.readOnlyPropagatesToServer
.getValue()).booleanValue()) {
String s = this.session.queryServerVariable((
versionMeetsMinimum(8, 0, 3) || (versionMeetsMinimum(5, 7, 20) && !versionMeetsMinimum(8, 0, 0))) ? "@@session.transaction_read_only" : "@@session.tx_read_only");
if (s != null)
return (Integer.parseInt(s) != 0);
}
return this.readOnly;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isSameResource(JdbcConnection otherConnection) {
synchronized (getConnectionMutex()) {
if (otherConnection == null)
return false;
boolean directCompare = true;
String otherHost = ((ConnectionImpl)otherConnection).origHostToConnectTo;
String otherOrigDatabase = ((ConnectionImpl)otherConnection).origHostInfo.getDatabase();
String otherCurrentDb = ((ConnectionImpl)otherConnection).database;
if (!nullSafeCompare(otherHost, this.origHostToConnectTo)) {
directCompare = false;
} else if (otherHost != null && otherHost.indexOf(',') == -1 && otherHost.indexOf(':') == -1) {
directCompare = (((ConnectionImpl)otherConnection).origPortToConnectTo == this.origPortToConnectTo);
}
if (directCompare && (
!nullSafeCompare(otherOrigDatabase, this.origHostInfo.getDatabase()) || !nullSafeCompare(otherCurrentDb, this.database)))
directCompare = false;
if (directCompare)
return true;
String otherResourceId = (String)((ConnectionImpl)otherConnection).getPropertySet().getStringProperty(PropertyKey.resourceId).getValue();
String myResourceId = (String)this.propertySet.getStringProperty(PropertyKey.resourceId).getValue();
if (otherResourceId != null || myResourceId != null) {
directCompare = nullSafeCompare(otherResourceId, myResourceId);
if (directCompare)
return true;
}
return false;
}
}
protected ConnectionImpl() {
this.autoIncrementIncrement = 0;
}
public ConnectionImpl(HostInfo hostInfo) throws SQLException {
this.autoIncrementIncrement = 0;
try {
this.origHostInfo = hostInfo;
this.origHostToConnectTo = hostInfo.getHost();
this.origPortToConnectTo = hostInfo.getPort();
this.database = hostInfo.getDatabase();
this.user = StringUtils.isNullOrEmpty(hostInfo.getUser()) ? "" : hostInfo.getUser();
this.password = StringUtils.isNullOrEmpty(hostInfo.getPassword()) ? "" : hostInfo.getPassword();
this.props = hostInfo.exposeAsProperties();
this.propertySet = new JdbcPropertySetImpl();
this.propertySet.initializeProperties(this.props);
this.nullStatementResultSetFactory = new ResultSetFactory(this, null);
this.session = new NativeSession(hostInfo, this.propertySet);
this.session.addListener(this);
this.autoReconnectForPools = this.propertySet.getBooleanProperty(PropertyKey.autoReconnectForPools);
this.cachePrepStmts = this.propertySet.getBooleanProperty(PropertyKey.cachePrepStmts);
this.autoReconnect = this.propertySet.getBooleanProperty(PropertyKey.autoReconnect);
this.useUsageAdvisor = this.propertySet.getBooleanProperty(PropertyKey.useUsageAdvisor);
this.reconnectAtTxEnd = this.propertySet.getBooleanProperty(PropertyKey.reconnectAtTxEnd);
this.emulateUnsupportedPstmts = this.propertySet.getBooleanProperty(PropertyKey.emulateUnsupportedPstmts);
this.ignoreNonTxTables = this.propertySet.getBooleanProperty(PropertyKey.ignoreNonTxTables);
this.pedantic = this.propertySet.getBooleanProperty(PropertyKey.pedantic);
this.prepStmtCacheSqlLimit = this.propertySet.getIntegerProperty(PropertyKey.prepStmtCacheSqlLimit);
this.useLocalSessionState = this.propertySet.getBooleanProperty(PropertyKey.useLocalSessionState);
this.useServerPrepStmts = this.propertySet.getBooleanProperty(PropertyKey.useServerPrepStmts);
this.processEscapeCodesForPrepStmts = this.propertySet.getBooleanProperty(PropertyKey.processEscapeCodesForPrepStmts);
this.useLocalTransactionState = this.propertySet.getBooleanProperty(PropertyKey.useLocalTransactionState);
this.disconnectOnExpiredPasswords = this.propertySet.getBooleanProperty(PropertyKey.disconnectOnExpiredPasswords);
this.readOnlyPropagatesToServer = this.propertySet.getBooleanProperty(PropertyKey.readOnlyPropagatesToServer);
String exceptionInterceptorClasses = this.propertySet.getStringProperty(PropertyKey.exceptionInterceptors).getStringValue();
if (exceptionInterceptorClasses != null && !"".equals(exceptionInterceptorClasses))
this.exceptionInterceptor = (ExceptionInterceptor)new ExceptionInterceptorChain(exceptionInterceptorClasses, this.props, this.session.getLog());
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue())
createPreparedStatementCaches();
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.cacheCallableStmts).getValue()).booleanValue())
this.parsedCallableStatementCache = new LRUCache(((Integer)this.propertySet.getIntegerProperty(PropertyKey.callableStmtCacheSize).getValue()).intValue());
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.allowMultiQueries).getValue()).booleanValue())
this.propertySet.getProperty(PropertyKey.cacheResultSetMetadata).setValue(Boolean.valueOf(false));
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.cacheResultSetMetadata).getValue()).booleanValue())
this.resultSetMetadataCache = new LRUCache(((Integer)this.propertySet.getIntegerProperty(PropertyKey.metadataCacheSize).getValue()).intValue());
if (this.propertySet.getStringProperty(PropertyKey.socksProxyHost).getStringValue() != null)
this.propertySet.getProperty(PropertyKey.socketFactory).setValue(SocksProxySocketFactory.class.getName());
this.dbmd = getMetaData(false, false);
initializeSafeQueryInterceptors();
} catch (CJException e1) {
throw SQLExceptionsMapping.translateException(e1, getExceptionInterceptor());
}
try {
createNewIO(false);
unSafeQueryInterceptors();
AbandonedConnectionCleanupThread.trackConnection(this, getSession().getNetworkResources());
} catch (SQLException ex) {
cleanup(ex);
throw ex;
} catch (Exception ex) {
cleanup(ex);
throw SQLError.createSQLException(((Boolean)this.propertySet.getBooleanProperty(PropertyKey.paranoid).getValue()).booleanValue() ? Messages.getString("Connection.0") : Messages.getString("Connection.1", new Object[] { this.session.getHostInfo().getHost(), Integer.valueOf(this.session.getHostInfo().getPort()) }), "08S01", ex, getExceptionInterceptor());
}
}
public int getAutoIncrementIncrement() {
return this.autoIncrementIncrement;
}
public boolean lowerCaseTableNames() {
return this.session.getServerSession().isLowerCaseTableNames();
}
public String nativeSQL(String sql) throws SQLException {
try {
if (sql == null)
return null;
Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, getMultiHostSafeProxy().getSession().getServerSession().getDefaultTimeZone(),
getMultiHostSafeProxy().getSession().getServerSession().getCapabilities().serverSupportsFracSecs(),
getMultiHostSafeProxy().getSession().getServerSession().isServerTruncatesFracSecs(), getExceptionInterceptor());
if (escapedSqlResult instanceof String)
return (String)escapedSqlResult;
return ((EscapeProcessorResult)escapedSqlResult).escapedSql;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private CallableStatement parseCallableStatement(String sql) throws SQLException {
Object escapedSqlResult = EscapeProcessor.escapeSQL(sql, getMultiHostSafeProxy().getSession().getServerSession().getDefaultTimeZone(),
getMultiHostSafeProxy().getSession().getServerSession().getCapabilities().serverSupportsFracSecs(),
getMultiHostSafeProxy().getSession().getServerSession().isServerTruncatesFracSecs(), getExceptionInterceptor());
boolean isFunctionCall = false;
String parsedSql = null;
if (escapedSqlResult instanceof EscapeProcessorResult) {
parsedSql = ((EscapeProcessorResult)escapedSqlResult).escapedSql;
isFunctionCall = ((EscapeProcessorResult)escapedSqlResult).callingStoredFunction;
} else {
parsedSql = (String)escapedSqlResult;
isFunctionCall = false;
}
return CallableStatement.getInstance(getMultiHostSafeProxy(), parsedSql, this.database, isFunctionCall);
}
public void ping() throws SQLException {
try {
pingInternal(true, 0);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void pingInternal(boolean checkForClosedConnection, int timeoutMillis) throws SQLException {
try {
this.session.ping(checkForClosedConnection, timeoutMillis);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public CallableStatement prepareCall(String sql) throws SQLException {
try {
return prepareCall(sql, 1003, 1007);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
try {
CallableStatement cStmt = null;
if (!((Boolean)this.propertySet.getBooleanProperty(PropertyKey.cacheCallableStmts).getValue()).booleanValue()) {
cStmt = parseCallableStatement(sql);
} else {
synchronized (this.parsedCallableStatementCache) {
CompoundCacheKey key = new CompoundCacheKey(getDatabase(), sql);
CallableStatement.CallableStatementParamInfo cachedParamInfo = (CallableStatement.CallableStatementParamInfo)this.parsedCallableStatementCache.get(key);
if (cachedParamInfo != null) {
cStmt = CallableStatement.getInstance(getMultiHostSafeProxy(), cachedParamInfo);
} else {
cStmt = parseCallableStatement(sql);
synchronized (cStmt) {
cachedParamInfo = cStmt.paramInfo;
}
this.parsedCallableStatementCache.put(key, cachedParamInfo);
}
}
}
cStmt.setResultSetType(resultSetType);
cStmt.setResultSetConcurrency(resultSetConcurrency);
return cStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
try {
if (((Boolean)this.pedantic.getValue()).booleanValue() &&
resultSetHoldability != 1)
throw SQLError.createSQLException(Messages.getString("Connection.17"), "S1009", getExceptionInterceptor());
CallableStatement cStmt = (CallableStatement)prepareCall(sql, resultSetType, resultSetConcurrency);
return cStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql) throws SQLException {
try {
return prepareStatement(sql, 1003, 1007);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql, int autoGenKeyIndex) throws SQLException {
try {
PreparedStatement pStmt = prepareStatement(sql);
((ClientPreparedStatement)pStmt).setRetrieveGeneratedKeys((autoGenKeyIndex == 1));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
ClientPreparedStatement pStmt = null;
boolean canServerPrepare = true;
String nativeSql = ((Boolean)this.processEscapeCodesForPrepStmts.getValue()).booleanValue() ? nativeSQL(sql) : sql;
if (((Boolean)this.useServerPrepStmts.getValue()).booleanValue() && ((Boolean)this.emulateUnsupportedPstmts.getValue()).booleanValue())
canServerPrepare = canHandleAsServerPreparedStatement(nativeSql);
if (((Boolean)this.useServerPrepStmts.getValue()).booleanValue() && canServerPrepare) {
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue()) {
synchronized (this.serverSideStatementCache) {
pStmt = (ClientPreparedStatement)this.serverSideStatementCache.remove(new CompoundCacheKey(this.database, sql));
if (pStmt != null) {
((ServerPreparedStatement)pStmt).setClosed(false);
pStmt.clearParameters();
}
if (pStmt == null)
try {
pStmt = ServerPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, this.database, resultSetType, resultSetConcurrency);
if (sql.length() < ((Integer)this.prepStmtCacheSqlLimit.getValue()).intValue())
((ServerPreparedStatement)pStmt).isCacheable = true;
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
} catch (SQLException sqlEx) {
if (((Boolean)this.emulateUnsupportedPstmts.getValue()).booleanValue()) {
pStmt = (ClientPreparedStatement)clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
if (sql.length() < ((Integer)this.prepStmtCacheSqlLimit.getValue()).intValue())
this.serverSideStatementCheckCache.put(sql, Boolean.FALSE);
} else {
throw sqlEx;
}
}
}
} else {
try {
pStmt = ServerPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, this.database, resultSetType, resultSetConcurrency);
pStmt.setResultSetType(resultSetType);
pStmt.setResultSetConcurrency(resultSetConcurrency);
} catch (SQLException sqlEx) {
if (((Boolean)this.emulateUnsupportedPstmts.getValue()).booleanValue()) {
pStmt = (ClientPreparedStatement)clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
} else {
throw sqlEx;
}
}
}
} else {
pStmt = (ClientPreparedStatement)clientPrepareStatement(nativeSql, resultSetType, resultSetConcurrency, false);
}
return pStmt;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
try {
if (((Boolean)this.pedantic.getValue()).booleanValue() &&
resultSetHoldability != 1)
throw SQLError.createSQLException(Messages.getString("Connection.17"), "S1009", getExceptionInterceptor());
return prepareStatement(sql, resultSetType, resultSetConcurrency);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql, int[] autoGenKeyIndexes) throws SQLException {
try {
PreparedStatement pStmt = prepareStatement(sql);
((ClientPreparedStatement)pStmt).setRetrieveGeneratedKeys((autoGenKeyIndexes != null && autoGenKeyIndexes.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement prepareStatement(String sql, String[] autoGenKeyColNames) throws SQLException {
try {
PreparedStatement pStmt = prepareStatement(sql);
((ClientPreparedStatement)pStmt).setRetrieveGeneratedKeys((autoGenKeyColNames != null && autoGenKeyColNames.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void realClose(boolean calledExplicitly, boolean issueRollback, boolean skipLocalTeardown, Throwable reason) throws SQLException {
try {
SQLException sqlEx = null;
if (isClosed())
return;
this.session.setForceClosedReason(reason);
try {
if (!skipLocalTeardown) {
if (!getAutoCommit() && issueRollback)
try {
rollback();
} catch (SQLException ex) {
sqlEx = ex;
}
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.gatherPerfMetrics).getValue()).booleanValue())
this.session.getProtocol().getMetricsHolder().reportMetrics(this.session.getLog());
if (((Boolean)this.useUsageAdvisor.getValue()).booleanValue()) {
if (!calledExplicitly)
this.session.getProfilerEventHandler().processEvent((byte)0, (Session)this.session, null, null, 0L, new Throwable(),
Messages.getString("Connection.18"));
if (System.currentTimeMillis() - this.session.getConnectionCreationTimeMillis() < 500L)
this.session.getProfilerEventHandler().processEvent((byte)0, (Session)this.session, null, null, 0L, new Throwable(),
Messages.getString("Connection.19"));
}
try {
closeAllOpenStatements();
} catch (SQLException ex) {
sqlEx = ex;
}
this.session.quit();
} else {
this.session.forceClose();
}
if (this.queryInterceptors != null)
for (int i = 0; i < this.queryInterceptors.size(); i++)
((QueryInterceptor)this.queryInterceptors.get(i)).destroy();
if (this.exceptionInterceptor != null)
this.exceptionInterceptor.destroy();
} finally {
this.openStatements.clear();
this.queryInterceptors = null;
this.exceptionInterceptor = null;
this.nullStatementResultSetFactory = null;
}
if (sqlEx != null)
throw sqlEx;
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void recachePreparedStatement(JdbcPreparedStatement pstmt) throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue() && pstmt.isPoolable())
synchronized (this.serverSideStatementCache) {
Object oldServerPrepStmt = this.serverSideStatementCache.put(new CompoundCacheKey(pstmt
.getCurrentDatabase(), ((PreparedQuery)pstmt.getQuery()).getOriginalSql()), pstmt);
if (oldServerPrepStmt != null && oldServerPrepStmt != pstmt) {
((ServerPreparedStatement)oldServerPrepStmt).isCached = false;
((ServerPreparedStatement)oldServerPrepStmt).setClosed(false);
((ServerPreparedStatement)oldServerPrepStmt).realClose(true, true);
}
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void decachePreparedStatement(JdbcPreparedStatement pstmt) throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (((Boolean)this.cachePrepStmts.getValue()).booleanValue())
synchronized (this.serverSideStatementCache) {
this.serverSideStatementCache
.remove(new CompoundCacheKey(pstmt.getCurrentDatabase(), ((PreparedQuery)pstmt.getQuery()).getOriginalSql()));
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void registerStatement(JdbcStatement stmt) {
this.openStatements.addIfAbsent(stmt);
}
public void releaseSavepoint(Savepoint arg0) throws SQLException {
try {
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void resetServerState() throws SQLException {
try {
if (!((Boolean)this.propertySet.getBooleanProperty(PropertyKey.paranoid).getValue()).booleanValue() && this.session != null)
changeUser(this.user, this.password);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void rollback() throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock<ConnectionLifecycleInterceptor> iter = new IterateBlock<ConnectionLifecycleInterceptor>(this.connectionLifecycleInterceptors.iterator()) {
void forEach(ConnectionLifecycleInterceptor each) throws SQLException {
if (!each.rollback())
this.stopIterating = true;
}
};
iter.doForAll();
if (!iter.fullIteration())
return;
}
if (this.session.getServerSession().isAutoCommit())
throw SQLError.createSQLException(Messages.getString("Connection.20"), "08003",
getExceptionInterceptor());
try {
rollbackNoChecks();
} catch (SQLException sqlEx) {
if (((Boolean)this.ignoreNonTxTables.getInitialValue()).booleanValue() && sqlEx.getErrorCode() == 1196)
return;
throw sqlEx;
}
} catch (SQLException sqlException) {
if ("08S01".equals(sqlException.getSQLState()))
throw SQLError.createSQLException(Messages.getString("Connection.21"), "08007",
getExceptionInterceptor());
throw sqlException;
} finally {
this.session.setNeedsPing(((Boolean)this.reconnectAtTxEnd.getValue()).booleanValue());
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void rollback(final Savepoint savepoint) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
try {
if (this.connectionLifecycleInterceptors != null) {
IterateBlock<ConnectionLifecycleInterceptor> iter = new IterateBlock<ConnectionLifecycleInterceptor>(this.connectionLifecycleInterceptors.iterator()) {
void forEach(ConnectionLifecycleInterceptor each) throws SQLException {
if (!each.rollback(savepoint))
this.stopIterating = true;
}
};
iter.doForAll();
if (!iter.fullIteration())
return;
}
StringBuilder rollbackQuery = new StringBuilder("ROLLBACK TO SAVEPOINT ");
rollbackQuery.append('`');
rollbackQuery.append(savepoint.getSavepointName());
rollbackQuery.append('`');
Statement stmt = null;
try {
stmt = getMetadataSafeStatement();
stmt.executeUpdate(rollbackQuery.toString());
} catch (SQLException sqlEx) {
int errno = sqlEx.getErrorCode();
if (errno == 1181) {
String msg = sqlEx.getMessage();
if (msg != null) {
int indexOfError153 = msg.indexOf("153");
if (indexOfError153 != -1)
throw SQLError.createSQLException(Messages.getString("Connection.22", new Object[] { savepoint.getSavepointName() }), "S1009", errno,
getExceptionInterceptor());
}
}
if (((Boolean)this.ignoreNonTxTables.getValue()).booleanValue() && sqlEx.getErrorCode() != 1196)
throw sqlEx;
if ("08S01".equals(sqlEx.getSQLState()))
throw SQLError.createSQLException(Messages.getString("Connection.23"), "08007",
getExceptionInterceptor());
throw sqlEx;
} finally {
closeStatement(stmt);
}
} finally {
this.session.setNeedsPing(((Boolean)this.reconnectAtTxEnd.getValue()).booleanValue());
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private void rollbackNoChecks() throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (((Boolean)this.useLocalTransactionState.getValue()).booleanValue() &&
!this.session.getServerSession().inTransactionOnServer())
return;
this.session.execSQL(null, "rollback", -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql) throws SQLException {
try {
String nativeSql = ((Boolean)this.processEscapeCodesForPrepStmts.getValue()).booleanValue() ? nativeSQL(sql) : sql;
return ServerPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, getDatabase(), 1003, 1007);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql, int autoGenKeyIndex) throws SQLException {
try {
String nativeSql = ((Boolean)this.processEscapeCodesForPrepStmts.getValue()).booleanValue() ? nativeSQL(sql) : sql;
ClientPreparedStatement pStmt = ServerPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, getDatabase(), 1003, 1007);
pStmt.setRetrieveGeneratedKeys((autoGenKeyIndex == 1));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
try {
String nativeSql = ((Boolean)this.processEscapeCodesForPrepStmts.getValue()).booleanValue() ? nativeSQL(sql) : sql;
return ServerPreparedStatement.getInstance(getMultiHostSafeProxy(), nativeSql, getDatabase(), resultSetType, resultSetConcurrency);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
try {
if (((Boolean)this.pedantic.getValue()).booleanValue() &&
resultSetHoldability != 1)
throw SQLError.createSQLException(Messages.getString("Connection.17"), "S1009", getExceptionInterceptor());
return serverPrepareStatement(sql, resultSetType, resultSetConcurrency);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql, int[] autoGenKeyIndexes) throws SQLException {
try {
ClientPreparedStatement pStmt = (ClientPreparedStatement)serverPrepareStatement(sql);
pStmt.setRetrieveGeneratedKeys((autoGenKeyIndexes != null && autoGenKeyIndexes.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public PreparedStatement serverPrepareStatement(String sql, String[] autoGenKeyColNames) throws SQLException {
try {
ClientPreparedStatement pStmt = (ClientPreparedStatement)serverPrepareStatement(sql);
pStmt.setRetrieveGeneratedKeys((autoGenKeyColNames != null && autoGenKeyColNames.length > 0));
return pStmt;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setAutoCommit(final boolean autoCommitFlag) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
if (this.connectionLifecycleInterceptors != null) {
IterateBlock<ConnectionLifecycleInterceptor> iter = new IterateBlock<ConnectionLifecycleInterceptor>(this.connectionLifecycleInterceptors.iterator()) {
void forEach(ConnectionLifecycleInterceptor each) throws SQLException {
if (!each.setAutoCommit(autoCommitFlag))
this.stopIterating = true;
}
};
iter.doForAll();
if (!iter.fullIteration())
return;
}
if (((Boolean)this.autoReconnectForPools.getValue()).booleanValue())
this.autoReconnect.setValue(Boolean.valueOf(true));
try {
boolean needsSetOnServer = true;
if (((Boolean)this.useLocalSessionState.getValue()).booleanValue() && this.session.getServerSession().isAutoCommit() == autoCommitFlag) {
needsSetOnServer = false;
} else if (!((Boolean)this.autoReconnect.getValue()).booleanValue()) {
needsSetOnServer = getSession().isSetNeededForAutoCommitMode(autoCommitFlag);
}
this.session.getServerSession().setAutoCommit(autoCommitFlag);
if (needsSetOnServer)
this.session.execSQL(null, autoCommitFlag ? "SET autocommit=1" : "SET autocommit=0", -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
} finally {
if (((Boolean)this.autoReconnectForPools.getValue()).booleanValue())
this.autoReconnect.setValue(Boolean.valueOf(false));
}
return;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setCatalog(String catalog) throws SQLException {
try {
if (this.propertySet.getEnumProperty(PropertyKey.databaseTerm).getValue() == PropertyDefinitions.DatabaseTerm.CATALOG)
setDatabase(catalog);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setDatabase(final String db) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
if (db == null)
throw SQLError.createSQLException("Database can not be null", "S1009", getExceptionInterceptor());
if (this.connectionLifecycleInterceptors != null) {
IterateBlock<ConnectionLifecycleInterceptor> iter = new IterateBlock<ConnectionLifecycleInterceptor>(this.connectionLifecycleInterceptors.iterator()) {
void forEach(ConnectionLifecycleInterceptor each) throws SQLException {
if (!each.setDatabase(db))
this.stopIterating = true;
}
};
iter.doForAll();
if (!iter.fullIteration())
return;
}
if (((Boolean)this.useLocalSessionState.getValue()).booleanValue())
if (this.session.getServerSession().isLowerCaseTableNames()) {
if (this.database.equalsIgnoreCase(db))
return;
} else if (this.database.equals(db)) {
return;
}
String quotedId = this.session.getIdentifierQuoteString();
if (quotedId == null || quotedId.equals(" "))
quotedId = "";
StringBuilder query = new StringBuilder("USE ");
query.append(StringUtils.quoteIdentifier(db, quotedId, ((Boolean)this.pedantic.getValue()).booleanValue()));
this.session.execSQL(null, query.toString(), -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
this.database = db;
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getDatabase() throws SQLException {
try {
synchronized (getConnectionMutex()) {
return this.database;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setFailedOver(boolean flag) {}
public void setHoldability(int arg0) throws SQLException {
try {
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setInGlobalTx(boolean flag) {
this.isInGlobalTx = flag;
}
public void setReadOnly(boolean readOnlyFlag) throws SQLException {
try {
checkClosed();
setReadOnlyInternal(readOnlyFlag);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setReadOnlyInternal(boolean readOnlyFlag) throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (((Boolean)this.readOnlyPropagatesToServer.getValue()).booleanValue() && versionMeetsMinimum(5, 6, 5) && (
!((Boolean)this.useLocalSessionState.getValue()).booleanValue() || readOnlyFlag != this.readOnly))
this.session.execSQL(null, "set session transaction " + (readOnlyFlag ? "read only" : "read write"), -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
this.readOnly = readOnlyFlag;
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Savepoint setSavepoint() throws SQLException {
try {
MysqlSavepoint savepoint = new MysqlSavepoint(getExceptionInterceptor());
setSavepoint(savepoint);
return savepoint;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private void setSavepoint(MysqlSavepoint savepoint) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
StringBuilder savePointQuery = new StringBuilder("SAVEPOINT ");
savePointQuery.append('`');
savePointQuery.append(savepoint.getSavepointName());
savePointQuery.append('`');
Statement stmt = null;
try {
stmt = getMetadataSafeStatement();
stmt.executeUpdate(savePointQuery.toString());
} finally {
closeStatement(stmt);
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Savepoint setSavepoint(String name) throws SQLException {
try {
synchronized (getConnectionMutex()) {
MysqlSavepoint savepoint = new MysqlSavepoint(name, getExceptionInterceptor());
setSavepoint(savepoint);
return savepoint;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setTransactionIsolation(int level) throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
String sql = null;
boolean shouldSendSet = false;
if (((Boolean)this.propertySet.getBooleanProperty(PropertyKey.alwaysSendSetIsolation).getValue()).booleanValue()) {
shouldSendSet = true;
} else if (level != this.isolationLevel) {
shouldSendSet = true;
}
if (((Boolean)this.useLocalSessionState.getValue()).booleanValue())
shouldSendSet = (this.isolationLevel != level);
if (shouldSendSet) {
switch (level) {
case 0:
throw SQLError.createSQLException(Messages.getString("Connection.24"), getExceptionInterceptor());
case 2:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED";
break;
case 1:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED";
break;
case 4:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
break;
case 8:
sql = "SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE";
break;
default:
throw SQLError.createSQLException(Messages.getString("Connection.25", new Object[] { Integer.valueOf(level) }), "S1C00",
getExceptionInterceptor());
}
this.session.execSQL(null, sql, -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
this.isolationLevel = level;
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
try {
synchronized (getConnectionMutex()) {
this.typeMap = map;
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private void setupServerForTruncationChecks() throws SQLException {
try {
synchronized (getConnectionMutex()) {
RuntimeProperty<Boolean> jdbcCompliantTruncation = this.propertySet.getProperty(PropertyKey.jdbcCompliantTruncation);
if (((Boolean)jdbcCompliantTruncation.getValue()).booleanValue()) {
String currentSqlMode = this.session.getServerSession().getServerVariable("sql_mode");
boolean strictTransTablesIsSet = (StringUtils.indexOfIgnoreCase(currentSqlMode, "STRICT_TRANS_TABLES") != -1);
if (currentSqlMode == null || currentSqlMode.length() == 0 || !strictTransTablesIsSet) {
StringBuilder commandBuf = new StringBuilder("SET sql_mode='");
if (currentSqlMode != null && currentSqlMode.length() > 0) {
commandBuf.append(currentSqlMode);
commandBuf.append(",");
}
commandBuf.append("STRICT_TRANS_TABLES'");
this.session.execSQL(null, commandBuf.toString(), -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
jdbcCompliantTruncation.setValue(Boolean.valueOf(false));
} else if (strictTransTablesIsSet) {
jdbcCompliantTruncation.setValue(Boolean.valueOf(false));
}
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void shutdownServer() throws SQLException {
try {
try {
this.session.shutdownServer();
} catch (CJException ex) {
SQLException sqlEx = SQLError.createSQLException(Messages.getString("Connection.UnhandledExceptionDuringShutdown"), "S1000",
getExceptionInterceptor());
sqlEx.initCause((Throwable)ex);
throw sqlEx;
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void unregisterStatement(JdbcStatement stmt) {
this.openStatements.remove(stmt);
}
public boolean versionMeetsMinimum(int major, int minor, int subminor) {
try {
checkClosed();
return this.session.versionMeetsMinimum(major, minor, subminor);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public CachedResultSetMetaData getCachedMetaData(String sql) {
if (this.resultSetMetadataCache != null)
synchronized (this.resultSetMetadataCache) {
return (CachedResultSetMetaData)this.resultSetMetadataCache.get(sql);
}
return null;
}
public void initializeResultsMetadataFromCache(String sql, CachedResultSetMetaData cachedMetaData, ResultSetInternalMethods resultSet) throws SQLException {
try {
CachedResultSetMetaDataImpl cachedResultSetMetaDataImpl;
if (cachedMetaData == null) {
cachedResultSetMetaDataImpl = new CachedResultSetMetaDataImpl();
resultSet.getColumnDefinition().buildIndexMapping();
resultSet.initializeWithMetadata();
if (resultSet instanceof UpdatableResultSet)
((UpdatableResultSet)resultSet).checkUpdatability();
resultSet.populateCachedMetaData((CachedResultSetMetaData)cachedResultSetMetaDataImpl);
this.resultSetMetadataCache.put(sql, cachedResultSetMetaDataImpl);
} else {
resultSet.getColumnDefinition().initializeFrom((ColumnDefinition)cachedResultSetMetaDataImpl);
resultSet.initializeWithMetadata();
if (resultSet instanceof UpdatableResultSet)
((UpdatableResultSet)resultSet).checkUpdatability();
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getStatementComment() {
return this.session.getProtocol().getQueryComment();
}
public void setStatementComment(String comment) {
this.session.getProtocol().setQueryComment(comment);
}
public void transactionBegun() {
synchronized (getConnectionMutex()) {
if (this.connectionLifecycleInterceptors != null)
this.connectionLifecycleInterceptors.stream().forEach(ConnectionLifecycleInterceptor::transactionBegun);
}
}
public void transactionCompleted() {
synchronized (getConnectionMutex()) {
if (this.connectionLifecycleInterceptors != null)
this.connectionLifecycleInterceptors.stream().forEach(ConnectionLifecycleInterceptor::transactionCompleted);
}
}
public boolean storesLowerCaseTableName() {
return this.session.getServerSession().storesLowerCaseTableNames();
}
public ExceptionInterceptor getExceptionInterceptor() {
return this.exceptionInterceptor;
}
public boolean isServerLocal() throws SQLException {
try {
synchronized (getConnectionMutex()) {
return this.session.isServerLocal((Session)getSession());
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public int getSessionMaxRows() {
synchronized (getConnectionMutex()) {
return this.session.getSessionMaxRows();
}
}
public void setSessionMaxRows(int max) throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (this.session.getSessionMaxRows() != max) {
this.session.setSessionMaxRows(max);
this.session.execSQL(null, "SET SQL_SELECT_LIMIT=" + ((this.session.getSessionMaxRows() == -1) ? "DEFAULT" : (String)Integer.valueOf(this.session.getSessionMaxRows())), -1, null, false, (ProtocolEntityFactory)this.nullStatementResultSetFactory, null, false);
}
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setSchema(String schema) throws SQLException {
try {
checkClosed();
if (this.propertySet.getEnumProperty(PropertyKey.databaseTerm).getValue() == PropertyDefinitions.DatabaseTerm.SCHEMA)
setDatabase(schema);
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public String getSchema() throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
return (this.propertySet.getEnumProperty(PropertyKey.databaseTerm).getValue() == PropertyDefinitions.DatabaseTerm.SCHEMA) ? this.database : null;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void abort(Executor executor) throws SQLException {
try {
SecurityManager sec = System.getSecurityManager();
if (sec != null)
sec.checkPermission(ABORT_PERM);
if (executor == null)
throw SQLError.createSQLException(Messages.getString("Connection.26"), "S1009", getExceptionInterceptor());
executor.execute(new Runnable() {
public void run() {
try {
ConnectionImpl.this.abortInternal();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
});
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
try {
synchronized (getConnectionMutex()) {
SecurityManager sec = System.getSecurityManager();
if (sec != null)
sec.checkPermission(SET_NETWORK_TIMEOUT_PERM);
if (executor == null)
throw SQLError.createSQLException(Messages.getString("Connection.26"), "S1009", getExceptionInterceptor());
checkClosed();
executor.execute(new NetworkTimeoutSetter(this, milliseconds));
}
return;
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
private static class NetworkTimeoutSetter implements Runnable {
private final WeakReference<JdbcConnection> connRef;
private final int milliseconds;
public NetworkTimeoutSetter(JdbcConnection conn, int milliseconds) {
this.connRef = new WeakReference<>(conn);
this.milliseconds = milliseconds;
}
public void run() {
JdbcConnection conn = this.connRef.get();
if (conn != null)
synchronized (conn.getConnectionMutex()) {
((NativeSession)conn.getSession()).setSocketTimeout(this.milliseconds);
}
}
}
public int getNetworkTimeout() throws SQLException {
try {
synchronized (getConnectionMutex()) {
checkClosed();
return this.session.getSocketTimeout();
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Clob createClob() {
try {
return new Clob(getExceptionInterceptor());
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Blob createBlob() {
try {
return new Blob(getExceptionInterceptor());
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public NClob createNClob() {
try {
return new NClob(getExceptionInterceptor());
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public SQLXML createSQLXML() throws SQLException {
try {
return new MysqlSQLXML(getExceptionInterceptor());
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isValid(int timeout) throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (isClosed())
return false;
try {
try {
pingInternal(false, timeout * 1000);
} catch (Throwable t) {
try {
abortInternal();
} catch (Throwable throwable) {}
return false;
}
} catch (Throwable t) {
return false;
}
return true;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public ClientInfoProvider getClientInfoProviderImpl() throws SQLException {
try {
synchronized (getConnectionMutex()) {
if (this.infoProvider == null) {
String clientInfoProvider = this.propertySet.getStringProperty(PropertyKey.clientInfoProvider).getStringValue();
try {
try {
this.infoProvider = (ClientInfoProvider)Util.getInstance(clientInfoProvider, new Class[0], new Object[0],
getExceptionInterceptor());
} catch (CJException ex) {
if (ex.getCause() instanceof ClassCastException)
try {
this.infoProvider = (ClientInfoProvider)Util.getInstance("com.mysql.cj.jdbc." + clientInfoProvider, new Class[0], new Object[0],
getExceptionInterceptor());
} catch (CJException e) {
throw SQLExceptionsMapping.translateException(e, getExceptionInterceptor());
}
}
} catch (ClassCastException cce) {
throw SQLError.createSQLException(Messages.getString("Connection.ClientInfoNotImplemented", new Object[] { clientInfoProvider }), "S1009",
getExceptionInterceptor());
}
this.infoProvider.initialize(this, this.props);
}
return this.infoProvider;
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public void setClientInfo(String name, String value) throws SQLClientInfoException {
try {
getClientInfoProviderImpl().setClientInfo(this, name, value);
} catch (SQLClientInfoException ciEx) {
throw ciEx;
} catch (SQLException|CJException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
public void setClientInfo(Properties properties) throws SQLClientInfoException {
try {
getClientInfoProviderImpl().setClientInfo(this, properties);
} catch (SQLClientInfoException ciEx) {
throw ciEx;
} catch (SQLException|CJException sqlEx) {
SQLClientInfoException clientInfoEx = new SQLClientInfoException();
clientInfoEx.initCause(sqlEx);
throw clientInfoEx;
}
}
public String getClientInfo(String name) throws SQLException {
try {
return getClientInfoProviderImpl().getClientInfo(this, name);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Properties getClientInfo() throws SQLException {
try {
return getClientInfoProviderImpl().getClientInfo(this);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
try {
throw SQLError.createSQLFeatureNotSupportedException();
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
try {
throw SQLError.createSQLFeatureNotSupportedException();
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public <T> T unwrap(Class<T> iface) throws SQLException {
try {
try {
return iface.cast(this);
} catch (ClassCastException cce) {
throw SQLError.createSQLException("Unable to unwrap to " + iface.toString(), "S1009",
getExceptionInterceptor());
}
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public boolean isWrapperFor(Class<?> iface) throws SQLException {
try {
checkClosed();
return iface.isInstance(this);
} catch (CJException cJException) {
throw SQLExceptionsMapping.translateException(cJException, getExceptionInterceptor());
}
}
public NativeSession getSession() {
return this.session;
}
public String getHostPortPair() {
return this.origHostInfo.getHostPortPair();
}
public void handleNormalClose() {
try {
close();
} catch (SQLException e) {
ExceptionFactory.createException(e.getMessage(), e);
}
}
public void handleReconnect() {
createNewIO(true);
}
public void handleCleanup(Throwable whyCleanedUp) {
cleanup(whyCleanedUp);
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\jdbc\ConnectionImpl.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.builder;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BandseiteType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungChargeListeType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.BeschichtungIstdatenType;
import com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml.SchichtTypEnum;
import java.io.StringWriter;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
public class BeschichtungIstdatenTypeBuilder
{
public static String marshal(BeschichtungIstdatenType beschichtungIstdatenType)
throws JAXBException
{
JAXBElement<BeschichtungIstdatenType> jaxbElement = new JAXBElement<>(new QName("TESTING"), BeschichtungIstdatenType.class , beschichtungIstdatenType);
StringWriter stringWriter = new StringWriter();
return stringWriter.toString();
}
private BandseiteType bandseite;
private Double beschichteteLaenge;
private BeschichtungChargeListeType beschichtungChargeListe;
private String beschichtungsmaschine;
private Double farbmesslaenge;
private Double farbmusterAWert;
private Double farbmusterAWertMax;
private Double farbmusterAWertMin;
private Double farbmusterAWertSoll;
private Double farbmusterAWertSollMax;
private Double farbmusterAWertSollMin;
private Double farbmusterBWert;
private Double farbmusterBWertMax;
private Double farbmusterBWertMin;
private Double farbmusterBWertSoll;
private Double farbmusterBWertSollMax;
private Double farbmusterBWertSollMin;
private Double farbmusterLWert;
private Double farbmusterLWertMax;
private Double farbmusterLWertMin;
private Double farbmusterLWertSoll;
private Double farbmusterLWertSollMax;
private Double farbmusterLWertSollMin;
private String lokaleStoffNr;
private Double nassdickeMittelwert;
private Integer schichtNr;
private Integer schichtNrVonBandmitte;
private SchichtTypEnum schichtTyp;
private String stoffNr;
private Double trockendickeMittelwert;
private Double trockendickeMittelwertRandAntriebsseite;
private Double trockendickeMittelwertRandBedienseite;
public BeschichtungIstdatenTypeBuilder setBandseite(BandseiteType value)
{
this.bandseite = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setBeschichteteLaenge(Double value)
{
this.beschichteteLaenge = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setBeschichtungChargeListe(BeschichtungChargeListeType value)
{
this.beschichtungChargeListe = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setBeschichtungsmaschine(String value)
{
this.beschichtungsmaschine = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmesslaenge(Double value)
{
this.farbmesslaenge = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWert(Double value)
{
this.farbmusterAWert = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWertMax(Double value)
{
this.farbmusterAWertMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWertMin(Double value)
{
this.farbmusterAWertMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWertSoll(Double value)
{
this.farbmusterAWertSoll = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWertSollMax(Double value)
{
this.farbmusterAWertSollMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterAWertSollMin(Double value)
{
this.farbmusterAWertSollMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWert(Double value)
{
this.farbmusterBWert = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWertMax(Double value)
{
this.farbmusterBWertMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWertMin(Double value)
{
this.farbmusterBWertMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWertSoll(Double value)
{
this.farbmusterBWertSoll = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWertSollMax(Double value)
{
this.farbmusterBWertSollMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterBWertSollMin(Double value)
{
this.farbmusterBWertSollMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWert(Double value)
{
this.farbmusterLWert = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWertMax(Double value)
{
this.farbmusterLWertMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWertMin(Double value)
{
this.farbmusterLWertMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWertSoll(Double value)
{
this.farbmusterLWertSoll = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWertSollMax(Double value)
{
this.farbmusterLWertSollMax = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setFarbmusterLWertSollMin(Double value)
{
this.farbmusterLWertSollMin = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setLokaleStoffNr(String value)
{
this.lokaleStoffNr = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setNassdickeMittelwert(Double value)
{
this.nassdickeMittelwert = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setSchichtNr(Integer value)
{
this.schichtNr = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setSchichtNrVonBandmitte(Integer value)
{
this.schichtNrVonBandmitte = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setSchichtTyp(SchichtTypEnum value)
{
this.schichtTyp = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setStoffNr(String value)
{
this.stoffNr = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setTrockendickeMittelwert(Double value)
{
this.trockendickeMittelwert = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setTrockendickeMittelwertRandAntriebsseite(Double value)
{
this.trockendickeMittelwertRandAntriebsseite = value;
return this;
}
public BeschichtungIstdatenTypeBuilder setTrockendickeMittelwertRandBedienseite(Double value)
{
this.trockendickeMittelwertRandBedienseite = value;
return this;
}
public BeschichtungIstdatenType build()
{
BeschichtungIstdatenType result = new BeschichtungIstdatenType();
result.setBandseite(bandseite);
result.setBeschichteteLaenge(beschichteteLaenge);
result.setBeschichtungChargeListe(beschichtungChargeListe);
result.setBeschichtungsmaschine(beschichtungsmaschine);
result.setFarbmesslaenge(farbmesslaenge);
result.setFarbmusterAWert(farbmusterAWert);
result.setFarbmusterAWertMax(farbmusterAWertMax);
result.setFarbmusterAWertMin(farbmusterAWertMin);
result.setFarbmusterAWertSoll(farbmusterAWertSoll);
result.setFarbmusterAWertSollMax(farbmusterAWertSollMax);
result.setFarbmusterAWertSollMin(farbmusterAWertSollMin);
result.setFarbmusterBWert(farbmusterBWert);
result.setFarbmusterBWertMax(farbmusterBWertMax);
result.setFarbmusterBWertMin(farbmusterBWertMin);
result.setFarbmusterBWertSoll(farbmusterBWertSoll);
result.setFarbmusterBWertSollMax(farbmusterBWertSollMax);
result.setFarbmusterBWertSollMin(farbmusterBWertSollMin);
result.setFarbmusterLWert(farbmusterLWert);
result.setFarbmusterLWertMax(farbmusterLWertMax);
result.setFarbmusterLWertMin(farbmusterLWertMin);
result.setFarbmusterLWertSoll(farbmusterLWertSoll);
result.setFarbmusterLWertSollMax(farbmusterLWertSollMax);
result.setFarbmusterLWertSollMin(farbmusterLWertSollMin);
result.setLokaleStoffNr(lokaleStoffNr);
result.setNassdickeMittelwert(nassdickeMittelwert);
result.setSchichtNr(schichtNr);
result.setSchichtNrVonBandmitte(schichtNrVonBandmitte);
result.setSchichtTyp(schichtTyp);
result.setStoffNr(stoffNr);
result.setTrockendickeMittelwert(trockendickeMittelwert);
result.setTrockendickeMittelwertRandAntriebsseite(trockendickeMittelwertRandAntriebsseite);
result.setTrockendickeMittelwertRandBedienseite(trockendickeMittelwertRandBedienseite);
return result;
}
}
|
package other;
import java.util.ArrayList;
import org.junit.Test;
/**
* Sieve of Eratosthenes
* @author szhou
*
*/
public class AllPrimes {
public ArrayList<Integer> sieve(int a) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (a < 2) {
return res;
}
ArrayList<Boolean> sieve = new ArrayList<Boolean>();
sieve.add(false);
sieve.add(false);
for (int i = 2; i <= a; i++) {
sieve.add(true);
}
for (int i = 0; i <= Math.sqrt(a); i++) {
System.out.println("**** " + i);
if (sieve.get(i) == true) {
for (int j = 2; j * i <= a; j++) {
System.out.println("set " + i * j + " to false");
sieve.set(i * j, false);
}
}
}
for (int i = 2; i < sieve.size(); i++) {
if (sieve.get(i) == true) {
res.add(i);
}
}
return res;
}
@Test
public void test() {
ArrayList<Integer> res = sieve(100);
System.out.println(res.size());
for(Integer i : res) {
System.out.println(i + " ");
}
}
}
|
package com.diozero.devices.sandpit;
/*-
* #%L
* Organisation: diozero
* Project: diozero - Core
* Filename: VL6180.java
*
* This file is part of the diozero project. More information about this project
* can be found at https://www.diozero.com/.
* %%
* Copyright (C) 2016 - 2023 diozero
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
import java.nio.ByteOrder;
import java.util.Date;
import java.util.GregorianCalendar;
import org.tinylog.Logger;
import com.diozero.api.I2CDevice;
import com.diozero.api.I2CDeviceInterface.I2CMessage;
import com.diozero.api.RuntimeIOException;
import com.diozero.devices.DistanceSensorInterface;
import com.diozero.util.SleepUtil;
/**
* References:
* <ul>
* <li><a href=
* "https://www.st.com/resource/en/datasheet/vl6180.pdf">Datasheet</a></li>
* <li><a href=
* "https://www.st.com/resource/en/application_note/dm00122600-vl6180x-basic-ranging-application-note-stmicroelectronics.pdf">Application
* notes</a></li>
* <li><a href=
* "https://github.com/sparkfun/SparkFun_ToF_Range_Finder-VL6180_Arduino_Library/blob/master/src/SparkFun_VL6180X.cpp">SparkFun
* C++ implementation</a></li>
* <li><a href=
* "https://github.com/pololu/vl6180x-arduino/blob/master/VL6180X.cpp">Pololu
* C++ implementation</a></li>
* <li><a href=
* "https://github.com/adafruit/Adafruit_CircuitPython_VL6180X">Adafruit Python
* implementation</a></li>
* </ul>
*/
public class VL6180 implements DistanceSensorInterface {
// Register addresses
// Identification
private static final int IDENTIFICATION_MODEL_ID = 0x0000;
private static final int IDENTIFICATION_MODEL_REV_MAJOR = 0x0001;
private static final int IDENTIFICATION_MODEL_REV_MINOR = 0x0002;
private static final int IDENTIFICATION_MODULE_REV_MAJOR = 0x0003;
private static final int IDENTIFICATION_MODULE_REV_MINOR = 0x0004;
private static final int IDENTIFICATION_DATE = 0x0006; // 16-bit value
private static final int IDENTIFICATION_TIME = 0x0008; // 16-bit value
// System setup
private static final int SYSTEM_MODE_GPIO0 = 0x0010;
private static final int SYSTEM_MODE_GPIO1 = 0x0011;
private static final int SYSTEM_HISTORY_CTRL = 0x0012;
private static final int SYSTEM_INTERRUPT_CONFIG_GPIO = 0x0014;
private static final int SYSTEM_INTERRUPT_CLEAR = 0x0015;
private static final int SYSTEM_FRESH_OUT_OF_RESET = 0x0016;
private static final int SYSTEM_GROUPED_PARAMETER_HOLD = 0x0017;
// Range setup
private static final int SYSRANGE_START = 0x0018;
private static final int SYSRANGE_THRESH_HIGH = 0x0019;
private static final int SYSRANGE_THRESH_LOW = 0x001A;
private static final int SYSRANGE_INTERMEASUREMENT_PERIOD = 0x001B;
private static final int SYSRANGE_MAX_CONVERGENCE_TIME = 0x001C;
private static final int SYSRANGE_CROSSTALK_COMPENSATION_RATE = 0x001E;
private static final int SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x0021;
private static final int SYSRANGE_EARLY_CONVERGENCE_ESTIMATE = 0x0022;
private static final int SYSRANGE_PART_TO_PART_RANGE_OFFSET = 0x0024;
private static final int SYSRANGE_RANGE_IGNORE_VALID_HEIGHT = 0x0025;
private static final int SYSRANGE_RANGE_IGNORE_THRESHOLD = 0x0026;
private static final int SYSRANGE_MAX_AMBIENT_LEVEL_MULT = 0x002C;
private static final int SYSRANGE_RANGE_CHECK_ENABLES = 0x002D;
private static final int SYSRANGE_VHV_RECALIBRATE = 0x002E;
private static final int SYSRANGE_VHV_REPEAT_RATE = 0x0031;
// Ambient Light Sensor
private static final int SYSALS_START = 0x0038;
private static final int SYSALS_THRESH_HIGH = 0x003A;
private static final int SYSALS_THRESH_LOW = 0x003C;
private static final int SYSALS_INTERMEASUREMENT_PERIOD = 0x003E;
private static final int SYSALS_ANALOGUE_GAIN = 0x003F;
private static final int SYSALS_INTEGRATION_PERIOD = 0x0040;
// Results
private static final int RESULT_RANGE_STATUS = 0x004D;
private static final int RESULT_ALS_STATUS = 0x004E;
private static final int RESULT_INTERRUPT_STATUS_GPIO = 0x004F;
private static final int RESULT_ALS_VAL = 0x0050;
private static final int RESULT_HISTORY_BUFFER = 0x0052;
private static final int RESULT_RANGE_VAL = 0x0062;
private static final int RESULT_RANGE_RAW = 0x0064;
private static final int RESULT_RANGE_RETURN_RATE = 0x0066;
private static final int RESULT_RANGE_REFERENCE_RATE = 0x0068;
private static final int RESULT_RANGE_RETURN_SIGNAL_COUNT = 0x006C;
private static final int RESULT_RANGE_REFERENCE_SIGNAL_COUNT = 0x0070;
private static final int RESULT_RANGE_RETURN_AMB_COUNT = 0x0074;
private static final int RESULT_RANGE_REFERENCE_AMB_COUNT = 0x0078;
private static final int RESULT_RANGE_RETURN_CONV_TIME = 0x007C;
private static final int RESULT_RANGE_REFERENCE_CONV_TIME = 0x0080;
private static final int READOUT_AVERAGING_SAMPLE_PERIOD = 0x010A;
private static final int FIRMWARE_BOOTUP = 0x0119;
private static final int FIRMWARE_RESULT_SCALER = 0x0120;
private static final int I2C_SLAVE_DEVICE_ADDRESS = 0x0212;
private static final int INTERLEAVED_MODE_ENABLE = 0x02A3;
private static final int DEFAULT_ADDRESS = 0x29;
public static final byte VL6180_MODEL_ID = (byte) 0xb4;
private I2CDevice device;
private short modelId;
private short modelMajor;
private short modelMinor;
private short moduleMajor;
private short moduleMinor;
private Date manufactureDateTime;
private int manufacturePhase;
public VL6180() {
device = I2CDevice.builder(DEFAULT_ADDRESS).setByteOrder(ByteOrder.BIG_ENDIAN).build();
init();
modelId = (short) (readByte(IDENTIFICATION_MODEL_ID) & 0xff);
modelMajor = (short) (readByte(IDENTIFICATION_MODEL_REV_MAJOR) & 0x07);
modelMinor = (short) (readByte(IDENTIFICATION_MODEL_REV_MINOR) & 0x07);
moduleMajor = (short) (readByte(IDENTIFICATION_MODULE_REV_MAJOR) & 0x07);
moduleMinor = (short) (readByte(IDENTIFICATION_MODULE_REV_MINOR) & 0x07);
int id_date = readShort(IDENTIFICATION_DATE) & 0xffff;
int year = (id_date >> 12) & 0xf;
int month = (id_date >> 8) & 0xf;
int day_of_month = (id_date >> 3) & 0x1f;
manufacturePhase = id_date & 0x07;
int time = (readShort(IDENTIFICATION_TIME) & 0xffff) * 2;
manufactureDateTime = new GregorianCalendar(2010 + year, month - 1, day_of_month - 1, time / 60 / 60,
(time / 60) % 60, time % 60).getTime();
}
public int getModelId() {
return modelId;
}
public short getModelMajor() {
return modelMajor;
}
public short getModelMinor() {
return modelMinor;
}
public short getModuleMajor() {
return moduleMajor;
}
public short getModuleMinor() {
return moduleMinor;
}
public Date getManufactureDateTime() {
return manufactureDateTime;
}
public int getManufacturePhase() {
return manufacturePhase;
}
private void init() {
if (readByte(SYSTEM_FRESH_OUT_OF_RESET) == 1) {
Logger.debug("initialising...");
// Mandatory : private registers
writeByte(0x207, 0x01);
writeByte(0x208, 0x01);
writeByte(0x096, 0x00);
writeByte(0x097, 0xFD);
writeByte(0x0E3, 0x01);
writeByte(0x0E4, 0x03);
writeByte(0x0E5, 0x02);
writeByte(0x0E6, 0x01);
writeByte(0x0E7, 0x03);
writeByte(0x0F5, 0x02);
writeByte(0x0D9, 0x05);
writeByte(0x0DB, 0xCE);
writeByte(0x0DC, 0x03);
writeByte(0x0DD, 0xF8);
writeByte(0x09F, 0x00);
writeByte(0x0A3, 0x3C);
writeByte(0x0B7, 0x00);
writeByte(0x0BB, 0x3C);
writeByte(0x0B2, 0x09);
writeByte(0x0CA, 0x09);
writeByte(0x198, 0x01);
writeByte(0x1B0, 0x17);
writeByte(0x1AD, 0x00);
writeByte(0x0FF, 0x05);
writeByte(0x100, 0x05);
writeByte(0x199, 0x05);
writeByte(0x1A6, 0x1B);
writeByte(0x1AC, 0x3E);
writeByte(0x1A7, 0x1F);
writeByte(0x030, 0x00);
}
writeByte(SYSTEM_FRESH_OUT_OF_RESET, 0);
SleepUtil.sleepMillis(10);
// Recommended : Public registers - See data sheet for more detail
// Enables polling for 'New Sample ready' when measurement completes
writeByte(SYSTEM_MODE_GPIO1, 0x10);
// Set the averaging sample period (compromise between lower noise and increased
// execution time)
writeByte(READOUT_AVERAGING_SAMPLE_PERIOD, 0x30);
// Sets the light and dark gain (upper nibble). Dark gain should not be changed.
writeByte(SYSALS_ANALOGUE_GAIN, 0x46);
// Sets the # of range measurements after which auto calibration of system is
// performed
writeByte(SYSRANGE_VHV_REPEAT_RATE, 0xFF);
// Set ALS integration time to 100ms
writeByte(0x0041, 0x63);
// Perform a single temperature calibration of the ranging sensor
// TODO Check for completion by waiting for the bit to be cleared
writeByte(SYSRANGE_VHV_RECALIBRATE, 0x01);
// Optional: Public registers - See data sheet for more detail
// Set default ranging inter-measurement period to 100ms
writeByte(SYSRANGE_INTERMEASUREMENT_PERIOD, 0x09);
// Set default ALS inter-measurement period to 500ms
writeByte(SYSALS_INTERMEASUREMENT_PERIOD, 0x31);
// Configures interrupt on 'New Sample Ready threshold event'
// writeByte(SYSTEM_INTERRUPT_CONFIG_GPIO, 0x24);
writeByte(SYSTEM_INTERRUPT_CONFIG_GPIO, 0x04);
}
private byte readByte(int register) {
byte[] buffer = new byte[3];
I2CMessage[] messages = new I2CMessage[2];
messages[0] = new I2CMessage(I2CMessage.I2C_M_WR, 2);
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
messages[1] = new I2CMessage(I2CMessage.I2C_M_RD, 1);
device.readWrite(messages, buffer);
return buffer[2];
}
private short readShort(int register) {
byte[] buffer = new byte[4];
I2CMessage[] messages = new I2CMessage[2];
messages[0] = new I2CMessage(I2CMessage.I2C_M_WR, 2);
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
messages[1] = new I2CMessage(I2CMessage.I2C_M_RD, 2);
device.readWrite(messages, buffer);
return (short) ((buffer[2] << 8) | (buffer[3] & 0xff));
}
private void writeByte(int register, int b) {
/*-
byte[] buffer = new byte[3];
I2CMessage[] messages = new I2CMessage[1];
messages[0] = new I2CMessage(I2CMessage.I2C_M_WR, 3);
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
buffer[2] = (byte) b;
device.readWrite(messages, buffer);
*/
byte[] buffer = new byte[3];
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
buffer[2] = (byte) b;
device.writeBytes(buffer);
}
private void writeShort(int register, int s) {
/*-
byte[] buffer = new byte[4];
I2CMessage[] messages = new I2CMessage[1];
messages[0] = new I2CMessage(I2CMessage.I2C_M_WR, 4);
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
buffer[2] = (byte) ((s >> 8) & 0xff);
buffer[3] = (byte) (s & 0xff);
device.readWrite(messages, buffer);
*/
byte[] buffer = new byte[4];
buffer[0] = (byte) ((register >> 8) & 0xff);
buffer[1] = (byte) (register & 0xff);
buffer[2] = (byte) ((s >> 8) & 0xff);
buffer[3] = (byte) (s & 0xff);
device.writeBytes(buffer);
}
@Override
public void close() {
device.close();
}
@Override
public float getDistanceCm() throws RuntimeIOException {
writeByte(SYSTEM_INTERRUPT_CLEAR, 0b101);
// Start single-shot mode
writeByte(SYSRANGE_START, 0b01);
byte interrupt_status;
long start_ms = System.currentTimeMillis();
do {
interrupt_status = readByte(RESULT_INTERRUPT_STATUS_GPIO);
} while ((interrupt_status & 0x04) == 0 && System.currentTimeMillis() - start_ms < 1000);
return (readByte(RESULT_RANGE_VAL) & 0xff) / 10f;
}
}
|
package com.hikki.sergey.montecarlo.component;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hikki.sergey.montecarlo.R;
import static android.util.TypedValue.COMPLEX_UNIT_SP;
public class ProjectDurationView extends LinearLayout {
private Context mContext;
private Resources mResources;
private TextView mTitleView;
private EditText mYearValue;
private TextView mErrorTextView;
public ProjectDurationView(Context context) {
super(context, null);
mContext = context;
mResources = getResources();
this.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
this.setOrientation(LinearLayout.VERTICAL);
this.setPadding(0, getDps(8), 0, 0);
mTitleView = new TextView(mContext);
mTitleView.setFocusable(true);
mTitleView.setText(mResources.getString(R.string.project_duration));
mTitleView.setTextColor(Color.BLACK);
mTitleView.setTextSize(COMPLEX_UNIT_SP, 14);
mTitleView.setPadding(getDps(8),0, getDps(8), 0);
LinearLayout subLayout = new LinearLayout(mContext);
subLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
subLayout.setOrientation(LinearLayout.HORIZONTAL);
subLayout.setGravity(Gravity.CENTER_VERTICAL);
subLayout.setPadding(getDps(8),0,getDps(8), 0);
mYearValue = new EditText(mContext);
mYearValue.setEms(4);
mYearValue.setSingleLine();
mYearValue.setText("1");
mYearValue.setTextSize(COMPLEX_UNIT_SP, 14);
mYearValue.setHint("99 лет...");
mYearValue.setInputType(InputType.TYPE_CLASS_NUMBER);
mYearValue.setScrollX(OVER_SCROLL_IF_CONTENT_SCROLLS);
mErrorTextView = new ErrorTextView(mContext);
Divider divider = new Divider(mContext, Divider.HORIZONTAL);
this.addView(mTitleView);
this.addView(subLayout);
subLayout.addView(mYearValue);
subLayout.addView(mErrorTextView);
this.addView(divider);
}
public ProjectDurationView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public int getYears(){
int n = 1;
if (!mYearValue.getText().equals("")){
try{
if(mYearValue != null) {
Integer i = Integer.valueOf(mYearValue.getText().toString());
n = i.intValue();
}
mErrorTextView.setVisibility(GONE);
} catch (Exception e){
mErrorTextView.setVisibility(VISIBLE);
}
}
return n;
}
private int getDps(int pixels){
float scale = mResources.getDisplayMetrics().density;
int dpAsPixels = (int) (pixels*scale + 0.5f);
return dpAsPixels;
}
public EditText getYearValue() {
return mYearValue;
}
public void showHideErrorMess(CharSequence s){
Log.i("ErrorMess", "ProjectDuration: "+s.toString());
if (s.toString().equals("0") || s.toString().equals("") || s.charAt(0) == '0'){
mErrorTextView.setVisibility(VISIBLE);
} else{
mErrorTextView.setVisibility(GONE);
}
}
}
|
package com.stackroute.activitystream.servicesbackend.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.springframework.stereotype.Component;
@Component
@Entity
public class UserCircle {
@Id
private String userCircleId;
private String circleId;
private String emailId;
//Where are subscribe field and date of joing field?
public String getUserCircleId() {
return userCircleId;
}
public void setUserCircleId(String userCircleId) {
this.userCircleId = userCircleId;
}
public String getCircleId() {
return circleId;
}
public void setCircleId(String circleId) {
this.circleId = circleId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}
|
package adt.queue.nodes;
import adt.queue.nodes.FullNode;
import adt.queue.nodes.Node;
import adt.queue.nodes.NullNode;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class NullNodeTests {
private NullNode<Object> nullNode;
@Before
public void setUp() {
this.nullNode = new NullNode<>();
}
@Test(expected = AssertionError.class)
public void testGetElementThrowsAssertionError() {
nullNode.getElement();
}
@Test(expected = AssertionError.class)
public void testSetNextNodeThrowsAssertionError() {
nullNode.setNextNode(new NullNode<>());
}
@Test(expected = AssertionError.class)
public void testGetNextNodeThrowsAssertionError() {
nullNode.getNextNode();
}
@Test
public void testAmountOfNodesFromHereTillTheEndIs0() {
assertTrue(nullNode.getAmountOfNodesFromHereTillTheEnd() == 0);
}
@Test
public void testDoesNotHaveNextNode() {
assertFalse(nullNode.hasNext());
}
@Test
public void testAddNullElementToTailTopReturnsFullNodeAsTop() {
Node<Object> top = nullNode.addElementToTailTop(null);
assertTrue(top instanceof FullNode);
}
}
|
package bdda;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import exception.ReqException;
import exception.SGBDException;
public class HeapFile {
private RelDef relation;
// TODO peut etre qu'il faut mettre un une liste avec toutes les pages (fichiers) associés à cette relation
// TODO puis mette ce numl de page en pararmetre de createNewOnDisk()
public RelDef getPointeur() {
return relation;
}
public void setPointeur(RelDef relation) {
this.relation = relation;
}
/**
* Gerer la creation du fichier disque correspondant et le rajout d’une
* HeaderPage « vide » a ce fichier
*
* @throws ReqException,SGBDException
* @throws IOException
*/
public void createNewOnDisk() throws IOException, ReqException, SGBDException {
// On creer un nouveau fichier qui correspond a l'id donner par le relation(qui
// correspond la relation concerne)
try {
DiskManager.getInstance().createFile(relation.getFileIdx());
PageId newHeaderPage = new PageId(relation.getFileIdx(), 0);
// Pour ajouter une page on a besoin d'une nouvelle page qui correspond a la
// HeaderPage
// l'identifiant de la headerpage sera toujours 0 car il s'agit
// de la premiere page du fichier
DiskManager.getInstance().addPage(relation.getFileIdx(), newHeaderPage);
ByteBuffer bufferNewHeaderPage = BufferManager.getInstance().getPage(newHeaderPage);
HeaderPageInfo headerPageInfo = new HeaderPageInfo();
headerPageInfo.setDataPageCount(0);
headerPageInfo.writeToBuffer(bufferNewHeaderPage);
// Pas plutot mettre le type dirty en int ?
// Comme dans les exercices vu en amphi ?
BufferManager.getInstance().freePage(newHeaderPage, true);
} catch (IOException e) {
throw new SGBDException("Erreur au niveau de la creation du fichier sur le disque (HeapFile)");
}
}
/**
* Cette methode doit remplir l'argument oPageId avec l'identifiant d'une page
* de donnees sur laquelle il reste des cases disponibles. Si cela n'est pas le
* cas, la methode gere le rajout d'une page (libre) et l'actualisation des
* informations de la Header Page.
*/
private void getFreePageId(PageId oPageId) throws SGBDException {
oPageId.setFileIdx(relation.getFileIdx());
try {
PageId headerpage = new PageId(relation.getFileIdx(), 0);
ByteBuffer bufferHeaderPage = BufferManager.getInstance().getPage(headerpage);
HeaderPageInfo headerPageI = new HeaderPageInfo();
headerPageI.readFromBuffer(bufferHeaderPage);
//System.out.println(headerPageI.getListePages().size() + " " + headerPageI.getDataPageCount());
boolean slotDisponible = false;
for (DataPage d : headerPageI.getListePages()) {
if (d.getFreeSlots() > 0) {
oPageId.setPageIdx(d.getPageIdx());
BufferManager.getInstance().freePage(headerpage, false);
slotDisponible = true;
break;
}
}
if (!(slotDisponible)) {
PageId newpid = new PageId();
DiskManager.getInstance().addPage(relation.getFileIdx(), newpid);
oPageId.setPageIdx(newpid.getPageIdx());
/*
System.out.println("SlotCount : " + relation.getSlotCount());
System.out.println("RecordSize : " + relation.getRecordSize());
int nbSlotsLibres = Constantes.pageSize / relation.getRecordSize();
nbSlotsLibres = Constantes.pageSize - nbSlotsLibres;
nbSlotsLibres = nbSlotsLibres / relation.getRecordSize();
System.out.println("nbSlotsLibres : " + nbSlotsLibres);
*/
//System.out.println("nbSlotLibres : " + (Constantes.pageSize - relation.getSlotCount()) / relation.getRecordSize());
//System.out.println((Constantes.pageSize - relation.getSlotCount()) / relation.getRecordSize());
//System.out.println(relation.getSlotCount());
headerPageI.addDataPage(new DataPage(oPageId.getPageIdx(), relation.getSlotCount()));
headerPageI.writeToBuffer(bufferHeaderPage);
BufferManager.getInstance().freePage(headerpage, true);
ByteBuffer nouvellePage = BufferManager.getInstance().getPage(newpid);
// Ecrire une sequence de 0 au debut de la page (bytemap) pour signifier que
// toutes les cases sont vides
nouvellePage.position(0);
for (int i = 0; i < relation.getSlotCount(); i++) {
nouvellePage.put((byte) 0);
}
BufferManager.getInstance().freePage(newpid, true);
}
} catch (IOException e) {
throw new SGBDException("Erreur d'I/O lors de la creation d'une page (HeapFile)");
}
}
/**
* actualise les informations dans la Header Page suite a l’occupation d’une des
* cases disponible sur une page
*
* @param iPageId de la page a modifier
* @throws SGBDException
*/
private void updateHeaderWithTakenSlot(PageId iPageId) throws SGBDException {
PageId headerPage = new PageId(relation.getFileIdx(), 0);
try {
ByteBuffer bufferHeaderPage = BufferManager.getInstance().getPage(headerPage);
HeaderPageInfo hpi = new HeaderPageInfo();
hpi.readFromBuffer(bufferHeaderPage);
boolean pageTrouver = false;
for (DataPage d : hpi.getListePages()) {
if (d.getPageIdx() == iPageId.getPageIdx()) {
// d.setPageIdx(iPageId.getPageIdx());
// d.setFreeSlots((d.getFreeSlots() + 1)); -Faux
d.setFreeSlots((d.getFreeSlots() - 1));
pageTrouver = true;
break;
}
}
if (pageTrouver) {
hpi.writeToBuffer(bufferHeaderPage);
BufferManager.getInstance().freePage(headerPage, true);
} else {
throw new SGBDException("La page n'a pas été trouvée (il va manquer un appel à freePage dans le BufferManager)");
}
} catch (SGBDException e) {
e.printStackTrace();
throw new SGBDException("Erreur d'I/O lors de la creation d'une page (HeapFile)");
}
}
/**
* Cette methode prend en argument un Record, un buffer (=une page en « format
* buffer ») et l’indice d’une case dans la page. Elle doit ecrire le Record
* dans le buffer a la position (offset) qui va bien – a vous de calculer cette
* position, en fonction de l’indice de la case, la taille du record, et sans
* oublier la presence de la bytemap au debut du buffer (rappel : la taille de
* la bytemap est donnee par la variable slotCount de la RelDef).
*
* @param iRecord
* @param ioBuffer
* @param iSlotIdx
*/
private void writeRecordInBuffer(Record iRecord, ByteBuffer ioBuffer, int iSlotIdx) {
long positionDebutByteMap = relation.getSlotCount();
ioBuffer.position(relation.getSlotCount() + (iSlotIdx * relation.getRecordSize()));
for (int i = 0; i < iRecord.getValues().size(); i++) {
String valeur = iRecord.getValues().get(i);
String type = relation.getType().get(i);
if (type.equals("int")) {
ioBuffer.putInt(Integer.parseInt(valeur));
} else if (type.equals("float")) {
ioBuffer.putFloat(Float.parseFloat(valeur));
} else if (type.substring(0, 6).equals("string")) {
int taille = Integer.parseInt(type.substring(6));
for (int j = 0; j < taille; j++) {
ioBuffer.putChar(valeur.charAt(j));
}
}
}
}
/**
* Cette methode prend en argument un Record et un PageId et ecrit le record
* dans la page comme suit : - d’abord, le buffer de la page est obtenu via le
* BufferManager. - ensuite, nous cherchons, avec la bytemap, une case
* disponible ; nous supposons qu’une telle case existe a l’appel de cette
* methode ! - puis nous ecrivons le Record avec writeRecordInBuffer - puis nous
* actualisons la bytemap pour specifier que la case est « occupee » (octet de
* valeur 1) - enfin, nous liberons le buffer de la page aupres du BufferManager
*
* @param iRecord
* @param iPageId
* @return Rid
* @throws SGBDException
*/
private Rid insertRecordInPage(Record iRecord, PageId iPageId) throws SGBDException {
try {
ByteBuffer bufferPage = BufferManager.getInstance().getPage(iPageId);
bufferPage.position(0);
int slotId = 0;
for (int i = 0; i < relation.getSlotCount(); i++) {
// TODO Modification ici
if (bufferPage.get(i) == 0) {
slotId = i;
bufferPage.position(i);
// Attention peut être faux byte en int
bufferPage.put((byte) 1);
writeRecordInBuffer(iRecord, bufferPage, i);
// A verifier appel update
//updateHeaderWithTakenSlot(iPageId);
break;
}
}
BufferManager.getInstance().freePage(iPageId, true);
return new Rid(iPageId, slotId);
} catch (SGBDException e) {
e.printStackTrace();
throw new SGBDException("Erreur d'insertion du record : pas de place libre sur la page");
}
}
public Record readRecordFromBuffer(ByteBuffer iBuffer, int iSlotIdx) {
Record record = new Record();
iBuffer.position(relation.getSlotCount() + (iSlotIdx * relation.getRecordSize()));
for (int i = 0; i < relation.getNbColonne(); i++) {
String type = relation.getType().get(i);
if (type.equals("int")) {
record.addValue(Integer.toString(iBuffer.getInt()));
} else if (type.equals("float")) {
record.addValue(Float.toString(iBuffer.getFloat()));
} else if (type.substring(0, 6).equals("string")) {
int taille = Integer.parseInt(type.substring(6));
StringBuilder sb = new StringBuilder();
for (int j = 0; j < taille; j++) {
sb.append(iBuffer.getChar());
}
record.addValue(sb.toString());
}
}
/*
for(String s : record.getValues()){
System.out.print(s + " ");
}
*/
return record;
}
public ArrayList<Record> getRecordsOnPage(PageId iPageId) {
ArrayList<Record> listRecord = new ArrayList<Record>();
try {
ByteBuffer bfPage = BufferManager.getInstance().getPage(iPageId);
bfPage.rewind();
/*
while(bfPage.hasRemaining()){
System.out.print(bfPage.get());
}
*/
for (int i = 0; i < relation.getSlotCount(); i++) {
if (bfPage.get(i) == 1) {
//System.out.println("ok" + i);
listRecord.add(readRecordFromBuffer(bfPage, i));
}
}
BufferManager.getInstance().freePage(iPageId, false);
return listRecord;
} catch (SGBDException e) {
e.printStackTrace();
}
return listRecord;
}
public ArrayList<PageId> getDataPagesIds() {
ArrayList<PageId> listPageId = new ArrayList<PageId>();
try {
PageId headerpage = new PageId(relation.getFileIdx(), 0);
ByteBuffer bufferHeaderPage;
bufferHeaderPage = BufferManager.getInstance().getPage(headerpage);
HeaderPageInfo headerPageI = new HeaderPageInfo();
headerPageI.readFromBuffer(bufferHeaderPage);
for (DataPage d : headerPageI.getListePages()) {
listPageId.add(new PageId(relation.getFileIdx(), d.getPageIdx()));
}
BufferManager.getInstance().freePage(headerpage, false);
// TODO on a ajouté un freePage ici
return listPageId;
} catch (SGBDException e) {
e.printStackTrace();
}
return listPageId;
}
/**
* Insere un record dans une page
*
* @param iRecord
* @return Rid
*/
public Rid insertRecord(Record iRecord) {
PageId pid = new PageId();
try {
getFreePageId(pid);
updateHeaderWithTakenSlot(pid);
return insertRecordInPage(iRecord, pid);
} catch (SGBDException e) {
e.printStackTrace();
}
return null;
}
}
|
package mapgenerator.domain;
import javafx.scene.paint.Color;
/**
* Class is used to store a biome-color-pair so that choosing biome colors when drawing is easier. Every biome is paired with one color,
* but this color may change during the execution of the program.
*/
public class BiomeColor {
String biome;
Color color;
public BiomeColor(String biome, Color color) {
this.biome = biome;
this.color = color;
}
public String getBiome() {
return biome;
}
public void setBiome(String biome) {
this.biome = biome;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
|
package Animacja;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JPanel;
public class Rysunek extends JPanel implements Runnable
{
private Thread runner=null;
private Obiekty obiekt = new Obiekty();
int x_dom=300;
int x_drzew=1300;
int samochod_x=-405;
int ptak_x=-100;
int ptak_y=100;
int ptak_krok=1;
int ptak_kierunek=1;
boolean ptak_siad=false;
boolean samochod_start=false;
boolean ptak=true;
//---------------------------
void play()
{
if (runner==null)
{
runner=new Thread(this);
runner.start();
}
}
//---------------------------
void stop()
{
if (runner!=null)
{
runner=null;
}
}
//---------------------------
public void run()
{
//Thread ten=Thread.currentThread();
while (runner != null) {
if (ptak == true) {
ptak_y+=ptak_krok;
if (ptak_y>=249)
{
ptak_krok=-1;
}
else if (ptak_y<150)
{
ptak_krok=1;
}
if (ptak_x > x_dom + 200) {
ptak_kierunek = 0;
samochod_start = true;
}
if (ptak_x < x_dom) {
ptak_kierunek = 1;
}
if (ptak_kierunek == 1)
{
ptak_x += 1;
}
else
{
ptak_x -= 1;
}
}
if(samochod_start==true){
if(samochod_x>x_dom && samochod_x+150<x_drzew){
x_dom-=4;
ptak_x-=4;
x_drzew-=4;
}
else
{
samochod_x+=4;
}
}
if(samochod_x>1100){
ptak_kierunek=1;
ptak=false;
if (ptak_x>=x_drzew+50) ptak_siad=true;
else ptak_x++;
}
if(ptak_siad==true){
if(ptak_y<210)
ptak_y++;
}
repaint();
try
{
Thread.sleep(20);
}
catch (InterruptedException e)
{
}
}}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
obiekt.tlo(g);
obiekt.domek(g,x_dom);
obiekt.drzewko(g, x_drzew);
obiekt.samochod(g,samochod_x);
if(ptak_siad==true)
obiekt.ptaksiada(g,ptak_x,ptak_y);
else{
if(ptak_kierunek==1)
obiekt.ptakprawo(g,ptak_x,ptak_y);
else obiekt.ptaklewo(g,ptak_x,ptak_y);
}
}
}
|
package jour29;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Exception1 {
public static void main(String[] args) throws FileNotFoundException {
// C/ Yeni dosyayi programa ekleyiniz
FileInputStream yeni = new FileInputStream("C/");
/*Exception in thread "main" java.io.FileNotFoundException: C (Le fichier spécifié est introuvable)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at jour29.Exception1.main(Exception1.java:12)*/
}
}
|
package ru.job4j.servlets.webarchitecturejsp.presentation;
import com.fasterxml.jackson.databind.ObjectMapper;
import ru.job4j.servlets.webarchitecturejsp.logic.CitiesDB;
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 java.io.IOException;
@WebServlet("/countryservlet")
public class CountriesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String toJson = objectMapper.writeValueAsString(CitiesDB.getInstance().getCountries());
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
resp.getWriter().write(toJson);
}
}
|
/**
* Logback: the reliable, generic, fast and flexible logging framework.
*
* Copyright (C) 1999-2006, QOS.ch
*
* This library is free software, you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation.
*/
package test;
import junit.framework.TestCase;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
/**
*
* A test case that issues the typical calls
* that an application using log4j 1.3 would do.
*
* @author Ceki Gülcü
* @author Sébastien Pennec
*/
public class Log4j13Calls extends TestCase {
public static final Logger logger = Logger.getLogger(Log4j12Calls.class);
public void testLog() {
MDC.put("key", "value1");
logger.trace("Trace level can be noisy");
logger.debug("Entering application");
logger.info("Violets are blue");
logger.warn("Here is a warning");
logger.info("The answer is {}.", new Integer(42));
logger.info("Number: {} and another one: {}.", new Integer(42), new Integer(24));
logger.error("Exiting application", new Exception("just testing"));
MDC.remove("key");
MDC.clear();
}
}
|
package com.mysql.cj.xdevapi;
import com.mysql.cj.exceptions.WrongArgumentException;
import com.mysql.cj.protocol.ResultStreamer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.function.Supplier;
public class SqlMultiResult implements SqlResult, ResultStreamer {
private Supplier<SqlResult> resultStream;
private List<SqlResult> pendingResults = new ArrayList<>();
private SqlResult currentResult;
public SqlMultiResult(Supplier<SqlResult> resultStream) {
this.resultStream = resultStream;
this.currentResult = resultStream.get();
}
private SqlResult getCurrentResult() {
if (this.currentResult == null)
throw new WrongArgumentException("No active result");
return this.currentResult;
}
public boolean nextResult() {
if (this.currentResult == null)
return false;
try {
if (ResultStreamer.class.isAssignableFrom(this.currentResult.getClass()))
((ResultStreamer)this.currentResult).finishStreaming();
} finally {
this.currentResult = null;
}
this.currentResult = (this.pendingResults.size() > 0) ? this.pendingResults.remove(0) : this.resultStream.get();
return (this.currentResult != null);
}
public void finishStreaming() {
if (this.currentResult == null)
return;
if (ResultStreamer.class.isAssignableFrom(this.currentResult.getClass()))
((ResultStreamer)this.currentResult).finishStreaming();
SqlResult pendingRs = null;
while ((pendingRs = this.resultStream.get()) != null) {
if (ResultStreamer.class.isAssignableFrom(pendingRs.getClass()))
((ResultStreamer)pendingRs).finishStreaming();
this.pendingResults.add(pendingRs);
}
}
public boolean hasData() {
return getCurrentResult().hasData();
}
public long getAffectedItemsCount() {
return getCurrentResult().getAffectedItemsCount();
}
public Long getAutoIncrementValue() {
return getCurrentResult().getAutoIncrementValue();
}
public int getWarningsCount() {
return getCurrentResult().getWarningsCount();
}
public Iterator<Warning> getWarnings() {
return getCurrentResult().getWarnings();
}
public int getColumnCount() {
return getCurrentResult().getColumnCount();
}
public List<Column> getColumns() {
return getCurrentResult().getColumns();
}
public List<String> getColumnNames() {
return getCurrentResult().getColumnNames();
}
public long count() {
return getCurrentResult().count();
}
public List<Row> fetchAll() {
return getCurrentResult().fetchAll();
}
public Row next() {
return getCurrentResult().next();
}
public boolean hasNext() {
return getCurrentResult().hasNext();
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\xdevapi\SqlMultiResult.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import Arquivo.EscreverArquivo;
import Model.Usuario;
import daoGeneric.HibernateControl;
public class Teste {
public static void main(String[] args) throws IOException {
EscreverArquivo escritor = new EscreverArquivo();
String nome = "Kariny";
System.out.println(escritor);
//escritor.escrever(nome, "qwe124519");
//escritor.escrever("Silvia", "qwe124519");
//System.out.println(escritor);
//escritor.escrever("Kariny3", "qwe124519");
escritor.salvarObjeto("Solange Meire", "qwe124519");
escritor.salvarObjeto("Marco Antonio", "qwe124519");
escritor.salvarObjeto("Kariny", "qwe124519");
escritor.salvarObjeto("Nadur Henrique", "qwe124519");
ArrayList<Usuario> usuarios = new ArrayList<>();
usuarios = escritor.lerObjeto();
//escritor.deletarObjeto(nome);
for(Usuario u: usuarios){
System.out.println(u.getNome());
}
}
}
|
package com.rofour.baseball.dao.waybill.mapper;
import javax.inject.Named;
import com.rofour.baseball.dao.waybill.bean.WaybillProblemBean;
/**
* 异常件
*
* @author wuzhiquan
*
*/
@Named("waybillProblemMapper")
public interface WaybillProblemMapper {
/**
* 查询异常件
*
* @param orderId
* @return
* @author wuzhiquan
*/
WaybillProblemBean getWaybillProblem(Long orderId);
/**
* 删除异常件
*
* @param problemId
* @return
* @author wuzhiquan
*/
int deleteWaybillProblem(Long problemId);
}
|
package sim.uf;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class UFDAOHibernate implements UnidadeFornecimentoDAO {
private Session session;
@Override
public void salvar(UnidadeFornecimento uf) {
this.session.save(uf);
}
@Override
public void excluir(UnidadeFornecimento uf) {
this.session.delete(uf);
}
@Override
public void atualizar(UnidadeFornecimento uf) {
this.session.update(uf);
}
@Override
public UnidadeFornecimento carregar(Integer codigo) {
return (UnidadeFornecimento)
this.session.get(UnidadeFornecimento.class, codigo);
}
@Override
public UnidadeFornecimento buscarUF(String descricao) {
String hql = "select u from UnidadeFornecimento u where u.descricao = :descricao";
Query q = this.session.createQuery(hql);
q.setString(descricao, "descricao");
return (UnidadeFornecimento) q.uniqueResult();
}
@Override
public List<UnidadeFornecimento> listar() {
return
this.session.createCriteria(UnidadeFornecimento.class).list();
}
public Session getSession() {
return session;
}
public void setSession(Session sessao) {
this.session = sessao;
}
}
|
package com.anywaycloud.common.utils;
import java.io.File;
import java.io.IOException;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Zhang Yu
*
*/
public class FileTransfer {
public static File multipartToFile(MultipartFile multipart)
throws IllegalStateException, IOException {
File convFile = new File(multipart.getOriginalFilename());
multipart.transferTo(convFile);
return convFile;
}
}
|
package com.involves.converter;
public abstract class ConverterFactory {
public abstract PojoConverter getConverter(Type type);
}
|
package uk.gov.hmcts.jsonstore;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static uk.gov.hmcts.common.CommonAssertions.applyCommonAssertionsOnBasicData;
import static uk.gov.hmcts.common.CommonAssertions.applyCommonAssertionsOnExtendedData;
import static uk.gov.hmcts.common.CommonAssertions.applyCommonAssertionsOnOverriddenData;
import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import uk.gov.hmcts.befta.data.HttpTestData;
public class JsonFileStoreWithInheritanceTest {
private JsonFileStoreWithInheritance fileStore;
private static final String DIRECTORIES_TEST_DATA_RESOURCE_FOLDER = "framework-test-data/json-store-test-data";
private static final String INHERITANCE_TEST_DATA_RESOURCE_FOLDER = "framework-test-data/inheritance-test-data";
private static final String ID_KEY = "_guid_";
private static final String FILE_IN_ROOT_ID = "File-In-Root";
private static final String FILE_IN_SUBDIRECTORY_ID = "File-In-Subdirectory";
private static final String FILE_WITHOUT_INHERITANCE = "Simple-Data-Without-Inheritance";
private static final String FILE_WITH_INHERITANCE = "Simple-Data-With-Inheritance";
private static final String FILE_WITH_OVERRIDES = "Simple-Data-With-Overrides";
@Test
public void shouldBuildFileStoreForAllSubdirectoriesSuccessfully() throws Exception {
fileStore = new JsonFileStoreWithInheritance(getFileFromResource(DIRECTORIES_TEST_DATA_RESOURCE_FOLDER));
fileStore.buildObjectStore();
final JsonNode rootNode = fileStore.getRootNode();
assertEquals(2, rootNode.size());
List<Object> ids = Arrays.asList(rootNode.get(0).get(ID_KEY).asText(), rootNode.get(1).get(ID_KEY).asText());
assertTrue(ids.contains(FILE_IN_ROOT_ID));
assertTrue(ids.contains(FILE_IN_SUBDIRECTORY_ID));
}
@Test
public void shouldGetObjectWithIdForBasicDataSuccessfully() throws Exception {
fileStore = new JsonFileStoreWithInheritance(getFileFromResource(INHERITANCE_TEST_DATA_RESOURCE_FOLDER));
final HttpTestData data = fileStore.getObjectWithId(FILE_WITHOUT_INHERITANCE, HttpTestData.class);
applyCommonAssertionsOnBasicData(data);
}
@Test
public void shouldGetObjectWithIdForInheritedDataSuccessfully() throws Exception {
fileStore = new JsonFileStoreWithInheritance(getFileFromResource(INHERITANCE_TEST_DATA_RESOURCE_FOLDER));
final HttpTestData data = fileStore.getObjectWithId(FILE_WITH_INHERITANCE, HttpTestData.class);
applyCommonAssertionsOnExtendedData(data);
}
@Test
public void shouldGetObjectWithIdForOverriddenDataSuccessfully() throws Exception {
fileStore = new JsonFileStoreWithInheritance(getFileFromResource(INHERITANCE_TEST_DATA_RESOURCE_FOLDER));
final HttpTestData data = fileStore.getObjectWithId(FILE_WITH_OVERRIDES, HttpTestData.class);
applyCommonAssertionsOnOverriddenData(data);
}
private File getFileFromResource(String location) {
URL url = ClassLoader.getSystemResource(location);
return new File(url.getFile());
}
}
|
package com.xulizao.jmeter;
/**
* Created by xulz on 17-4-6.
*/
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;
public class JavaRequestFull extends AbstractJavaSamplerClient {
@Override
public void setupTest(JavaSamplerContext context){
// TODO: initial the Test Case
// 数据准备阶段,在每个线程初始化时执行
super.setupTest(context);
}
@Override
public Arguments getDefaultParameters() {
Arguments params = new Arguments();
// TODO: define/set parameters from GUI
// 提供默认值等
return params;
}
@Override
public SampleResult runTest(JavaSamplerContext arg0) {
// TODO Auto-generated method stub
SampleResult result = new SampleResult();
boolean success = true;
result.sampleStart();
// Write your test code here.
//
result.sampleEnd();
result.setSuccessful(success); //可以稍后验证结果
// 进一步的结果验证
// 返回具体结果
return result;
}
@Override
public void teardownTest(JavaSamplerContext context){
// TODO: 清除工作
//
super.teardownTest(context);
}
public static void main(String[] args) {
Arguments params = new Arguments();
params.addArgument("project", "demo");
JavaSamplerContext context = new JavaSamplerContext(params);
JavaRequestFull test = new JavaRequestFull();
test.setupTest(context);
test.runTest(context);
test.teardownTest(context);
}
}
|
package com.example.model;
public class KeepInformation {
private static int idUser;
private static String role;
public static int getIdUser() {
return idUser;
}
public static void setIdUser(int idUser) {
KeepInformation.idUser = idUser;
}
public static String getRole() {
return role;
}
public static void setRole(String role) {
KeepInformation.role = role;
}
}
|
package cn.itcast;
public class Test01 {
public static void main(String[] args) {
System.out.println("hello ,github!");
System.out.println("hello ,update git!");
System.out.println("hello ,update git 02!");
System.out.println("hello ,update git 03!");
System.out.println("hello ,update git 04!");
System.out.println("hello ,update git 06!");
System.out.println("hello ,update git 08!");
System.out.println("hello ,update git 07!");
System.out.println("hello ,update git 19!");
System.out.println("hello ,update git 11!");
System.out.println("hello ,update git 11! by lzd");
}
}
|
package com.lins.myzoom.controller.admin;
import com.lins.myzoom.pojo.Tag;
import com.lins.myzoom.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.naming.Binding;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
/**
* @ClassName TagController
* @Description TODO
* @Author lin
* @Date 2021/2/3 10:50
* @Version 1.0
**/
@Controller
@RequestMapping("/admin")
public class TagController {
@Autowired
private TagService tagService;
@GetMapping("/tags")
public String tags(@PageableDefault(size = 6,sort = {"id"},direction = Sort.Direction.DESC)Pageable pageable,
Model model,
HttpSession session){
model.addAttribute("user",session.getAttribute("user"));
model.addAttribute("page",tagService.listTag(pageable));
return "/admin/admin-tags";
}
@GetMapping("/tags/input")
public String input(Model model){
model.addAttribute("tag",new Tag());
return "/admin/admin-addtag";
}
@GetMapping("/tags/{id}/input")
public String editInput(@PathVariable Long id,Model model){
model.addAttribute("tag",tagService.getTag(id));
return "/admin/admin-addtag";
}
@PostMapping("/tags")
public String post(@Valid Tag tag, BindingResult result, RedirectAttributes attributes){
Tag tag1=tagService.getTagByName(tag.getName());
if(tag1!=null){
result.rejectValue("name","nameError","标签已存在");
}
if(result.hasErrors()){
return "/admin/admin-addtag";
}
Tag tag2=tagService.saveTag(tag);
if(tag2==null){
attributes.addFlashAttribute("message","添加失败");
}
else {
attributes.addFlashAttribute("message","添加成功");
}
return "redirect:/admin/tags";
}
@PostMapping("/tags/{id}")
public String editPost(@Valid Tag tag, BindingResult result,@PathVariable Long id, RedirectAttributes attributes){
Tag tag1=tagService.getTagByName(tag.getName());
if(tag1!=null){
result.rejectValue("name","nameError","标签已存在");
}
if(result.hasErrors()){
return "/admin/admin-addtag";
}
Tag tag2=tagService.updateTag(id,tag);
if(tag2==null){
attributes.addFlashAttribute("message","更新失败");
}
else {
attributes.addFlashAttribute("message","更新成功");
}
return "redirect:/admin/tags";
}
@GetMapping("/tags/{id}/delete")
public String delete(@PathVariable Long id,RedirectAttributes attributes){
tagService.deleteTag(id);
attributes.addFlashAttribute("message","删除成功");
return "redirect:/admin/tags";
}
}
|
package rabbitmq.bean;
import java.util.Date;
import java.util.HashMap;
import org.apache.log4j.Logger;
import rabbitmq.conf.MqQueueConfig;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import exception.ChannelClosedException;
/**
*
* @描述: 对rabbit mq 渠道的封装
* @版权: Copyright (c) 2019
* @公司: 思迪科技
* @作者: 严磊
* @版本: 1.0
* @创建日期: 2019年7月26日
* @创建时间: 上午9:12:34
*/
public class RabbitMqCha
{
/**
* 使用中
*/
public static final String status_used = "status_used";
/**
* 空闲,初始化的状态
*/
public static final String status_idel = "status_idel";
/**
* 空闲
*/
public static final String status_invalid = "status_invalid";
protected static Logger logger = Logger.getLogger(RabbitMqCha.class);
protected Channel cha;
protected String status = RabbitMqCha.status_idel;
//状态改变锁,通过对该对象加锁,来限制,不能异步(同时去调用)调用同一个对象的多个改变状态的方法。
protected Object statusLock = new Object();
//当前渠道最后被使用时的时间点(通过连接获取渠道时代表被使用)
protected volatile long IdleTime;
/**
* 当前渠道的状态
*/
protected boolean isClose = false;
/**
*
* @描述:获取渠道的最后使用时间点
* @作者:严磊
* @时间:2019年7月25日 下午7:51:40
* @return
*/
public long getIdleTime()
{
return IdleTime;
}
/**
*
* @描述:修改渠道状态由使用中变为***状态
* @作者:严磊
* @时间:2019年7月25日 下午7:46:39
* @return
*/
public boolean toBeIdel()
{
synchronized (statusLock)
{
if ( RabbitMqCha.status_used.equals(this.status) )
{
this.status = RabbitMqCha.status_idel;
return true;
}
else
{
return false;
}
}
}
/**
*
* @描述:修改渠道状态由***变为使用中状态,如果渠道不为空闲,返回false
* @作者:严磊
* @时间:2019年7月25日 下午7:46:39
* @return
*/
public boolean toBeUsed()
{
synchronized (statusLock)
{
if ( RabbitMqCha.status_idel.equals(this.status) )
{
this.status = RabbitMqCha.status_used;
return true;
}
else
{
return false;
}
}
}
/**
*
* @描述:修改渠道状态由***变为空闲状态
* @作者:严磊
* @时间:2019年7月25日 下午7:46:39
* @return
*/
public boolean idelToInvalid()
{
synchronized (statusLock)
{
if ( RabbitMqCha.status_idel.equals(this.status) )
{
this.status = RabbitMqCha.status_invalid;
return true;
}
else
{
return false;
}
}
}
/**
*
* @描述:修改渠道状态由使用中变为空闲状态
* @作者:严磊
* @时间:2019年7月25日 下午7:46:39
* @return
*/
public boolean usedToInvalid()
{
synchronized (statusLock)
{
if ( RabbitMqCha.status_used.equals(this.status) )
{
this.status = RabbitMqCha.status_invalid;
return true;
}
else
{
return false;
}
}
}
/**
*
* 描述: 构造方法,RabbitMqCha是对Channel对象的封装
* @param cha
* @throws Exception
*/
public RabbitMqCha(Channel cha) throws Exception
{
if ( cha == null )
{
throw new Exception("cha不能为空");
}
this.cha = cha;
}
/**
*
* @描述:关闭渠道
* @作者:严磊
* @时间:2019年7月25日 下午6:45:03
*/
public void closeCha()
{
try
{
if ( cha != null && cha.isOpen() )
{
cha.close();
cha = null;
}
}
catch (Exception e)
{
logger.error("关闭渠道出错", e);
}
}
//把渠道还到渠道池
/**
*
* @描述:重设渠道的最后使用时间
* @作者:严磊
* @时间:2019年7月25日 下午7:59:01
*/
public void reloadIdleTime()
{
IdleTime = new Date().getTime();
}
/**
*
* @描述:检查渠道是否是打开状态
* @作者:严磊
* @时间:2019年7月26日 上午8:59:05
* @return
*/
public boolean isOpen()
{
return this.cha.isOpen();
}
//发布消息
/**
*
* @描述:发布消息到交换机
* @作者:严磊
* @时间:2019年7月26日 上午9:07:30
* @param entity
* @throws Exception
*/
public void publish(MqRequestEntity entity) throws Exception
{
String queueName = entity.getQueueName();
// 获取队列信息
HashMap<String, String> queueInfo = MqQueueConfig.getQueueInfo(queueName);
String queueValue = queueInfo.get("value");
String type = queueInfo.get("type");
String exchange = queueInfo.get("exchange");
if ( !isOpen() )
{
throw new ChannelClosedException("渠道关闭了");
}
if ( type.equals("fanout") )
{
cha.basicPublish(exchange, "", MessageProperties.PERSISTENT_TEXT_PLAIN, JSONObject.toJSONString(entity)
.getBytes("GBK"));
}
else if ( type.equals("direct") )
{
cha.basicPublish(exchange, queueValue, null, JSONObject.toJSONString(entity).getBytes("GBK"));
}
else
{
cha.basicPublish("", queueValue, MessageProperties.PERSISTENT_TEXT_PLAIN, JSONObject.toJSONString(entity)
.getBytes("GBK"));
}
}
}
|
package com.leepc.chat.socket;
import com.alibaba.fastjson.JSON;
import com.leepc.chat.domain.Message;
import com.leepc.chat.service.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/ws/{uid}")
@Component
public class MyWebSocket {
private static Map<Integer, MyWebSocket> userMap;
private static int userCount;
private static MessageService messageService;
private Session webSocketSession;
private Integer uid;
private static Logger logger = LoggerFactory.getLogger(MyWebSocket.class);
@Autowired
public void setMessageService(MessageService m) {
MyWebSocket.messageService = m;
}
static {
userMap = new ConcurrentHashMap<>();
userCount = 0;
}
@OnOpen
public void onOpen(@PathParam(value = "uid") Integer param, Session session){
this.webSocketSession = session;
this.uid = param;
userMap.put(param, this);
logger.info("" + uid + "连接上了");
addOnlineCount();
logger.info("当前在线人数: " + userCount);
}
@OnClose
public void onClose() {
if (userMap.containsKey(uid)) {
userMap.remove(uid);
subOnlineCount();
logger.info(""+ uid + "断开连接...");
}
}
@OnMessage
public void onMessage(String message, Session session) {
if (!StringUtils.isEmpty(message)) {
logger.info("收到了消息: " + message);
Message msg = JSON.parseObject(message, Message.class);
if (msg.getFromId() == null)
msg.setFromId(uid);
Integer to = msg.getToId();
messageService.insert(msg);
try {
userMap.get(to).sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void sendToUser(Integer userId, String message) throws IOException {
if (userMap.containsKey(userId))
userMap.get(userId).sendMessage(message);
}
public static void sendToAll(String message) throws IOException {
for (Map.Entry<Integer, MyWebSocket> entry : userMap.entrySet()) {
Integer k = entry.getKey();
MyWebSocket v = entry.getValue();
v.sendMessage(message);
}
}
public void sendMessage(String message) throws IOException {
logger.info("给" + uid + "发送了消息");
this.webSocketSession.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return userCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.userCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.userCount--;
}
}
|
package com.edu.miusched.service.impl;
import com.edu.miusched.dao.StudentDao;
import com.edu.miusched.domain.Student;
import com.edu.miusched.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
StudentDao studentDao;
@Override
public Student save(Student student) {
return studentDao.save(student);
}
@Override
public Student getStudentByEmail(String email) {
return studentDao.findStudentByEmail(email);
}
@Override
public Student getStudentById(Long studentID) {
return studentDao.findStudentById(studentID);
}
@Override
public List<Student> getAllStudents() {
return studentDao.findAll();
}
@Override
public void deleteStudentById(Long id) {
studentDao.deleteById(id);
}
@Override
public void deleteStudentByStudentId(String studentId) {
studentDao.deleteStudentByStudentId(studentId);
}
}
|
package eu.tivian.musico.ui;
import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import eu.tivian.musico.R;
import eu.tivian.musico.SharedViewModel;
/**
* Setting dialog.
*/
public class SettingsDialogFragment extends DialogFragment {
/**
* The Last.fm username.
*/
private EditText username;
/**
* Chosen app language.
*/
private Spinner language;
/**
* Creates the settings dialog, which gives the option to change the language of the application
* and change which Last.fm user info should be shown in the app.
*
* @param savedInstanceState always {@code null}.
* @return a new {@link Dialog} instance to be displayed by the {@link Fragment}.
*/
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = requireActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialog_settings, null);
username = view.findViewById(R.id.et_username);
language = view.findViewById(R.id.spinner_language);
final SharedViewModel viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
viewModel.getLanguage().observe(this, pos -> language.setSelection(pos));
viewModel.getUsername().observe(this, login -> username.setText(login));
builder.setView(view).setTitle(R.string.title_settings)
.setNegativeButton(R.string.dialog_cancel, null)
.setPositiveButton(R.string.dialog_save, (dialog, which) -> {
viewModel.setLanguage(language.getSelectedItemPosition());
viewModel.setUsername(username.getText().toString());
});
return builder.create();
}
}
|
package com.xjf.wemall.service.pkg;
import java.util.HashMap;
import java.util.Map;
import org.junit.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import com.xjf.wemall.service.AllServiceTest;
import com.xjf.wemall.service.index.api.IndexService;
/**
* Unit test for simple App.
*/
public class Pkg extends AllServiceTest {
@Autowired
private IndexService indexService;
@Test
public void index() {
// 不可以
// Cat cat = new Cat();
}
public static void main(String[] arg) {
Map<String, String> hm = new HashMap<String, String>();
// hm.put("pkReferenceRule", "XSFW");
RestTemplate rest = new RestTemplate();
System.out.println(rest.postForObject("http://home.chexiang.com/wxRestFul/queryServicePriceInfoForRestFul", hm, String.class));
}
}
|
package org.nyer.sns.http.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* 拼装URL
*
* @author [[mailto:hzmaoyinjie@corp.netease.com][Mao Yinjie]]
*/
public class UrlBuilder {
/**
* initial url
*/
private String url;
/**
* 参数
*/
private Map<String, String> params = new HashMap<String, String>();
/**
* @param url initial url
*/
public UrlBuilder(String url) {
this.url = url;
}
/**
* 增加一个参数
*
* @param paramName 参数名称
* @param paramValue 参数值
* @return UrlBuilder本身
*/
public UrlBuilder add(String paramName, Object paramValue) {
String value = paramValue != null ? paramValue.toString() : "";
params.put(paramName, value);
return this;
}
/**
* 增加一组参数
*
* @param params 一组参数
* @return UrlBuilder本身
*/
public UrlBuilder add(Map<String, ? extends Object> params) {
for (Entry<String, ? extends Object> entry : params.entrySet()) {
add(entry.getKey(), entry.getValue());
}
return this;
}
/**
* 拼装url
*
* @param charset 对参数进行url encode时使用的编码
* @return 拼装好的url
*/
public String toUrl(String charset) {
try {
StringBuilder builder = new StringBuilder(url);
String separator = url.indexOf("?") == -1 ? "?" : "&";
for (Entry<String, String> entry : params.entrySet()) {
builder.append(separator).append(URLEncoder.encode(entry.getKey(), charset)).append("=").append(
URLEncoder.encode(entry.getValue(), charset));
separator = "&";
}
return builder.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
|
package com.lti.handson2;
import java.util.*;
public class DuplicateUnsortedARrayofStrings
{
static void remDuplicate(char str[],int length)
{
int index=0;
for(int i=0;i<length;i++)
{
int j;
for(j=0;j<i;j++)
{
if(str[i]==str[j])
{
break;
}
}
}
if(j==i)
{
str[index++]=str[i];
}
System.out.println(String.valueOf(Arrays.copyOf(str,index)));
}
public static void main(String[] args)
{
String info = "This is a good game";
char str[] = info.toCharArray();
int len = str.length;
remDuplicate(str, len);
}
}
|
package qslabs.com.introtabscreen;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity implements tab1.OnFragmentInteractionListener, tab2.OnFragmentInteractionListener, tab3.OnFragmentInteractionListener, tab4.OnFragmentInteractionListener, tab5.OnFragmentInteractionListener {
/**
* A PagerAdapter is used to generate and provide the pages
* displayed by the ViewPager manager (see class initialization below).
* PagerAdapter is used in cases where the number of
* pages is fixed; each sibling page is stored in memory.
* if the number of pages is variable, consider
* implementing a FragmentStatePagerAdapter, which reduces memory cost.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* a ViewPager is defined as a 'Layout manager that allows the user
* to flip left and right through pages of data'
* (https://developer.android.com/reference/android/support/v4/view/ViewPager.html).
* This is the standard implementation for achieving swipe navigation between fragments.
*/
private ViewPager mViewPager;
private TabLayout navigation_tab;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
/**
* A PageTransformer allows for animations to be applied to page views;
* The PageTransformer is invoked when the displayed page from the ViewPager
* is scrolled.
*/
mViewPager.setPageTransformer(false, new IntroPageTransformer());
navigation_tab = findViewById(R.id.navigation_tab); // navigation_tab serves to provide a visualization of the tab layout
navigation_tab.setupWithViewPager(mViewPager, true);
}
/**
* Required method override in order to
* implement OnFragmentInteractionListeners.
*/
@Override
public void onFragmentInteraction(Uri uri) {
}
/**
* Using the auto-populated SectionsPagerAdapter initialization
* generated by the 'Tabbed Activity' code-behind. Functions to return
* a fragment corresponding to one of the tabs.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
/**
* getItem instantiates the respective fragment;
* modify the cases to create the desired fragment order.
*/
@Override
public Fragment getItem(int position) {
switch(position)
{
case 0:
return tab1.newInstance(position);
case 1:
return tab2.newInstance(position);
case 2:
return tab3.newInstance(position);
case 3:
return tab4.newInstance(position);
case 4:
return tab5.newInstance(position);
default:
return tab1.newInstance(position);
}
}
/**
* Returns the total number of pages; ensure the count
* matches the number of cases above.
*/
@Override
public int getCount() {
return 5;
}
}
}
|
package com.tencent.mm.plugin.facedetect.ui;
import com.tencent.mm.plugin.facedetect.model.o;
import com.tencent.mm.sdk.platformtools.ah;
class FaceDetectPrepareUI$5 implements Runnable {
final /* synthetic */ FaceDetectPrepareUI iRf;
FaceDetectPrepareUI$5(FaceDetectPrepareUI faceDetectPrepareUI) {
this.iRf = faceDetectPrepareUI;
}
public final void run() {
ah.A(new 1(this, o.AT(FaceDetectPrepareUI.e(this.iRf))));
}
}
|
package com.kevinkuai.worm;
import java.util.List;
import com.kevinkuai.framework.Game;
import com.kevinkuai.framework.Graphics;
import com.kevinkuai.framework.Screen;
import com.kevinkuai.framework.Input.TouchEvent;
public class HighScoreScreen extends Screen {
String lines[] = new String[5];
public HighScoreScreen(Game game) {
super(game);
// TODO Auto-generated constructor stub
for (int i=0; i<5; i++){
lines[i]=" "+(i+1)+". "+Settings.highscores[i];
}
}
@Override
public void update(float deltaTime) {
// TODO Auto-generated method stub
List <TouchEvent> touch = game.getInput().getTouchEvents();
game.getInput().getKeyEvents();
int len = touch.size();
for (int i=0; i<len; i++){
TouchEvent te = touch.get(i);
if (te.type == TouchEvent.TOUCH_UP){
if (te.x <64 && te.y >416){
game.setScreen(new MainMenuScreen(game));
if (Settings.soundEnabled)
Assets.click.play(1);
return;
}
}
}
}
@Override
public void present(float deltaTime) {
// TODO Auto-generated method stub
Graphics g = game.getGraphics();
g.drawPixmap(Assets.background, 0, 0);
g.drawPixmap(Assets.mainMenu, 64, 20,0,42,196,42);
int y = 100;
for (int i = 0; i<5; i++){
drawText(g, lines[i], 20, y);
y+=50;
}
g.drawPixmap(Assets.buttons, 0, 416, 64, 64, 64, 64);
}
private void drawText(Graphics g, String line, int x, int y) {
// TODO Auto-generated method stub
int len = line.length();
for (int i =0; i<len; i++){
char c = line.charAt(i);
if (c == ' ') {
x += 20;
continue;
}
int srcX = 0;
int srcWidth = 0;
if (c == '.') {
srcX = 200;
srcWidth = 10;
}else{
srcX = (c - '0')*20;
srcWidth = 20;
}
g.drawPixmap(Assets.numbers, x, y, srcX, 0, srcWidth, 32);
x += srcWidth;
}
}
@Override
public void pause() {
// TODO Auto-generated method stub
}
@Override
public void resume() {
// TODO Auto-generated method stub
}
@Override
public void dispose() {
// TODO Auto-generated method stub
}
}
|
package com.yoeki.kalpnay.hrporatal.Benefits.PersonalBenefits;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import com.yoeki.kalpnay.hrporatal.R;
/**
* Created by IACE on 15-Sep-18.
*/
public class home_personalBenmefits extends AppCompatActivity {
ImageView personal_back;
WebView web_personalbenifits;
String str="<p><strong><span style=\"font-size: 16pt;\">Personal Benefits</span></strong></p>\n" +
"<div id=\"mntl-sc-block_1-0-19\" class=\"comp mntl-sc-block mntl-sc-block-html\">\n" +
"<p><span style=\"font-size: 12pt;\">Almost half the (medium and large) employers surveyed offered either a defined benefit or a defined contribution pension plan. About 75% offered health insurance, but almost all required some employee contribution towards the cost. It's not hard to look at the averages and see how your employer or your job offer measures up.</span></p>\n" +
"</div>\n" +
"<div id=\"mntl-sc-block_1-0-21\" class=\"comp mntl-sc-block mntl-sc-block-html\">\n" +
"<p><span style=\"font-size: 12pt;\">In addition, there is an increasing use of bonuses, perks, and incentives by employers to recruit and retain employees. Look at the companies rated the best places to work and you'll discover many offer health club memberships, flexible schedules, daycare, tuition reimbursement, and even on-site dry cleaning.</span></p>\n" +
"</div>";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_personal_benefit);
personal_back=findViewById(R.id.personal_back);
web_personalbenifits=findViewById(R.id.web_personalbenifits);
web_personalbenifits.loadDataWithBaseURL(null, str, "text/html", "UTF-8", null);
personal_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
import java.util.Date;
/**
* TYearDemand generated by hbm2java
*/
public class TYearDemand implements java.io.Serializable {
private TYearDemandId id;
private String uniqueid;
private String batchnum;
private Date createtime;
private String creator;
private String deptid;
private Long lastremain;
private Long oneqty;
private Long twoqty;
private Long threeqty;
private Long fourqty;
private Long fiveqty;
private Long sixqty;
private Long sevenqty;
private Long eightqty;
private Long nineqty;
private Long tenqty;
private Long elevenqty;
private String notes;
private Long twelveqty;
private Long currentyearqty;
public TYearDemand() {
}
public TYearDemand(TYearDemandId id, String uniqueid, String deptid) {
this.id = id;
this.uniqueid = uniqueid;
this.deptid = deptid;
}
public TYearDemand(TYearDemandId id, String uniqueid, String batchnum, Date createtime, String creator,
String deptid, Long lastremain, Long oneqty, Long twoqty, Long threeqty, Long fourqty, Long fiveqty,
Long sixqty, Long sevenqty, Long eightqty, Long nineqty, Long tenqty, Long elevenqty, String notes,
Long twelveqty, Long currentyearqty) {
this.id = id;
this.uniqueid = uniqueid;
this.batchnum = batchnum;
this.createtime = createtime;
this.creator = creator;
this.deptid = deptid;
this.lastremain = lastremain;
this.oneqty = oneqty;
this.twoqty = twoqty;
this.threeqty = threeqty;
this.fourqty = fourqty;
this.fiveqty = fiveqty;
this.sixqty = sixqty;
this.sevenqty = sevenqty;
this.eightqty = eightqty;
this.nineqty = nineqty;
this.tenqty = tenqty;
this.elevenqty = elevenqty;
this.notes = notes;
this.twelveqty = twelveqty;
this.currentyearqty = currentyearqty;
}
public TYearDemandId getId() {
return this.id;
}
public void setId(TYearDemandId id) {
this.id = id;
}
public String getUniqueid() {
return this.uniqueid;
}
public void setUniqueid(String uniqueid) {
this.uniqueid = uniqueid;
}
public String getBatchnum() {
return this.batchnum;
}
public void setBatchnum(String batchnum) {
this.batchnum = batchnum;
}
public Date getCreatetime() {
return this.createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getDeptid() {
return this.deptid;
}
public void setDeptid(String deptid) {
this.deptid = deptid;
}
public Long getLastremain() {
return this.lastremain;
}
public void setLastremain(Long lastremain) {
this.lastremain = lastremain;
}
public Long getOneqty() {
return this.oneqty;
}
public void setOneqty(Long oneqty) {
this.oneqty = oneqty;
}
public Long getTwoqty() {
return this.twoqty;
}
public void setTwoqty(Long twoqty) {
this.twoqty = twoqty;
}
public Long getThreeqty() {
return this.threeqty;
}
public void setThreeqty(Long threeqty) {
this.threeqty = threeqty;
}
public Long getFourqty() {
return this.fourqty;
}
public void setFourqty(Long fourqty) {
this.fourqty = fourqty;
}
public Long getFiveqty() {
return this.fiveqty;
}
public void setFiveqty(Long fiveqty) {
this.fiveqty = fiveqty;
}
public Long getSixqty() {
return this.sixqty;
}
public void setSixqty(Long sixqty) {
this.sixqty = sixqty;
}
public Long getSevenqty() {
return this.sevenqty;
}
public void setSevenqty(Long sevenqty) {
this.sevenqty = sevenqty;
}
public Long getEightqty() {
return this.eightqty;
}
public void setEightqty(Long eightqty) {
this.eightqty = eightqty;
}
public Long getNineqty() {
return this.nineqty;
}
public void setNineqty(Long nineqty) {
this.nineqty = nineqty;
}
public Long getTenqty() {
return this.tenqty;
}
public void setTenqty(Long tenqty) {
this.tenqty = tenqty;
}
public Long getElevenqty() {
return this.elevenqty;
}
public void setElevenqty(Long elevenqty) {
this.elevenqty = elevenqty;
}
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Long getTwelveqty() {
return this.twelveqty;
}
public void setTwelveqty(Long twelveqty) {
this.twelveqty = twelveqty;
}
public Long getCurrentyearqty() {
return this.currentyearqty;
}
public void setCurrentyearqty(Long currentyearqty) {
this.currentyearqty = currentyearqty;
}
}
|
package com.spring.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.UUID;
import org.apache.log4j.Logger;
public class GenerateUniqueIdentifier {
static final Logger log=Logger.getLogger(GenerateUniqueIdentifier.class);
public static Random random=new Random();
public synchronized static String getUniqueIdforTransaction(String MerchantId)
{
String uniqueId="";
try{
UUID myuuid = UUID.randomUUID();
long highbits = myuuid.getMostSignificantBits();
long lowbits = myuuid.getLeastSignificantBits();
byte[] bytes = ByteBuffer.allocate(16).putLong(highbits).putLong(lowbits).array();
BigInteger big = new BigInteger(bytes);
String numericUuid = big.toString().replace('-','1');
if(numericUuid.length()>19)
{
uniqueId=numericUuid.substring(0, 19);
}
else{
uniqueId=numericUuid;
}
}
catch(Exception e)
{
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
log.debug("Caught exception; during action : " + stack.toString());
uniqueId=String.valueOf(random.nextLong()).replace('-','1');
}
if(MerchantId!=null && MerchantId.trim().length()>0 )
{
uniqueId= MerchantId+uniqueId;
}
log.info("Unique Id Generated for Transaction is :"+uniqueId);
return uniqueId;
}
}
|
/*
* 2012-3 Red Hat Inc. and/or its affiliates and other contributors.
*
* 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.overlord.rtgov.call.trace.model;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
/**
* This abstract base class represents a node in the call
* trace tree.
*
*/
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({@Type(value=Call.class),
@Type(value=Task.class) })
@org.codehaus.enunciate.json.JsonType
public abstract class TraceNode {
private long _duration=0;
private int _percentage=0;
private Status _status=Status.Success;
private java.util.Map<String,String> _properties=new java.util.HashMap<String, String>();
/**
* This method returns the duration of the task.
*
* @return The duration
*/
public long getDuration() {
return (_duration);
}
/**
* This method sets the duration of the task.
*
* @param duration The duration
*/
public void setDuration(long duration) {
_duration = duration;
}
/**
* This method returns the percentage of time
* taken by this task within a parent call scope.
*
* @return The percentage
*/
public int getPercentage() {
return (_percentage);
}
/**
* This method sets the percentage of time
* taken by this task within a parent call scope.
*
* @param percentage The percentage
*/
public void setPercentage(int percentage) {
_percentage = percentage;
}
/**
* This method returns the status.
*
* @return The status
*/
public Status getStatus() {
return (_status);
}
/**
* This method sets the status.
*
* @param status The status
*/
public void setStatus(Status status) {
_status = status;
}
/**
* This method returns the properties of the task.
*
* @return The properties
*/
public java.util.Map<String,String> getProperties() {
return (_properties);
}
/**
* This method sets the properties of the task.
*
* @param properties The properties
*/
public void setProperties(java.util.Map<String,String> properties) {
_properties = properties;
}
/**
* This enumerated type represents the completion status
* of the call.
*
*/
public static enum Status {
/**
* Completed successfully.
*/
Success,
/**
* A problem occurred within the scope of the node.
*/
Warning,
/**
* Completed unsuccessfully.
*/
Fail
}
}
|
package com.tencent.mm.plugin.scanner.ui;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.MMFlipper.a;
class SelectScanModePanel$1 implements a {
final /* synthetic */ SelectScanModePanel mMm;
SelectScanModePanel$1(SelectScanModePanel selectScanModePanel) {
this.mMm = selectScanModePanel;
}
public final void dp(int i, int i2) {
x.v("MicroMsg.scanner.SelectScanModePanel", "onMeasure width:" + i + " height:" + i2 + " isMeasured:" + SelectScanModePanel.a(this.mMm));
if (!SelectScanModePanel.a(this.mMm) && i2 != 0 && i != 0) {
SelectScanModePanel.b(this.mMm);
SelectScanModePanel.a(this.mMm, i2);
SelectScanModePanel.b(this.mMm, i);
SelectScanModePanel.c(this.mMm);
}
}
}
|
package com.rsm.yuri.projecttaxilivredriver.domain.di;
import com.rsm.yuri.projecttaxilivredriver.TaxiLivreDriverAppModule;
import javax.inject.Singleton;
import dagger.Component;
/**
* Created by yuri_ on 12/01/2018.
*/
@Singleton
@Component(modules = {DomainModule.class, TaxiLivreDriverAppModule.class})
public interface DomainComponent {
}
|
package com.yz.git.sc.account.api.impl;
import com.yz.git.sc.account.api.ScAccountApi;
import com.yz.git.sc.account.common.message.Message;
import com.yz.git.sc.account.common.message.Messages;
import com.yz.git.sc.account.param.ProductInfo;
import com.yz.git.sc.account.service.ScAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author xuyang
* @date 2019/08/19
*/
@Slf4j
@Service
public class ScAccountApiImpl implements ScAccountApi{
@Autowired
ScAccountService scAccountService;
@Override
public Message<List<ProductInfo>> queryProductList() {
return null;
}
@Override
public Message<String> tryGetMsg() {
log.info("调用远程产品模块!");
String response = null;
try {
response = scAccountService.tryGetMsg();
} catch (Exception e) {
log.error("调用产品模块异常",e);
}
return Messages.success(response);
}
}
|
package com.argentinatecno.checkmanager.main.fragment_add.di;
import com.argentinatecno.checkmanager.CheckManagerAppModule;
import com.argentinatecno.checkmanager.lib.base.ImageLoader;
import com.argentinatecno.checkmanager.lib.di.LibsModule;
import com.argentinatecno.checkmanager.main.fragment_add.FragmentAddPresenter;
import com.argentinatecno.checkmanager.main.fragment_add.ui.FragmentAdd;
import javax.inject.Singleton;
import dagger.Component;
@Singleton
@Component(modules = {FragmentAddModule.class, LibsModule.class, CheckManagerAppModule.class})
public interface FragmentAddComponent {
void inject(FragmentAdd fragment);
ImageLoader getImageLoader();
FragmentAddPresenter getPresenter();
}
|
package edu.iit.cs445.StateParking.Objects;
public interface Visitor {
public int getVid();
public String getName() ;
public String getEmail();
public boolean KeywordMatch(String keyword);
public boolean isNull();
}
|
package ca.mohawk.jdw.shifty.desktopclient.auth;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: desktop-client
Developed By: Josh Maione (000320309)
*/
import ca.mohawk.jdw.shifty.clientapi.ShiftyClient;
import ca.mohawk.jdw.shifty.desktopclient.ui.UI;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
public class TitlePane extends BorderPane {
private final ShiftyClient.Config config;
private final Label nameLabel;
private final Label phoneLabel;
private final Label emailLabel;
public TitlePane(final ShiftyClient.Config config){
this.config = config;
getStylesheets().add(UI.css("titlePane"));
final Tooltip addressTip = new Tooltip();
addressTip.setText(
String.format(
"%d %s\n%s, %s",
config.company().address().unit(),
config.company().address().street(),
config.company().address().city(),
config.company().address().country()
)
);
nameLabel = new Label(config.company().name());
nameLabel.getStyleClass().add("name");
nameLabel.setTooltip(addressTip);
phoneLabel = new Label(config.company().phone());
emailLabel = new Label(config.company().email());
final VBox labels = new VBox();
labels.setAlignment(Pos.CENTER);
labels.getChildren().addAll(nameLabel, phoneLabel, emailLabel);
setCenter(labels);
}
}
|
package kr.co.toondra.web.sample.dao;
import java.util.HashMap;
import java.util.List;
import kr.co.toondra.base.dao.BaseDao;
import org.springframework.stereotype.Repository;
@Repository
public class SampleDao extends BaseDao {
public List<HashMap<String,Object>> getGetTogetherList(){
return selectList("sample.getMemberList");
}
public int insertComment(){
return insert("sample.insertComment");
}
public int insertComment2(){
return insert("sample.insertComment2");
}
}
|
package com.modnsolutions.bookfinder;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.text.HtmlCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.loader.app.LoaderManager;
import androidx.loader.content.Loader;
import com.bumptech.glide.Glide;
import com.modnsolutions.bookfinder.db.entity.BookEntity;
import com.modnsolutions.bookfinder.db.viewmodel.BookViewModel;
import com.modnsolutions.bookfinder.loader.BookDetailLoader;
import com.modnsolutions.bookfinder.utils.Utilities;
import org.json.JSONException;
import org.json.JSONObject;
public class BookDetailFragment extends Fragment implements
LoaderManager.LoaderCallbacks<JSONObject> {
private static final int LOADER_ID = 1;
private LoaderManager mLoaderManager;
private ImageView mBookImageView;
private TextView mTitleTextView;
private TextView mAuthorsTextView;
private TextView mPublisherTextView;
private TextView mPublicationDateTextView;
private TextView mPagesTextView;
private TextView mCategoriesTextView;
private TextView mDescriptionTextView;
private ProgressBar mProgressBar;
private LinearLayout mLinearLayout;
private BookViewModel mBookViewModel;
private BookEntity mBook;
private JSONObject mJSONBook;
public static final String FRAGMENT_TAG = BookDetailFragment.class.getCanonicalName();
public static final String BOOK_ID_EXTRA = "com.modnsolutions.bookfinder.BOOK_ID_EXTRA";
public BookDetailFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLoaderManager = LoaderManager.getInstance(this);
if (mLoaderManager.getLoader(LOADER_ID) != null)
mLoaderManager.initLoader(LOADER_ID, null, this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_book_detail, container, false);
mLinearLayout = root.findViewById(R.id.ll);
mBookImageView = root.findViewById(R.id.img_view_book);
mTitleTextView = root.findViewById(R.id.textview_book_title);
mAuthorsTextView = root.findViewById(R.id.textview_authors);
mPublisherTextView = root.findViewById(R.id.textview_publisher);
mPublicationDateTextView = root.findViewById(R.id.textview_publication_date);
mPagesTextView = root.findViewById(R.id.textview_pages);
mCategoriesTextView = root.findViewById(R.id.textview_categories);
mDescriptionTextView = root.findViewById(R.id.textview_book_description);
mProgressBar = root.findViewById(R.id.progress_bar);
mLinearLayout.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
Intent intent = new Intent();
Bundle bundle = getArguments();
if (bundle != null) {
intent.putExtra(SearchResultsFragment.QUERY_ID_EXTRA, bundle.getString(
SearchResultsFragment.QUERY_ID_EXTRA));
} else intent = getActivity().getIntent();
if (intent != null) {
// Find book in favorite. If it exist, display it, if not get book details from
// Google Books API.
mBookViewModel = ViewModelProviders.of(this).get(BookViewModel.class);
mBook = mBookViewModel.findFavorite(intent.getStringExtra(
SearchResultsFragment.QUERY_ID_EXTRA));
if (mBook != null) {
mProgressBar.setVisibility(View.INVISIBLE);
mLinearLayout.setVisibility(View.VISIBLE);
Glide.with(this)
.load(mBook.getImageLink())
.fitCenter()
.into(mBookImageView);
mBookImageView.setContentDescription(mBook.getTitle());
mTitleTextView.setText(mBook.getTitle());
mAuthorsTextView.setText(mBook.getAuthors());
mPublisherTextView.setText(mBook.getPublisher());
mPublicationDateTextView.setText(mBook.getPublishedDate());
mPagesTextView.setText(String.valueOf(mBook.getPageCount()));
mCategoriesTextView.setText(mBook.getCategories());
mDescriptionTextView.setText(HtmlCompat.fromHtml(mBook.getDescription(),0));
} else {
Bundle loaderBundle = new Bundle();
loaderBundle.putString(BOOK_ID_EXTRA, intent.getStringExtra(SearchResultsFragment
.QUERY_ID_EXTRA));
mLoaderManager.restartLoader(LOADER_ID, loaderBundle, this);
}
}
return root;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_bookmark, menu);
// Get bookmark icon
MenuItem bookmarkIcon = menu.getItem(1);
if (mBook != null) {
bookmarkIcon.setIcon(R.drawable.ic_bookmark_saved);
} else {
bookmarkIcon.setIcon(R.drawable.ic_bookmark_unsaved);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_bookmark:
// If book exist in favorite, remove it and change icon. Set mBook to null.
// Else add to favorite and change icon.
if (mBook != null) {
mBookViewModel.remove(mBook);
item.setIcon(R.drawable.ic_bookmark_unsaved);
Utilities.toastMessage(getContext(), mBook.getTitle()
+ " has been removed from your favorites.");
mBook = null;
} else {
if (mJSONBook != null) {
try {
BookEntity bookEntity = new BookEntity(mJSONBook.getString("id"),
mJSONBook.getString("title"),
mJSONBook.getString("publisher"),
mJSONBook.getString("publishedDate"),
Utilities.convertImageURL(mJSONBook.getJSONObject("imageLinks")
.getString("thumbnail")),
mJSONBook.getString("authors"),
mJSONBook.getInt("pageCount"),
mJSONBook.getString("categories"),
mJSONBook.getString("description"));
mBookViewModel.insert(bookEntity);
item.setIcon(R.drawable.ic_bookmark_saved);
Utilities.toastMessage(getContext(),
mJSONBook.getString("title")
+ " has been added to your favorites.");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return true;
}
return super.onOptionsItemSelected(item);
}
@NonNull
@Override
public Loader<JSONObject> onCreateLoader(int id, @Nullable Bundle args) {
String bookId = args.getString(BOOK_ID_EXTRA, null);
return new BookDetailLoader(getContext(), bookId);
}
@Override
public void onLoadFinished(@NonNull Loader<JSONObject> loader, JSONObject data) {
if (data != null) {
mJSONBook = data;
try {
mProgressBar.setVisibility(View.INVISIBLE);
mLinearLayout.setVisibility(View.VISIBLE);
Glide.with(this)
.load(Utilities.convertImageURL(data.getJSONObject("imageLinks")
.getString("thumbnail")))
.fitCenter()
.into(mBookImageView);
mBookImageView.setContentDescription(data.getString("title"));
mTitleTextView.setText(data.getString("title"));
mAuthorsTextView.setText(data.getString("authors"));
mPublisherTextView.setText(data.getString("publisher"));
mPublicationDateTextView.setText(data.getString("publishedDate"));
mPagesTextView.setText(String.valueOf(data.getInt("pageCount")));
mCategoriesTextView.setText(data.getString("categories"));
mDescriptionTextView.setText(HtmlCompat.fromHtml(data.getString("description"),
0));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public void onLoaderReset(@NonNull Loader<JSONObject> loader) {
}
}
|
package lesson11;
/**
* 11章長方形クラス
* @author t-hama
*
*/
public class Rectangle {
/**
* コンストラクタで大きさの指定がない場合に利用する初期値
*/
final int INITIAL_WIDTH = 20;
final int INITIAL_HEIGHT = 10;
final int INITIAL_X = 0;
final int INITIAL_Y = 0;
/**
* 長方形の開始座標(x,y)と、大きさのステータス(width,height)
*/
int width;
int height;
int x;
int y;
/**
* コンストラクタ
*/
public Rectangle(){
this.x = INITIAL_X;
this.y = INITIAL_Y;
this.width = INITIAL_WIDTH;
this.height = INITIAL_HEIGHT;
}
/**
* コンストラクタ
* @param width
* @param height
*/
public Rectangle(int width,int height){
this.x = INITIAL_X;
this.y = INITIAL_Y;
//問題11-8 値がマイナスの場合はゼロに置き換え
this.width = width < 0 ? 0 : width;
this.height = height < 0 ? 0 : height;
}
/**
* コンストラクタ
* @param x
* @param y
* @param width
* @param height
*/
public Rectangle(int x, int y, int width, int height){
this.x = x;
this.y = y;
this.width = width < 0 ? 0 : width;
this.height = height < 0 ? 0 : height;
}
/**
* 位置を設定します
* @param x
* @param y
*/
public void setLocation(int x, int y){
this.x = x;
this.y = y;
}
/**
* 大きさを設定します
* @param width
* @param height
*/
public void setSize(int width,int height){
this.width = width < 0 ? 0 : width;
this.height = height < 0 ? 0 : height;
}
/**
* 渡されたRectangleオブジェクトと座標上で重なっている部分を算出し、
* 新たなRectangleオブジェクトを返します。
* 重なっていない場合、x,y,width,heightが全てゼロのRectangleオブジェクトを返します。
* @param r
* @return
*/
public Rectangle intersect(Rectangle r){
//戻り値のベースになる長方形インスタンス
Rectangle resultRectangle;
//2つの長方形の始点をx軸、y軸でそれぞれ比較し、座標としてより奥(右下)にある方を仮始点とする
int startPointX = this.x < r.x ? r.x: this.x;
int startPointY = this.y < r.y ? r.y: this.y;
//2つの長方形の終点をx軸、y軸でそれぞれ比較し、座標としてより手前(左上)にある方を仮終点とする
int endPointX = (this.x + this.width) < (r.x + r.width) ? (this.x + this.width): (r.x + r.width);
int endPointY = (this.y + this.height) < (r.y + r.height) ? (this.y + this.height): (r.y + r.height);
//仮終点-仮始点で、重複分の長方形の幅、高さを求める
int overlapWidth = endPointX - startPointX;
int overlapHeight = endPointY - startPointY;
//幅または高さがゼロ以下の場合、重複する面積が存在しないため、重複なしと判断
if (overlapWidth <= 0 || overlapHeight <= 0){
resultRectangle = new Rectangle(0,0,0,0);
}else{
resultRectangle = new Rectangle(startPointX, startPointY, overlapWidth, overlapHeight);
}
return resultRectangle;
}
@Override
public String toString(){
return "[" + this.x + ", " + this.y + ", " + this.width + ", " + this.height + "]";
}
/**
* 同じ座標・大きさであるRectangleかどうかをBooleanで返します。
* @param obj
* @return
*/
@Override
public boolean equals(Object obj){
Rectangle r = (Rectangle)obj;
return (x == r.x && y == r.y && width == r.width && height == r.height);
}
}
|
package com.example.test;
import org.apache.log4j.Logger;
public class TestExample {
private static Logger logger = Logger.getLogger(TestExample.class);
public static void main(String[] args) {
String usrHome = System.getProperty("user.home");
System.out.println(usrHome);
String str = "1243";
System.out.println(str.charAt(0));
String projectPath = TestExample.class.getResource("/").getPath();
System.out.println(projectPath);
System.setProperty("projectPath", projectPath.substring(0, projectPath.lastIndexOf("classes")-1));
logger.info("this is a log test");
logger.error("this is a log test");
logger.debug("this is a log test");
// int page;
// System.out.println(page);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.