text
stringlengths 10
2.72M
|
|---|
/*
* Copyright (c) 2016. Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved.
*/
package com.flyingosred.app.perpetualcalendar.database.xml;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class XmlHelper {
private static int INDENT_SIZE = 4;
public static Document createDocument() {
return DocumentHelper.createDocument();
}
public static void addComment(Document document) {
document.addComment("Copyright (C) 2016 Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved.");
document.addComment("This file is auto-generated");
document.addComment("DO NOT MODIFY");
}
public static Element createRootElement(Document document, String rootName) {
Element root = document.addElement(rootName);
return root;
}
public static Element createElement(Element parent, String name, String value) {
return parent.addElement(name).addText(value);
}
public static Element createElement(Element parent, String name) {
return parent.addElement(name);
}
public static void outputFile(String path, Document document) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setIndentSize(INDENT_SIZE);
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(path), format);
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createXmlFile(String path, String rootName, String element, String elementName, String item,
List<String> itemNameList) {
Document document = DocumentHelper.createDocument();
document.addComment("Copyright (C) 2016 Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved.");
document.addComment("This file is auto-generated");
document.addComment("DO NOT MODIFY");
Element root = document.addElement(rootName);
Element rootElement = root.addElement(element).addAttribute("name", elementName);
for (String itemName : itemNameList) {
rootElement.addElement(item).addText(itemName);
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setIndentSize(INDENT_SIZE);
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(path), format);
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void createXmlFile(String path, String rootName, String element, Map<String, String> elementValues) {
Document document = DocumentHelper.createDocument();
document.addComment("Copyright (C) 2016 Osred Brockhoist <osred.brockhoist@hotmail.com>. All Rights Reserved.");
document.addComment("This file is auto-generated");
document.addComment("DO NOT MODIFY");
Element root = document.addElement(rootName);
for (Map.Entry<String, String> entry : elementValues.entrySet()) {
root.addElement(element).addAttribute("name", entry.getKey()).addText(entry.getValue());
}
OutputFormat format = OutputFormat.createPrettyPrint();
format.setIndentSize(INDENT_SIZE);
XMLWriter writer;
try {
writer = new XMLWriter(new FileOutputStream(path), format);
writer.write(document);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package hola;
import java.util.Scanner;
public class GiftsNoRand {
/* This program accepts as input names separated by commas(,) and outputs a possible order of
* giving gifts between each name such that no person leaves without a gift. The output order
* is fixed with no randomization yet.
* */
public static void main(String[] args) {
System.out.println("Dame los nombres separados por comas: ");
Scanner input = new Scanner(System.in);
String names = input.nextLine();
String[] tokens = new String[names.length()];
tokens = names.split(",");
if (tokens.length%2 == 0)
for(int i=0; i+1<tokens.length; i+=2) {
System.out.println(tokens[i]+"->"+tokens[i+1]+"\n");
System.out.println(tokens[i+1]+"->"+tokens[i]+"\n");
}
else {
System.out.println(tokens[tokens.length-1]+"->"+tokens[0]+"\n");
for(int i=0; i+1<tokens.length; i++)
System.out.println(tokens[i]+"->"+tokens[i+1]+"\n");
}
}
}
|
/*
* 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 Business.Users;
import Business.Abstract.User;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @author AEDSpring2019
*/
public class Customer extends User{
private String date;
public Customer(String password,String username)
{
super(password,username,"CUSTOMER");
Date now=new Date();
date=now.toString();
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public boolean verify(String password) {
if(password.equals(super.getPassword()))
return true;
else
return false;
}
}
|
package com.zzp.nacos.user.test;
import com.alibaba.fastjson.JSON;
import com.zzp.nacos.user.entity.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import java.util.Map;
import static org.mockito.Mockito.*;
/**
* @Description IUserServiceTest
* @Author karyzeng
* @since 2020.12.02
**/
@RunWith(SpringRunner.class)
//@SpringBootTest
public class IUserServiceTest {
@Test
public void createMockObject() throws Exception{
List<User> mockList = mock(List.class);
User user1 = new User();
user1.setId(100);
user1.setAge(18);
User user2 = new User();
user2.setId(200);
user2.setAge(28);
when(mockList.get(0)).thenReturn(user1).thenReturn(user2);
for (int i = 0; i < 2; i++) {
System.out.println(JSON.toJSONString(mockList.get(0)));
}
Assert.assertTrue(mockList instanceof List);
}
}
|
package com.codingchili.instance.model.items;
import com.codingchili.instance.model.entity.Creature;
import com.codingchili.instance.model.events.Event;
import com.codingchili.instance.model.events.EventType;
/**
* @author Robin Duda
*/
public class EntityUpdateEvent implements Event {
private Creature updated;
public EntityUpdateEvent(Creature updated) {
this.updated = updated;
}
public Creature getUpdated() {
return updated;
}
@Override
public EventType getRoute() {
return EventType.update;
}
}
|
package com.pwc.util;
import com.pwc.array.Array;
import com.pwc.io.DataInputBufferStream;
import java.io.*;
public class BinaryObject {
public static int getSizeOfFile(String fileName) throws IOException {
RandomAccessFile file = new RandomAccessFile(fileName, "r");
int length = 0;
try {
length = (int) file.length() / 4;
} catch (IOException e) {
e.printStackTrace();
} finally {
file.close();
}
if (length == 0) {
throw new RuntimeException();
}
return length;
}
public static void write(int[] a, String fileName) throws IOException {
DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
int off = 0;
int BUFFER_SIZE = 1024 * 1024; // 1M
byte[] buffer = new byte[BUFFER_SIZE * 4]; // 4MB
for (int i = 0; i < a.length; i++) {
Data.addIntToByteArray(a[i], buffer, off);
off++;
if (off == BUFFER_SIZE) {
off = 0;
out.write(buffer);
continue;
}
if (i == a.length - 1) {
out.write(buffer, 0, off * 4);
break;
}
}
out.flush();
out.close();
}
public static int[] loadAsIntArray(String filename) throws IOException {
int length = getSizeOfFile(filename);
DataInputBufferStream in = new DataInputBufferStream(new FileInputStream(filename));
int[] a = new int[length];
for (int i = 0; i < length; i++) {
a[i] = in.getInt();
}
in.close();
return a;
}
public static int[] loadAsIntArray2(String fileName) throws IOException {
int length = getSizeOfFile(fileName);
DataInputBufferStream in = new DataInputBufferStream(new FileInputStream(fileName));
int[] a = new int[length];
for (int i = 0; i < length; i++) {
a[i] = in.getInt();
}
in.close();
return a;
}
public static void generateRandomNumber(int from, int to, String fileName) throws IOException {
int[] a = getIntArray(from, to);
Array.shuffle(a);
BinaryObject.write(a, fileName);
}
public static void generateOrderNumber(int from, int to, String fileName) throws IOException {
int[] a = getIntArray(from, to);
BinaryObject.write(a, fileName);
}
private static int[] getIntArray(int from, int to) {
int[] a = new int[to - from + 1];
for (int i = from; i <= to; i++) {
a[i] = i;
}
return a;
}
public static int[] get(String fileName, int off, int length) throws Exception {
RandomAccessFile file = new RandomAccessFile(fileName, "r");
byte[] bytes = new byte[length];
try {
file.seek(off);
file.read(bytes);
} catch (IOException e) {
} finally {
try {
file.close();
} catch (IOException e) {
}
}
return Convert.BytesToIntArray(bytes);
}
}
|
package com.itheima.web.servlet;
import com.itheima.config.SpringConfig;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;
public class AccountServlet {
public static void main(String[] args) {
// ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfig.class);
// AccountService accountService = (AccountService) app.getBean("accountService");
AccountService accountService = app.getBean(AccountService.class);
List<Account> list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
}
}
|
package Transform;
import entity.WaterSensor;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import java.util.ArrayList;
/**
* @author douglas
* @create 2021-02-19 20:55
*/
public class Flink08_TransForm_nomal_Collection {
public static void main(String[] args) throws Exception {
//创建执行环境
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//从集合中读取数据
ArrayList<WaterSensor> waterSensors = new ArrayList<>();
waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 50));
waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
KeyedStream<WaterSensor, String> kbStream = env.fromCollection(waterSensors)
.keyBy(WaterSensor::getId);
// kbStream.sum("vc")
// .print("maxBy...").var;
kbStream.maxBy("vc",false)
.print();
env.execute();
}
}
|
package com.example.smdemo1.dto.response;
import java.io.Serializable;
import com.example.smdemo1.common.Constant;
import com.example.smdemo1.util.ResponseCodeUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* @author xp-dc
* @date 2019/4/25
*/
@Setter
@Getter
@ToString
public class BaseResponseDTO<T> implements Serializable {
private static final long serialVersionUID = -4049706808413497765L;
private int code;
private String message;
private T data;
private BaseResponseDTO(){}
private BaseResponseDTO(T data){
this.data = data;
}
private BaseResponseDTO(T data, int code, String message){
this.data = data;
this.code = code;
this.message = message;
}
/**
* 构建通用响应对象
* @param data
* @return
*/
public static <T> BaseResponseDTO<T> build(T data){
int code = Constant.ResponseCode.SUCCESS;
String message = ResponseCodeUtil.getMessage(code);
return new BaseResponseDTO<T>(data, code, message);
}
/**
* 构建通用响应对象
* @param data
* @param code
* @return
*/
public static <T> BaseResponseDTO<T> build(T data, int code){
String message = ResponseCodeUtil.getMessage(code);
return new BaseResponseDTO<T>(data, code, message);
}
/**
* 构建通用响应对象
* @param code
* @param message
* @return
*/
public static <T> BaseResponseDTO<T> build(int code, String message){
return new BaseResponseDTO<T>(null, code, message);
}
/**
* 构建通用响应对象
* @param data
* @param code
* @param message
* @return
*/
public static <T> BaseResponseDTO<T> build(T data, int code, String message){
return new BaseResponseDTO<T>(data, code, message);
}
}
|
package fr.aresrpg.tofumanchou.domain.event.player;
import fr.aresrpg.commons.domain.event.Event;
import fr.aresrpg.commons.domain.event.EventBus;
import fr.aresrpg.tofumanchou.domain.data.Account;
/**
* An event triggered when the perso lvl up
*
* @since
*/
public class LevelUpEvent implements Event<LevelUpEvent> {
private static final EventBus<LevelUpEvent> BUS = new EventBus<>(LevelUpEvent.class);
private Account client;
private int newLvl;
/**
* @param client
* @param newLvl
*/
public LevelUpEvent(Account client, int newLvl) {
this.client = client;
this.newLvl = newLvl;
}
/**
* @param client
* the client to set
*/
public void setClient(Account client) {
this.client = client;
}
/**
* @param newLvl
* the newLvl to set
*/
public void setNewLvl(int newLvl) {
this.newLvl = newLvl;
}
/**
* @return the newLvl
*/
public int getNewLvl() {
return newLvl;
}
/**
* @return the client
*/
public Account getClient() {
return client;
}
@Override
public EventBus<LevelUpEvent> getBus() {
return BUS;
}
@Override
public boolean isAsynchronous() {
return true;
}
@Override
public String toString() {
return "LevelUpEvent [client=" + client + ", newLvl=" + newLvl + "]";
}
}
|
package controllers;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.libs.F.Function;
import play.*;
import play.data.Form;
import play.libs.F.Promise;
import play.libs.Json;
import play.libs.ws.*;
import play.mvc.*;
import views.formdata.LoginForm;
import views.html.*;
import views.html.admin.*;
public class Application extends Controller {
/**
* The index page of your application.
* @return the rendered index page of your application
*/
public Result index() {
//TODO put internationalization support for your application
return ok(index.render("Welcome to (c)Birivarmi.com"));
}
public Result home() {
return ok(home.render("Welcome to (c)Birivarmi.com"));
}
public Result adminHome() {
return ok(adminhome.render());
}
public Result adminLogin(){
Form<LoginForm> loginForm = Form.form(LoginForm.class);
return ok(adminlogin.render("Welcome to (c)Birivarmi.com", loginForm));
}
public Result authenticateAdmin(){
Form<LoginForm> loginForm = Form.form(LoginForm.class).bindFromRequest();
if (loginForm.hasErrors()) {
return badRequest(adminlogin.render("Welcome to (c)Birivarmi.com", loginForm));
} else {
session().clear();
session("email", loginForm.get().email);
return adminHome();
}
}
public Result signup(){
return ok("Success!");
}
public Result post(){
return badRequest(Application.buildJsonResponse("error", "No such post"));
}
public static ObjectNode buildJsonResponse(String type, String message) {
ObjectNode wrapper = Json.newObject();
ObjectNode msg = Json.newObject();
msg.put("message", message);
wrapper.put(type, msg);
return wrapper;
}
}
|
package com.icanit.bdmapversion2.entity;
import com.baidu.platform.comapi.basestruct.GeoPoint;
public class Merchant implements java.io.Serializable {
// Fields
private long id;
private String merName;
private Integer typeId;
private double minCost;
private String detail;
private GeoPoint geoPoint;
private long commuId;
// Constructors
/** default constructor */
public Merchant() {
}
// Property accessors
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMerName() {
return merName;
}
public void setMerName(String merName) {
this.merName = merName;
}
public Integer getTypeId() {
return typeId;
}
public void setTypeId(Integer typeId) {
this.typeId = typeId;
}
public double getMinCost() {
return minCost;
}
public void setMinCost(double minCost) {
this.minCost = minCost;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public GeoPoint getGeoPoint() {
return geoPoint;
}
public void setGeoPoint(GeoPoint geoPoint) {
this.geoPoint = geoPoint;
}
public long getCommuId() {
return commuId;
}
public void setCommuId(long commuId) {
this.commuId = commuId;
}
}
|
package com.example.jse58.androiduiandlogin_jacobesworthy;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
public class LoginScreen extends AppCompatActivity {
private ArrayList<UserProfile> mUsers;
private UserProfilePersistence mPresistenceProfile;
private static final String TAG = "LoginActivity";
private String newUserEmail;
//Firebase info
FirebaseAuth mSigninAuth;
private ListView listView;
private String[] firstNames;
private String[] lastNames;
private String[] bdays;
private EditText mEditTxtEmail = null;
private EditText mEditTxtPswd = null;
private Button mBtnLogin = null;
private Button mBtnSignUp = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
mSigninAuth = FirebaseAuth.getInstance();
mPresistenceProfile = new UserProfilePersistence(this);
mEditTxtEmail = (EditText) findViewById(R.id.editTxtEmail);
mEditTxtPswd = (EditText) findViewById(R.id.editTxtPassowrd);
mBtnLogin = (Button) findViewById(R.id.BtnLogin);
mBtnSignUp = (Button) findViewById(R.id.BtnSignUp);
mBtnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
SignIn(mEditTxtEmail.getText().toString(), mEditTxtPswd.getText().toString());
}
});
mBtnSignUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "SignUp Button Pressed", Toast.LENGTH_SHORT).show();
Intent intentSignUp = new Intent(LoginScreen.this, SignUpActivity.class);
startActivity(intentSignUp);
}
});
}
@Override
protected void onResume() {
super.onResume();
Intent prevIntent = getIntent();
newUserEmail = prevIntent.getStringExtra("NEW_EMAIL");
mEditTxtEmail.setText(newUserEmail);
mEditTxtPswd.setText("");
}
public String[] validateInfo(String user, String pswd) {
mUsers = mPresistenceProfile.getDataFromDB();
String[] returnStrArr = new String[4];
returnStrArr[0] = "0";
returnStrArr[1] = "1";
returnStrArr[2] = "2";
returnStrArr[3] = "a";
if (mUsers.size() == 0) {
toastMessage("Please Signup.");
return returnStrArr;
}
for (UserProfile up : mUsers) {
if (up.getEmail().equals(user) || up.getUserName().equals(user)) {
if (up.getPswd().equals(pswd)) {
returnStrArr[0] = up.getName();
returnStrArr[1] = up.getLastName();
returnStrArr[2] = up.getBday();
returnStrArr[3] = "true";
break;
}
}
returnStrArr[3] = "a";
}
return returnStrArr;
}
public void SignIn(String email, String password) {
try {
mSigninAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
{
String firstname, lastname, bday;
@Override
public void onComplete(@NonNull Task<AuthResult> task)
{
if (task.isSuccessful())
{
FirebaseUser user = mSigninAuth.getCurrentUser();
mUsers = mPresistenceProfile.getDataFromDB();
for (UserProfile up : mUsers) {
if (up.getEmail().equals(mEditTxtEmail.getText().toString()) || up.getUserName().equals(mEditTxtEmail.getText().toString())) {
if (up.getPswd().equals(mEditTxtPswd.getText().toString())) {
firstname = up.getName();
lastname = up.getLastName();
bday = up.getBday();
break;
}
}
}
Intent intentLoginSuccess = new Intent(LoginScreen.this, LoginSuccessActivity.class);
intentLoginSuccess.putExtra("CURRENT_FIRST_NAME", firstname);
intentLoginSuccess.putExtra("CURRENT_LAST_NAME", lastname);
intentLoginSuccess.putExtra("CURRENT_BDAY", bday);
startActivity(intentLoginSuccess);
}
}
});
}
catch (Exception ex)
{
try {
mUsers = mPresistenceProfile.getDataFromDB();
String[] b = new String[4];
Toast.makeText(getApplicationContext(), "Login Button Pressed", Toast.LENGTH_SHORT).show();
if (!mEditTxtEmail.getText().toString().isEmpty() && !mEditTxtPswd.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(), "Verifying Info.", Toast.LENGTH_SHORT).show();
b = validateInfo(mEditTxtEmail.getText().toString(), mEditTxtPswd.getText().toString());
if (!b[3].isEmpty()) {
Toast.makeText(getApplicationContext(), "Logging In.", Toast.LENGTH_SHORT).show();
Intent intentLoginSuccess = new Intent(LoginScreen.this, LoginSuccessActivity.class);
intentLoginSuccess.putExtra("CURRENT_FIRST_NAME", b[0]);
intentLoginSuccess.putExtra("CURRENT_LAST_NAME", b[1]);
intentLoginSuccess.putExtra("CURRENT_BDAY", b[2]);
startActivity(intentLoginSuccess);
}
} else {
Toast.makeText(getApplicationContext(), "Type your credentails first.", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
Log.d(TAG, e.getMessage());
toastMessage("Sign in Error.");
mEditTxtEmail.setText("");
mEditTxtPswd.setText("");
}
}
}
public void toastMessage(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
}
|
package com.baiwang.custom.common.util;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 字符串对象是否为空判断工具类
* Created by LiaoJS on 2016/8/13.
*/
public class StringUtil {
public static boolean isEmpty(String str) {
if (str == null || str.length() == 0) {
return true;
}
return false;
}
/**
* 判定原字符串是否为空,为空则返回空串"",否则返回字符串本身
* 20171103之前,返回Object,有点多余,特修改为直接反馈字符串
*
* @param str
* @return
*/
public static String isNull(String str) {
if (str == null || str.length() == 0 || "null".equals(str)) {
return "";
}
return str;
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
* 判断字串的真实长度(含中文)
*
* @param s
* @return
*/
public static int String_length(String s) {
int length = 0;
for (int i = 0; i < s.length(); i++) {
int ascii = Character.codePointAt(s, i);
if (ascii >= 0 && ascii <= 255)
length++;
else
length += 2;
}
return length;
}
/**
* 获取指定字符串之间的字串
*
* @param source
* @param priStr
* @param fromIndex
* @param suxStr
* @return
*/
public static String getIntervalValue(String source, String priStr, int fromIndex, String suxStr) {
if (source == null)
return "";
int iFirst = source.indexOf(priStr, fromIndex);
int iLast = source.indexOf(suxStr, fromIndex);
if (iFirst < 0 || iLast < 0)
return "";
int beginIndex = iFirst + priStr.length();
return source.substring(beginIndex, iLast);
}
public static String getIntervalValue(String source, String priStr, String suxStr) {
return getIntervalValue(source, priStr, 0, suxStr);
}
/**
* base64转inputStream
*
* @param base64string
* @return
*/
public static InputStream baseToInputStream(String base64string) {
ByteArrayInputStream stream = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
byte[] bytes1 = decoder.decodeBuffer(base64string);
stream = new ByteArrayInputStream(bytes1);
} catch (Exception e) {
e.printStackTrace();
}
return stream;
}
public static final byte[] input2byte(InputStream inStream)
throws IOException {
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = inStream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
byte[] in2b = swapStream.toByteArray();
return in2b;
}
}
|
package org.apache.cordova.localMusic;
import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowInsets;
// import com.duanqu.qupai.utils.BitmapUtil;
// import com.duntuo.SmartVoiceAPP.MainActivity;
// import com.duntuo.SmartVoiceAPP.R;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import static android.content.Context.BIND_AUTO_CREATE;
/**
* This class echoes a string called from JavaScript.
*/
public class LocalMusic extends CordovaPlugin {
public static final String LOG_TAG = "LOCALMUSIC";
public static Uri ALL_SONGS_URI = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
public static Uri ALBUMS_URI = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
public static Uri ARTISTS_URI = android.provider.MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI;
//获取焦点
// AudioManager mAudioManager = (AudioManager) cordova.getContext().getSystemService(Context.AUDIO_SERVICE);
private AudioManager mAudioManager;
final MediaPlayer mMediaPlayer = new MediaPlayer();
private ArrayList<String> musicList;
private ArrayList<String> musicIds;
private String isPlaying; // 1 正在播放
private String songId; // 标记当前歌曲的序号
private String musicType="song"; //播放来源的类别 song 单曲,art 歌手,album 专辑
private String typeId; // musicType != song 。 typeid 表示的是artid, albumid
private int selectedSegmentIndex=0; // 0 顺序播放 1 随机 2 单曲循环
private int songIndex;
public static int musicPosition;
JSONArray allMusic = new JSONArray();
private MediaSessionCompat mMediaSession;
private CallbackContext BleButtonCallbackContext = null;
public static final int SEEK_CLOSEST = 0x03;
public boolean execute(String action, JSONArray args,CallbackContext callbackContext) throws JSONException {
//mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
//requestFocus();
//初始化AudioManager对象
mAudioManager = (AudioManager) cordova.getContext().getSystemService(Context.AUDIO_SERVICE);
//申请焦点
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
//判断权限够不够,不够就给
if (ContextCompat.checkSelfPermission(cordova.getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(cordova.getActivity(), new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE
}, 1);
}
if("getMusicList".equals(action)) {
musicPosition=0;
allMusic = this.getJsonListOfSongs();
callbackContext.success(allMusic);
} else if("getAlbums".equals(action)){
musicPosition=0;
JSONArray allAlbums = this.getJsonListOfAlbums();
callbackContext.success(allAlbums);
} else if("getArtists".equals(action)){
musicPosition=0;
JSONArray allAlbums = this.getJsonListOfArtists();
callbackContext.success(allAlbums);
}
// 播放 、 暂停
else if("playOrPause".equals(action)){
songId = args.getString(0);
isPlaying = args.getString(1);
musicType = args.getString(2);
typeId = args.getString(3);
//Log.e(null,"第几首歌:"+songId+" 播放暂停:"+isPlaying);
if(allMusic.length()==0){
allMusic = this.getJsonListOfSongs();
}
//开始播放
if (isPlaying.equals("1") && musicPosition!=0){
mMediaPlayer.start();
} else {
playMusic(false);
}
}
//上一曲
else if("prevSong".equals(action)){
isPlaying = "1";
musicPosition=0;
musicType = args.getString(0);
typeId = args.getString(1);
preciousMusic();
callbackContext.success(songId);
}
//下一曲
else if("nextSong".equals(action)){
isPlaying = "1";
musicPosition=0;
musicType = args.getString(0);
typeId = args.getString(1);
nextMusic(false);
callbackContext.success(songId);
}
// 0顺序播放 1随机。2循环。
else if("setSelectedSegmentIndexs".equals(action)){
musicPosition=0;
selectedSegmentIndex = Integer.parseInt(args.getString(0));
}
// 快进 or 后退
else if("speedOrBack".equals(action)){
Log.e(null,args.getString(0));
//mMediaPlayer.pause();
mMediaPlayer.seekTo(Integer.parseInt(args.getString(0))); //SEEK_CLOSEST
//mMediaPlayer.start();
}
// 开启媒体按键监听 android
if (action.equals("start")) {
if (this.BleButtonCallbackContext != null) {
removeBleButtonListener();
}
this.BleButtonCallbackContext = callbackContext;
Context context = this.cordova.getContext();
mMediaSession = new MediaSessionCompat(context,LOG_TAG);
mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mMediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public boolean onMediaButtonEvent(Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_BUTTON)) {
// 获得KeyEvent对象
KeyEvent key = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (key == null) {
return false;
}
if (key.getAction() != KeyEvent.ACTION_DOWN) {
int keycode = key.getKeyCode();
if (keycode == KeyEvent.KEYCODE_MEDIA_NEXT) {
// 下一首按键
sendUpdate("PRESS_NEXT", true);
} else if (keycode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) {
// 上一首按键
sendUpdate("PRESS_PREVIOUS", true);
} else if (keycode == KeyEvent.KEYCODE_MEDIA_PLAY) {
// 播放按键
sendUpdate("PRESS_PLAY", true);
} else if (keycode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
// 暂停按键
sendUpdate("PRESS_PAUSE", true);
} else if (keycode == KeyEvent.KEYCODE_VOLUME_UP) {
// 暂停按键
sendUpdate("PRESS_VOLUME_UP", true);
} else if (keycode == KeyEvent.KEYCODE_VOLUME_DOWN) {
// 暂停按键
sendUpdate("PRESS_VOLUME_DOWN", true);
}
// 还可以添加更多按键操作,可以参阅 KeyEvent 类
}
}
return true;
}
});
mMediaSession.setActive(true);
}
else {
return false;
}
return true;
}
/**
* 焦点变化监听器
*/
private AudioManager.OnAudioFocusChangeListener mAudioFocusChange = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange){
case AudioManager.AUDIOFOCUS_LOSS:
//长时间丢失焦点
Log.d(null, "AUDIOFOCUS_LOSS");
stop();
//释放焦点
mAudioManager.abandonAudioFocus(mAudioFocusChange);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
//短暂性丢失焦点
stop();
Log.d(null, "AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
//短暂性丢失焦点并作降音处理
Log.d(null, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
break;
case AudioManager.AUDIOFOCUS_GAIN:
//重新获得焦点
Log.d(null, "AUDIOFOCUS_GAIN");
start();
break;
}
}
};
private void start() {
mAudioManager.requestAudioFocus(mAudioFocusChange, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mMediaPlayer.start();
}
private void stop() {
mMediaPlayer.pause();
}
private void sendUpdate(String message, boolean keepCallback) {
if (this.BleButtonCallbackContext != null) {
PluginResult result = new PluginResult(PluginResult.Status.OK, message);
result.setKeepCallback(keepCallback);
this.BleButtonCallbackContext.sendPluginResult(result);
}
}
private void removeBleButtonListener() {
if(mMediaSession != null) {
mMediaSession.setCallback(null);
mMediaSession.setActive(false);
mMediaSession.release();
}
}
public JSONArray getJsonListOfSongs(){
ContentResolver contentResolver = this.cordova.getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ALL_SONGS_URI, null, (android.provider.MediaStore.Audio.Media.IS_MUSIC+" = ?"), new String[]{"1"}, null);
allMusic = new JSONArray();
musicList = new ArrayList<String>(); //音乐列表
musicIds = new ArrayList<String>();
if (cursor == null){
}else if (!cursor.moveToFirst()){
}else{
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int albumIdColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ALBUM_ID);
int albumColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ALBUM);
int artistIdColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST_ID);
int artistColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int durationColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DURATION);
int dataColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA);
//int dataImgUrl = cursor.getColumnIndex(android.provider.MediaStore.Audio.Thumbnails);
do {
JSONObject music = new JSONObject();
try {
if(cursor.getLong(idColumn)>0){
music.put("id", cursor.getLong(idColumn));
music.put("displayName", cursor.getString(titleColumn));
music.put("album_id", cursor.getLong(albumIdColumn));
music.put("albumName", cursor.getString(albumColumn));
music.put("artist_id", cursor.getLong(artistIdColumn));
music.put("artistName", cursor.getString(artistColumn));
music.put("duration", cursor.getLong(durationColumn));
music.put("data", cursor.getString(dataColumn));
music.put("albumsImgUrl", MediaStore.Video.Thumbnails.getContentUri(cursor.getString(titleColumn)));
allMusic.put(music);
musicList.add(cursor.getString(dataColumn));
musicIds.add(Long.toString(cursor.getLong(idColumn)));
Log.e( null ,music.getString("displayName"));
Log.e( null ,music.getString("data"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
// 释放资源
cursor.close();
return allMusic;
}
/**
根据歌曲路径获得专辑封面
* @Description 获取专辑封面
* @param filePath 文件路径,like XXX/XXX/XX.mp3
* @return 专辑封面bitmap
*/
public static Bitmap createAlbumArt(final String filePath) {
Bitmap bitmap = null;
//能够获取多媒体文件元数据的类
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(filePath); //设置数据源
byte[] embedPic = retriever.getEmbeddedPicture(); //得到字节型数据
bitmap = BitmapFactory.decodeByteArray(embedPic, 0, embedPic.length); //转换为图片
//要优化后再加载
//bitmap=BitmapUtil.decodeBitmapByByteArray(embedPic,80,80);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
retriever.release();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return bitmap;
}
public JSONArray getJsonListOfAlbums(){
ContentResolver contentResolver = this.cordova.getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ALBUMS_URI, null, null, null, null);
JSONArray allAlbums = new JSONArray();
if (cursor == null){
}else if (!cursor.moveToFirst()){
}else{
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums._ID);
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM);
int albumArtColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ALBUM_ART);
int noOfSongsColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.NUMBER_OF_SONGS);
int artistColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Albums.ARTIST);
do {
JSONObject album = new JSONObject();
try {
album.put("id", cursor.getLong(idColumn));
album.put("displayName", cursor.getString(titleColumn));
album.put("image", cursor.getString(albumArtColumn));
album.put("noOfSongs", cursor.getLong(noOfSongsColumn));
album.put("artist", cursor.getString(artistColumn));
allAlbums.put(album);
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
return allAlbums;
}
public JSONArray getJsonListOfArtists(){
ContentResolver contentResolver = this.cordova.getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ARTISTS_URI, null, null, null, null);
JSONArray allArtists = new JSONArray();
if (cursor == null){
}else if (!cursor.moveToFirst()){
}else{
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Artists._ID);
int artistColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Artists.ARTIST);
int noOfSongsColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Artists.NUMBER_OF_TRACKS);
do {
JSONObject artist = new JSONObject();
try {
artist.put("id", cursor.getLong(idColumn));
artist.put("artistName", cursor.getString(artistColumn));
artist.put("noOfSongs", cursor.getLong(noOfSongsColumn));
allArtists.put(artist);
} catch (JSONException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
return allArtists;
}
/**
* 播放\暂停音乐
*/
public void playMusic(boolean isAutoNextPlay) {
Log.e(null,"开始播放-暂停音乐"+isPlaying);
if (isPlaying.equals("1")) {
//如果还没开始播放,就开始
Log.e(null,"开始播放");
mMediaPlayer.reset();
iniMediaPlayerFile(songId);
if(musicPosition!=0){
mMediaPlayer.seekTo(musicPosition);
}
else {
mMediaPlayer.start();
}
isPlaying = "0";
}
// 暂停播放
else {
mMediaPlayer.pause();
musicPosition = mMediaPlayer.getCurrentPosition();
Log.e(null,"暂停"+musicPosition);
isPlaying = "1";
}
//播放完成事件
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
Log.e(null,"播放结束,自动下一曲");
isPlaying = "1";
musicPosition = 0;
nextMusic(true);
}
});
//播放跳转事件
// mMediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener(){
// @Override
// public void onSeekComplete(MediaPlayer mp) {
// //TODO: Your code here
// mMediaPlayer.start();
// }
// });
}
/**
* 下一首
*/
public void nextMusic(boolean isAutoNextPlay) {
if (mMediaPlayer != null) {
int countMusicSize = allMusic.length();
if(musicType.equals("art")){
try {
countMusicSize = 0;
for (int i = 0; i < allMusic.length(); i++) {
JSONObject jsonObject = allMusic.getJSONObject(i);
String artist_id = jsonObject.getString("artist_id"); //歌手
if( artist_id.equals(typeId)){
countMusicSize++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if(musicType.equals("album")){
try {
countMusicSize = 0;
for (int i = 0; i < allMusic.length(); i++) {
JSONObject jsonObject = allMusic.getJSONObject(i);
String artist_id = jsonObject.getString("album_id"); //专辑
if( artist_id.equals(typeId)){
countMusicSize++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if (selectedSegmentIndex == 0) { //顺序播放
if (songIndex >= countMusicSize - 1) {
songIndex = 0;
} else {
songIndex++;
}
}
else if (selectedSegmentIndex == 1) { //随机播放
int max= countMusicSize - 1;
Random random = new Random();
songIndex = random.nextInt(max)%(max+1);
}
int countTypes = 0;
for(int i = 0; i <allMusic.length(); i++) {
try {
if(musicType.equals("art")) {
if(typeId.equals(allMusic.getJSONObject(i).getString("artist_id"))) {
if(countTypes == songIndex) {
songId = allMusic.getJSONObject(i).getString("id");
//Log.e(null,allMusic.getJSONObject(i).getString("displayName"));
break;
}
countTypes++;
}
} else if(musicType.equals("album")) {
if(typeId.equals(allMusic.getJSONObject(i).getString("album_id"))) {
if(countTypes == songIndex) {
songId = allMusic.getJSONObject(i).getString("id");
break;
}
countTypes++;
}
} else if(musicType.equals("song")) {
if(songIndex == i){
songId = allMusic.getJSONObject(i).getString("id");
break;
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
playMusic(isAutoNextPlay);
if(isAutoNextPlay){
sendUpdate(songId,true);
}
}
}
/**
* 上一首
*/
public void preciousMusic() {
if (mMediaPlayer != null){
int countMusicSize = allMusic.length();
if(musicType.equals("art")){
countMusicSize = 0;
try {
for (int i = 0; i < allMusic.length(); i++) {
JSONObject jsonObject = allMusic.getJSONObject(i);
String artist_id = jsonObject.getString("artist_id");
if( artist_id.equals(typeId)){
countMusicSize++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else if(musicType.equals("album")){
countMusicSize = 0;
try {
for (int i = 0; i < allMusic.length(); i++) {
JSONObject jsonObject = allMusic.getJSONObject(i);
String artist_id = jsonObject.getString("album_id");
if( artist_id.equals(typeId)){
countMusicSize++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if (selectedSegmentIndex == 0) { //顺序播放
if (songIndex <= 0) {
songIndex = countMusicSize - 1;
} else {
songIndex--;
}
}
else if (selectedSegmentIndex == 1){ //随机播放
int max= countMusicSize - 1;
Random random = new Random();
songIndex = random.nextInt(max)%(max+1);
}
// 从歌手处播放
int countTypes = 0;
for(int i = 0; i <allMusic.length(); i++) {
try {
if(musicType.equals("art")) {
if(typeId.equals(allMusic.getJSONObject(i).getString("artist_id"))) {
if(countTypes == songIndex) {
songId = allMusic.getJSONObject(i).getString("id");
Log.e(null,allMusic.getJSONObject(i).getString("displayName"));
break;
}
countTypes++;
}
} else if(musicType.equals("album")) {
if(typeId.equals(allMusic.getJSONObject(i).getString("album_id"))) {
if(countTypes == songIndex) {
songId = allMusic.getJSONObject(i).getString("id");
Log.e(null,allMusic.getJSONObject(i).getString("displayName"));
break;
}
countTypes++;
}
} else if(musicType.equals("song")) {
if(songIndex == i){
songId = allMusic.getJSONObject(i).getString("id");
break;
}
}
}catch (JSONException e) {
e.printStackTrace();
}
}
playMusic(false);
}
}
/**
* 关闭播放器
*/
public void closeMedia() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
/**
* 添加file文件到MediaPlayer对象并且准备播放音频
*/
private void iniMediaPlayerFile(String idex) {
//获取文件路径
try {
//此处的两个方法需要捕获IO异常
//设置音频文件到MediaPlayer对象中
int song_index = 0;
int count_type = 0;
String songPath = musicList.get(song_index);
for(int i = 0; i < musicIds.size(); i++){
if( musicIds.get(i).equals(idex)){
song_index = i;
if(musicType.equals("song")) {
songIndex = i;
songPath = musicList.get(song_index);
}
}
}
// 从歌手和专辑列表
for(int i =0; i < allMusic.length();i++){
try {
String song_id = allMusic.getJSONObject(i).getString("id");
if(musicType.equals("art")){
String artist_id = allMusic.getJSONObject(i).getString("artist_id");
if(artist_id.equals(typeId)){
if(song_id.equals(idex)){
songIndex = count_type;
songPath = musicList.get(song_index);
break;
}
count_type++;
}
} else if(musicType.equals("album")){
String album_id = allMusic.getJSONObject(i).getString("album_id");
if(album_id.equals(typeId)){
if(song_id.equals(idex)){
songIndex = count_type;
songPath = musicList.get(song_index);
break;
}
count_type++;
}
}
} catch(JSONException e) {
e.printStackTrace();
}
}
Log.d(LOG_TAG , "播放路径");
Log.e(null,songPath);
mMediaPlayer.setDataSource(songPath);
//让MediaPlayer对象准备
mMediaPlayer.prepare();
} catch (IOException e) {
Log.d(LOG_TAG , "设置资源,准备阶段出错");
e.printStackTrace();
}
}
}
|
package com.capgemini.Resource_Management.service;
import com.capgemini.Resource_Management.model.ProjectDetails;
public interface ProjectService {
public void saveProject(ProjectDetails projectDetails);
}
|
package com.es.test;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
public class ESTest_Doc_Delete {
public static void main(String[] args) throws Exception{
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
DeleteRequest request = new DeleteRequest();
request.index("user").id("1001");
client.delete(request,RequestOptions.DEFAULT);
client.close();;
}
}
|
package org.celllife.stock.interfaces.service;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.celllife.stock.application.service.user.UserService;
import org.celllife.stock.domain.exception.StockException;
import org.celllife.stock.domain.user.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/service/users")
public class UserController {
private static Logger log = LoggerFactory.getLogger(UserController.class);
@Autowired
UserService userService;
@Value("${external.base.url}")
String baseUrl;
@ResponseBody
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public UserDto getUser(@RequestParam("msisdn") String msisdn, HttpServletResponse response) throws IOException {
try {
UserDto user = userService.getUser(msisdn);
if (user == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return null;
}
return user;
} catch (StockException e) {
log.error("Error while getting user with msisdn "+msisdn, e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
return null;
}
}
@RequestMapping(method = RequestMethod.POST)
public void saveUser(@RequestBody UserDto user, HttpServletResponse response) throws IOException {
try {
// FIXME: lookup the clinic name if clinicName is null (using the clinic service)
UserDto newUser = userService.createUser(user);
response.setHeader("Location", baseUrl + "/service/users?msisdn=" + newUser.getMsisdn());
response.setStatus(HttpServletResponse.SC_CREATED);
} catch (StockException e) {
log.error("Error while saving user "+user, e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
@RequestMapping(method = RequestMethod.PUT)
public void updateUser(@RequestBody UserDto user, HttpServletResponse response) throws IOException {
try {
userService.updateUser(user);
response.setStatus(HttpServletResponse.SC_OK);
} catch (StockException e) {
log.error("Error while updating user "+user, e);
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
}
}
}
|
package com.chauyiu1994.grpc.service;
import com.chauyiu1994.grpc.User;
import com.chauyiu1994.grpc.userGrpc.userImplBase;
import io.grpc.stub.StreamObserver;
public class UserService extends userImplBase {
@Override
public void login(User.LoginRequest request, StreamObserver<User.APIResponse> responseObserver) {
System.out.println("Inside login");
String username = request.getUsername();
String password = request.getPassword();
User.APIResponse.Builder response = User.APIResponse.newBuilder();
if (username.equals(password)) {
response.setResponseCode(0).setResponseMessage("SUCCESS");
} else {
response.setResponseCode(100).setResponseMessage("INVALID PASSWORD");
}
responseObserver.onNext(response.build());
// close the call
responseObserver.onCompleted();
}
@Override
public void logout(User.Empty request, StreamObserver<User.APIResponse> responseObserver) {
super.logout(request, responseObserver);
}
}
|
package br.com.zolp.estudozolp.document;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
/**
* Classe responsável por efetuar o mapeamento das informações de response.
*
* @author mamede
* @version 0.0.1-SNAPSHOT
*
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@ApiModel(description = "Objeto responsável pelo response.")
public class ObjetoResponseDocument implements Serializable {
private static final long serialVersionUID = 326582784214857854L;
@ApiModelProperty(notes = "Retorno.")
private String retorno;
public ObjetoResponseDocument() {
}
public final String getRetorno() {
return retorno;
}
public final void setRetorno(final String retorno) {
this.retorno = retorno;
}
@Override
public final String toString() {
return "ObjetoResponseDocument{" +
"retorno='" + retorno + '\'' +
'}';
}
}
|
package hu.mentlerd.hybrid.asm;
import java.lang.reflect.Method;
public class Loader {
public static Class<?> loadClass( ClassLoader loader, byte[] code, String name ){
try {
Class<?> clazz = Class.forName("java.lang.ClassLoader");
Method defineClass = clazz.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class );
defineClass.setAccessible(true);
Object[] args = new Object[]{ name, code, 0, code.length };
return (Class<?>) defineClass.invoke(loader, args);
} catch ( Exception err ){
err.printStackTrace();
}
return null;
}
public static <T> T createInstance( ClassLoader loader, byte[] code, String name, Class<T> clazz ){
Class<?> genClass = loadClass(loader, code, name);
try {
return clazz.cast( genClass.newInstance() );
} catch ( Exception err ) {
err.printStackTrace();
}
return null;
}
}
|
package com.pruebatecnicaomar.PruebaTecnicaOmar.service;
import java.util.List;
import com.pruebatecnicaomar.PruebaTecnicaOmar.dto.CoinHistorial;
public interface HistorialService {
public List<CoinHistorial> getHistorialBTC(int ultimosMinutos);
public List<CoinHistorial> getHistorialLRC(int ultimosMinutos);
public List<CoinHistorial> getHistorialADA(int ultimosMinutos);
}
|
package com.example.zrust.helloworld;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import com.example.zrust.helloworld.service.ProviderService;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(ProviderService.ACTION_DATA_RECEIVED);
registerReceiver(statusReceiver, filter);
}
public void buttonOnClick(View view){
System.out.println("You clicked me! :)");
TextView textView3 = (TextView) findViewById(R.id.textView3);
EditText text = (EditText) findViewById(R.id.editText);
textView3.setText(text.getText());
Intent i = new Intent(ProviderService.ACTION_DATA_SENT);
i.putExtra("message", text.getText().toString());
sendBroadcast(i);
}
BroadcastReceiver statusReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message"); //get the type of message from MyGcmListenerService 1 - lock or 0 -Unlock
System.out.println("DATA RECEIVED: " + message);
TextView textView3 = (TextView) findViewById(R.id.textView3);
textView3.setText(message);
}
};
}
|
package model;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.UIDefaults;
public class CellRenderer implements ListCellRenderer {
Color color;
private JTextArea ta;
public CellRenderer() {
UIDefaults defaults = javax.swing.UIManager.getDefaults();
color=defaults.getColor("List.selectionBackground");
ta = new JTextArea();
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
ta.setText(value.toString());
if(isSelected)
ta.setBackground(color);
else
ta.setBackground(Color.WHITE);
int width = list.getWidth();
if (width > 0)
ta.setSize(width, Short.MAX_VALUE);
return ta;
}
}
|
package com.tianwotian.tools;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;
/**
* 内存缓存
* 因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。Google建议使用LruCache
* Created by user on 2016/9/8.
*/
public class MemoryCacheUtils {
// private HashMap<String, Bitmap> mMemoryCache = new HashMap<String,
// Bitmap>();
// private HashMap<String, SoftReference<Bitmap>> mMemoryCache = new
// HashMap<String, SoftReference<Bitmap>>();
private LruCache<String, Bitmap> mMemoryCache;
public MemoryCacheUtils() {
// LruCache 可以将最近最少使用的对象回收掉, 从而保证内存不会超出范围
// Lru: least recentlly used 最近最少使用算法
long maxMemory = Runtime.getRuntime().maxMemory();// 获取分配给app的内存大小
System.out.println("maxMemory:" + maxMemory);
mMemoryCache = new LruCache<String, Bitmap>((int) (maxMemory / 8)) {
// 返回每个对象的大小
@Override
protected int sizeOf(String key, Bitmap value) {
// int byteCount = value.getByteCount();
int byteCount = value.getRowBytes() * value.getHeight();// 计算图片大小:每行字节数*高度
return byteCount;
}
};
}
/**
* 写缓存
*/
public void setMemoryCache(String url, Bitmap bitmap) {
// mMemoryCache.put(url, bitmap);
// SoftReference<Bitmap> soft = new SoftReference<Bitmap>(bitmap);//
// 使用软引用将bitmap包装起来
// mMemoryCache.put(url, soft);
mMemoryCache.put(url, bitmap);
}
/**
* 读缓存
*/
public Bitmap getMemoryCache(String url) {
// SoftReference<Bitmap> softReference = mMemoryCache.get(url);
//
// if (softReference != null) {
// Bitmap bitmap = softReference.get();
// return bitmap;
// }
Log.d("image", "这是从内存中加载的图片");
return mMemoryCache.get(url);
}
}
|
package gameView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import javax.swing.JFrame;
import javax.swing.JRootPane;
import gameController.ObservedGame;
class SaveHandler implements ActionListener
{
GameView gv;
public SaveHandler(GameView gameview)
{
gv = gameview;
}
public void actionPerformed(ActionEvent arg0)
{
FileOutputStream fileOut;
int id = (int) Math.floor(Math.random()*100);
try {
fileOut = new FileOutputStream("assets/saves/save" + id + ".ser");
gv.gc.saveGame(fileOut);
} catch (FileNotFoundException e) {
System.out.println("Erro de salvamento:" + e.getMessage());
}
}
}
|
package ProjectManagement;
public class User implements Comparable<User>,UserReport_ {
private String name;
private int consumption;
private int latest;
User(String name)
{
consumption=0;
this.name=name;
latest=0;
}
public String name()
{
return name;
}
@Override
public int compareTo(User user)
{
int y=this.consumed()-user.consumed();
if(y==0)
y=this.getLatest()-user.getLatest();
return y;
}
public void consumed(int a)
{
consumption+=a;
}
@Override
public int consumed() {
return consumption;
}
@Override
public String user() {
return name;
}
public void setLatest(int a)
{
latest=a;
}
public int getLatest()
{
return latest;
}
}
|
package com.rtw.myrpccore.server;
import java.io.Serializable;
/**
* @author rtw
* @since 2019-04-15
*/
public class ServerRequest implements Serializable {
private Long id;
private Object content; // 传参
private String command; // 类 + 方法名
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
}
|
/*
* 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 ie.irishliterature.dao;
/**
*
* @author markus
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Database {
public Connection getConnection() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
Connection connection = null;
// Store the database URL in a string
// String url = "jdbc:mysql://localhost:3306/ILGAS";
String url = "jdbc:mysql://literatureirelandgrantapplication.com:3306/ILGAS";
Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
// set the url, username and password for the databse
connection = DriverManager.getConnection( url, "markus", "ankh573" );
return connection;
}
}
|
package exercicio06;
public class Miseravel extends Pessoa
{
Miseravel(String nome, int idade)
{
super(nome, idade);
}
public void Mendigo()
{
System.out.println(this.getNome()+" é considerado uma pessoa miseravel e precisa de ajuda\n");
}
}
|
package au.gov.nsw.records.digitalarchive.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import au.gov.nsw.records.digitalarchive.ORM.Archivist;
import au.gov.nsw.records.digitalarchive.ORM.Member;
import au.gov.nsw.records.digitalarchive.ORM.Publication;
import au.gov.nsw.records.digitalarchive.base.BaseAction;
import au.gov.nsw.records.digitalarchive.base.Constants;
import au.gov.nsw.records.digitalarchive.service.FileService;
import au.gov.nsw.records.digitalarchive.service.FileServiceImpl;
import au.gov.nsw.records.digitalarchive.service.MemberService;
import au.gov.nsw.records.digitalarchive.service.MemberServiceImpl;
import au.gov.nsw.records.digitalarchive.service.PublicationService;
import au.gov.nsw.records.digitalarchive.service.PublicationServiceImpl;
public class MemberAction extends BaseAction{
public MemberAction()
{}
public ActionForward loadMember(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
ActionForward forward = null;
MemberService ms = new MemberServiceImpl();
try{
Archivist archivist = (Archivist)request.getSession().getAttribute("archivist");
if( archivist == null)
{
forward = mapping.findForward("welcome");
}else
{
List<Member> list = ms.browseMember();
request.setAttribute("memberList", list);
forward = mapping.findForward("loadMember");
}
}catch(Exception ex){
logger.info("In class MemberAction:loadMember()\n");
ex.printStackTrace();
}
return forward;
}
public ActionForward viewMember(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
MemberService service = new MemberServiceImpl();
Member member = null;
String p = request.getParameter("id");
Integer id = null;
if(p!=null)
{
id = new Integer(p);
}else
{
id = new Integer(0);
}
try{
member = service.loadMember(id);
if (member!=null)
{
request.getSession().setAttribute("member", member);
}
}catch(Exception ex){
logger.info("In class MemberAction:viewMember()\n");
ex.printStackTrace();
}
return mapping.findForward("memberdetail");
}
public ActionForward deleteMember (ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
ActionForward forward = null;
ActionMessages msgs = new ActionMessages();
if (!("").equalsIgnoreCase(request.getParameter("id")))
{
Integer id = null;
id = new Integer(request.getParameter("id"));
try
{
Archivist archivist = (Archivist)request.getSession().getAttribute("archivist");
if (archivist == null)
{
forward = mapping.findForward("login");
}else
{
MemberService ms = new MemberServiceImpl();
boolean status = ms.delMember(id);
if (status)
{
msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("member.delete.success"));
}else
{
msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("member.delete.failed"));
}
saveMessages(request, msgs);
forward = mapping.findForward("loadArchivist");
}
}catch(Exception ex)
{
logger.info("In class MemberAction:deleteMember()\n");
ex.printStackTrace();
}
}else
{
forward = mapping.findForward("home");
}
return forward;
}
public ActionForward switchAccount(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
MemberService ms = new MemberServiceImpl();
Member member = (Member)request.getSession().getAttribute("member");
Archivist archivist = (Archivist)request.getSession().getAttribute("archivist");
Integer id = new Integer(request.getParameter("id"));
ActionForward forward = null;
try
{
if (archivist == null){
forward = mapping.findForward("exit");
}else
{
if (member != null)
{
Member memberForm = ms.loadMember(id);
String action = request.getParameter("action");
if ("De-Activate this account".equalsIgnoreCase(action))
{
memberForm.setActivated("n");
}
if ("Activate this account".equalsIgnoreCase(action))
{
memberForm.setActivated("y");
}
if ("Flag this member as Privileged".equalsIgnoreCase(action))
{
memberForm.setPrivileged("y");
}
if ("Unflag this member as Privileged".equalsIgnoreCase(action))
{
memberForm.setPrivileged("n");
}
Boolean status = ms.updateMember(memberForm);
if (status)
{
forward = new ActionForward("/member.do?method=viewMember&id="+id);
}else
{
forward = new ActionForward("/member.do?method=viewMember&id="+id);
}
}
}
}catch(Exception ex)
{
logger.info("In class MemberAction:switchAccount()\n");
ex.printStackTrace();
}
return forward;
}
}
|
package orm.integ.eao.model;
public class FromOrmHelper {
public static boolean isFromOrm(RecordObject obj) {
if (obj==null) {
return false;
}
return obj.fromOrm==1;
}
public static void setFromOrm(RecordObject obj) {
if (obj!=null) {
obj.fromOrm = 1;
}
}
}
|
/*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.client;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.junit.Assert;
import org.junit.Test;
import com.nimbusds.oauth2.sdk.ParseException;
import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata;
import pl.edu.icm.unity.oauth.client.OpenIdConnectDiscovery;
import pl.edu.icm.unity.oauth.client.config.CustomProviderProperties;
public class OIDCDiscoveryTest
{
@Test
public void test() throws ParseException, IOException
{
OpenIdConnectDiscovery tested = new OpenIdConnectDiscovery(new URL(
"https://accounts.google.com/.well-known/openid-configuration"));
Properties props = new Properties();
props.setProperty("translationProfile", "");
props.setProperty("clientSecret", "");
props.setProperty("clientId", "");
props.setProperty("name", "");
props.setProperty("openIdConnect", "true");
props.setProperty("openIdConnectDiscoveryEndpoint", "https://accounts.google.com/.well-known/openid-configuration");
CustomProviderProperties def = new CustomProviderProperties(props, "", null);
OIDCProviderMetadata meta = tested.getMetadata(def);
Assert.assertEquals("https://accounts.google.com", meta.getIssuer().getValue());
}
}
|
/*
* 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 Controladores;
import ConexionBaseDeDatos.ConexionBD;
import Interfaces.PanelListarCarreras;
import Interfaces.PanelNuevaCarrera;
import Modelos.ModeloCarreras;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author HP
*/
public class Carreras implements ActionListener,KeyListener {
ModeloCarreras Modelo;
PanelListarCarreras VistaListar;
PanelNuevaCarrera VistaFormulario;
JDialog Dialogo;
public Carreras(JFrame jFramePrincipal, ConexionBD conexionMySQL) {
this.Modelo = new ModeloCarreras(conexionMySQL);
this.VistaListar = new PanelListarCarreras();
this.VistaListar.setSize(jFramePrincipal.getWidth(), jFramePrincipal.getHeight());
this.VistaListar.getBtnNuevo().addActionListener(this);
this.VistaListar.getBtnModificar().addActionListener(this);
this.VistaListar.getBtnEliminar().addActionListener(this);
this.VistaListar.getBtnActualizar().addActionListener(this);
this.VistaListar.getTxtBusqueda().addKeyListener((KeyListener) this);
this.VistaListar.getBtnBuscar().addActionListener(this);
this.VistaListar.getBtnLimpiar().addActionListener(this);
this.VistaFormulario = new PanelNuevaCarrera();
this.VistaFormulario.getBtnAgregar().addActionListener(this);
this.VistaFormulario.getBtnCancelar().addActionListener(this);
this.Dialogo = new JDialog(jFramePrincipal, true);
cargarDatos(VistaListar.getTxtBusqueda().getText());
jFramePrincipal.getContentPane().removeAll();
jFramePrincipal.getContentPane().add(VistaListar);
jFramePrincipal.pack();
}
@Override
public void actionPerformed(ActionEvent e) {
//Botón Nuevo pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnNuevo()) {
Dialogo.getContentPane().add(this.VistaFormulario);
Dialogo.setTitle("Nueva Categoría");
Dialogo.setSize(620, 350);
centrarVentana(this.VistaListar, Dialogo);
Dialogo.setResizable(false);
Dialogo.setVisible(true);
}
//Botón Modificar pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnModificar()) {
if (VistaListar.getTableCarreras().getSelectedRow() < 0) {
JOptionPane.showMessageDialog(VistaListar, "Debe seleccionar un registro");
}else {
String[] carrera = Modelo.getCarrera(
Integer.parseInt(((DefaultTableModel)VistaListar.getTableCarreras().getModel())
.getValueAt(VistaListar.getTableCarreras().getSelectedRow(), 0).toString()));
VistaFormulario.getJTextFieldId().setText(carrera[0]);
VistaFormulario.getTxtCarrera().setText(carrera[1]);
VistaFormulario.getTxtDescripcion().setText(carrera[2]);
VistaFormulario.getTxtAsignaturas().setText(carrera[3]);
VistaFormulario.getDuracion().setSelectedItem(carrera[4]);
VistaFormulario.getMatricula().setSelectedItem(carrera[5]);
VistaFormulario.getTxtCostoMatricula().setText(carrera[6]);
Dialogo.getContentPane().add(this.VistaFormulario);
Dialogo.setTitle("Modificar Carrera");
Dialogo.setSize(620, 350);
centrarVentana(this.VistaListar, Dialogo);
Dialogo.setResizable(false);
Dialogo.setVisible(true);
}
}
//Botón Borrar pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnEliminar()) {
if (VistaListar.getTableCarreras().getSelectedRow() < 0) {
JOptionPane.showMessageDialog(VistaListar, "Debe seleccionar un registro");
} else {
int dialogoResultado = JOptionPane.showConfirmDialog(VistaListar, "¿Esta segur@ de borrar el registro de Carrera?", "Pregunta", JOptionPane.YES_NO_OPTION);
if (dialogoResultado == JOptionPane.YES_OPTION) {
int id = Integer.parseInt(
((DefaultTableModel)VistaListar.getTableCarreras().getModel())
.getValueAt(VistaListar.getTableCarreras().getSelectedRow(), 0).toString());
if (Modelo.borrar(id)) {
} else {
JOptionPane.showMessageDialog(VistaListar, "El Registro no se pudo borrar");
}
cargarDatos(VistaListar.getTxtBusqueda().getText());
}
}
}
//Botón Actualizar pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnActualizar()) {
cargarDatos(VistaListar.getTxtBusqueda().getText());
}
//Botón Buscar pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnBuscar()) {
cargarDatos(VistaListar.getTxtBusqueda().getText());
}
//
// //Botón Limpiar pulsado desde el Panel de JPanelCategoriasListar
if (e.getSource() == this.VistaListar.getBtnLimpiar()) {
VistaListar.getTxtBusqueda().setText("");
cargarDatos("");
}
//Botón Guardar pulsado desde el Panel de JPanelCategoriasFormulario
if (e.getSource() == this.VistaFormulario.getBtnAgregar()) {
if (Modelo.guardar(
Integer.parseInt(this.VistaFormulario.getJTextFieldId().getText()),
this.VistaFormulario.getTxtCarrera().getText(),
this.VistaFormulario.getTxtDescripcion().getText(),
Integer.parseInt(this.VistaFormulario.getTxtAsignaturas().getText()),
Integer.parseInt(this.VistaFormulario.getDuracion().getSelectedItem().toString()),
this.VistaFormulario.getMatricula().getSelectedItem().toString(),
Double.parseDouble(this.VistaFormulario.getTxtCostoMatricula().getText())
)) {
Dialogo.setVisible(false);
limpiarFormulario();
cargarDatos("");
} else {
JOptionPane.showMessageDialog(Dialogo, "No se pudo guardar la Carrera", "Error", JOptionPane.ERROR_MESSAGE);
}
}
//Botón Cancelar pulsado desde el Panel de JPanelCategoriasFormulario
if (e.getSource() == this.VistaFormulario.getBtnCancelar()) {
Dialogo.setVisible(false);
limpiarFormulario();
cargarDatos(VistaListar.getTxtBusqueda().getText());
}
}
public void cargarDatos(String textoBusqueda) {
this.VistaListar.setDatos(this.Modelo.getLista(textoBusqueda), this.Modelo.getTotal());
//Ocultamos la columna del Id para que no se vea
this.VistaListar.getTableCarreras().getColumnModel().getColumn(0).setWidth(0);
this.VistaListar.getTableCarreras().getColumnModel().getColumn(0).setMinWidth(0);
this.VistaListar.getTableCarreras().getColumnModel().getColumn(0).setMaxWidth(0);
}
public void limpiarFormulario() {
this.VistaFormulario.getJTextFieldId().setText("0");
this.VistaFormulario.getTxtCarrera().setText("");
this.VistaFormulario.getTxtDescripcion().setText("");
this.VistaFormulario.getTxtCostoMatricula().setText("");
this.VistaFormulario.getTxtAsignaturas().setText("");
this.VistaFormulario.getDuracion().setSelectedIndex(0);
this.VistaFormulario.getMatricula().setSelectedIndex(0);
}
public void centrarVentana(Component jFrame, Component dialogo) {
Dimension tamanioVentana = jFrame.getSize();
dialogo.setLocation(
jFrame.getX() + ((tamanioVentana.width - dialogo.getSize().width) / 2),
jFrame.getY() + ((tamanioVentana.height - dialogo.getSize().height) / 2));
}
@Override
public void keyTyped(KeyEvent e) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER){
cargarDatos(VistaListar.getTxtBusqueda().getText());
}
}
@Override
public void keyReleased(KeyEvent e) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
|
/*
* 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 com.koshish.java.hibernate.ecommerce.DAO.impl;
import com.koshish.java.hibernate.ecommerce.DAO.CustomerDAO;
import com.koshish.java.hibernate.ecommerce.entity.Customer;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
/**
*
* @author Koshish Rijal
*/
@Repository("customerDAO")
public class CustomerDAOImpl implements CustomerDAO {
@Autowired
private SessionFactory sessionFactory;
private Transaction transaction;
private Session session;
private List<Customer> customerList;
@Override
public List<Customer> getAll() {
session = sessionFactory.openSession();
customerList = session.createQuery("From Customer c").list();
session.close();
return customerList;
}
@Override
public Customer getById(int id) {
session = sessionFactory.openSession();
Customer customer=(Customer) session.get(Customer.class, id);
session.close();
return customer;
}
@Override
public int insert(Customer customer) {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
int result = (int) session.save(customer);
transaction.commit();
session.close();
return result;
}
@Override
public int update(Customer customer) {
session=sessionFactory.openSession();
transaction=session.beginTransaction();
session.update(customer);
transaction.commit();
session.close();
return 1;
}
@Override
public int delete(int id) {
Customer customer=getById(id);
if(!customer.getPurchaseList().isEmpty()){
return 0;
}
session=sessionFactory.openSession();
transaction=session.beginTransaction();
session.delete(customer);
transaction.commit();
session.close();
return 1;
}
}
|
package com.rengu.operationsmanagementsuitev3.Controller;
import com.rengu.operationsmanagementsuitev3.Entity.ResultEntity;
import com.rengu.operationsmanagementsuitev3.Service.DeployLogDetailService;
import com.rengu.operationsmanagementsuitev3.Service.DeployLogService;
import com.rengu.operationsmanagementsuitev3.Utils.ResultUtils;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
/**
* @program: operations-management-suite-v3
* @author: hanch
* @create: 2018-09-06 18:24
**/
@RestController
@RequestMapping(value = "/deploylogs")
public class DeployLogController {
private final DeployLogService deployLogService;
private final DeployLogDetailService deployLogDetailService;
@Autowired
public DeployLogController(DeployLogService deployLogService, DeployLogDetailService deployLogDetailService) {
this.deployLogService = deployLogService;
this.deployLogDetailService = deployLogDetailService;
}
// 根据Id删除部署日志
@DeleteMapping(value = "/{deployLogId}")
public ResultEntity deleteDeployLogById(@PathVariable(value = "deployLogId") String deployLogId) {
return ResultUtils.build(deployLogService.deleteDeployLogById(deployLogId));
}
// 根据id查询部署日志
@GetMapping(value = "/{deployLogId}")
public ResultEntity getDeployLogById(@PathVariable(value = "deployLogId") String deployLogId) {
return ResultUtils.build(deployLogService.getDeployLogById(deployLogId));
}
// 根据id查询部署日志详情
@GetMapping(value = "/{deployLogId}/deploylogdetails")
public ResultEntity getDeployLogDetailsByDeployLog(@PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable, @PathVariable(value = "deployLogId") String deployLogId) {
return ResultUtils.build(deployLogDetailService.getDeployLogDetailsByDeployLog(pageable, deployLogService.getDeployLogById(deployLogId)));
}
// 根据全部部署设计详情
@GetMapping
@PreAuthorize(value = "hasRole('admin')")
public ResultEntity getDeployLogs(@PageableDefault(sort = "createTime", direction = Sort.Direction.DESC) Pageable pageable) {
return ResultUtils.build(deployLogService.getDeployLogs(pageable));
}
}
|
package util.parameters;
import board.blockingobject.Player;
import items.IdentityDisc;
public class StepOnParameter {
private Player player;
private IdentityDisc identityDisc;
/**
* Creates a new player step on parameter
* @param player which steps on the square
*
* @throws IllegalArgumentException
* when player is null.
*/
public StepOnParameter(Player player) throws IllegalArgumentException
{
if(player == null)
throw new IllegalArgumentException();
this.player = player;
}
/**
* Creates a new force field step on parameter
* @param identityDisc The identity disc which hits the force field
*
* @throws IllegalArgumentException
* when {@link IdentityDisc} is null.
*/
public StepOnParameter(IdentityDisc identityDisc) throws IllegalArgumentException {
if(identityDisc == null)
throw new IllegalArgumentException();
this.identityDisc = identityDisc;
}
/**
*
* @return player which steps on the square
*/
public Player getPlayer()
{
return player;
}
/**
*
* @return identity disc The identity disc which hits the force field
*/
public IdentityDisc getIdentityDisc()
{
return identityDisc;
}
}
|
package com.teamdev.webapp;
import com.google.gson.Gson;
import com.teamdev.business.AuthenticationService;
import com.teamdev.business.ChatRoomService;
import com.teamdev.business.MessageService;
import com.teamdev.business.UserService;
import com.teamdev.business.impl.dto.*;
import com.teamdev.business.impl.exception.AuthenticationException;
import com.teamdev.business.impl.exception.ChatRoomAlreadyExistsException;
import com.teamdev.business.impl.exception.ChatRoomNotFoundException;
import com.teamdev.business.impl.exception.UserNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
public class TestServlet extends HttpServlet {
private BeanProvider beanProvider;
@Override
public void init() throws ServletException {
beanProvider = BeanProvider.getInstance();
try {
generateSampleData();
} catch (AuthenticationException e) {
e.printStackTrace();
} catch (ChatRoomAlreadyExistsException e) {
e.printStackTrace();
} catch (UserNotFoundException e) {
e.printStackTrace();
} catch (ChatRoomNotFoundException e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/json;charset=UTF-8");
PrintWriter printWriter = resp.getWriter();
Map<String, String[]> parameterMap = req.getParameterMap();
UserId userId = new UserId(Long.parseLong(parameterMap.get("userId")[0]));
UserService userService = beanProvider.getBean(UserService.class);
Set<ChatRoomDTO> availableChats = userService.findAvailableChats(userId);
String json = toJson(availableChats);
printWriter.write(json);
}
private void generateSampleData() throws AuthenticationException, ChatRoomAlreadyExistsException, UserNotFoundException, ChatRoomNotFoundException {
ChatRoomService chatRoomService = beanProvider.getBean(ChatRoomService.class);
ChatRoomDTO chatRoomDTO = chatRoomService.create("TestRoom");
UserService userService = beanProvider.getBean(UserService.class);
UserDTO userDTO1 = userService.register(new UserName("Vasya"), new UserEmail("vasya@gmail.com"), new UserPassword("pwd"));
UserDTO userDTO2 = userService.register(new UserName("Masha"), new UserEmail("masha@gmail.com"), new UserPassword("pwd1"));
AuthenticationService tokenService = beanProvider.getBean(AuthenticationService.class);
Token token1 = tokenService.login(new UserEmail(userDTO1.email), new UserPassword("pwd"));
UserId id1 = new UserId(userDTO1.id);
UserId id2 = new UserId(userDTO2.id);
chatRoomService.joinToChatRoom(token1, new UserId(userDTO1.id), new ChatRoomId(chatRoomDTO.id));
MessageService messageService = beanProvider.getBean(MessageService.class);
messageService.sendPrivateMessage(token1, id1, id2, "Hello, Masha!");
}
private String toJson(Collection<ChatRoomDTO> chatRoomDTOs) {
Gson gson = new Gson();
return gson.toJson(chatRoomDTOs);
}
}
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
package com.pointinside.android.piwebservices.provider;
import android.content.*;
import android.database.sqlite.*;
import android.net.Uri;
import java.util.ArrayList;
public abstract class SQLiteContentProvider extends ContentProvider
implements SQLiteTransactionListener
{
public SQLiteContentProvider()
{
}
private boolean applyingBatch()
{
return mApplyingBatch.get() != null && ((Boolean)mApplyingBatch.get()).booleanValue();
}
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> arraylist)
throws OperationApplicationException
{
int i;
int j;
i = 0;
j = 0;
mDb = mOpenHelper.getWritableDatabase();
mDb.beginTransactionWithListener(this);
int k;
ContentProviderResult acontentproviderresult[];
mApplyingBatch.set(Boolean.valueOf(true));
k = arraylist.size();
acontentproviderresult = new ContentProviderResult[k];
int l = 0;
try {
for(;l < k;) {
if(++j >= 500)
throw new OperationApplicationException("Too many content provider operations between yield points. The maximum number of operations per yield point is 500", i);
ContentProviderOperation contentprovideroperation = (ContentProviderOperation)arraylist.get(l);
if(l > 0 && contentprovideroperation.isYieldAllowed()) {
boolean flag;
flag = mDb.yieldIfContendedSafely(4000L);
j = 0;
if(flag)
i++;
}
acontentproviderresult[l] = contentprovideroperation.apply(this, acontentproviderresult, l);
l++;
}
mDb.setTransactionSuccessful();
mApplyingBatch.set(Boolean.valueOf(false));
mDb.endTransaction();
onEndTransaction();
} catch(Exception exception) {
mApplyingBatch.set(Boolean.valueOf(false));
mDb.endTransaction();
onEndTransaction();
throw new OperationApplicationException(exception.toString());
}
return acontentproviderresult;
}
protected void beforeTransactionCommit()
{
}
public int bulkInsert(Uri paramUri, ContentValues[] paramArrayOfContentValues)
{
int i = paramArrayOfContentValues.length;
this.mDb = this.mOpenHelper.getWritableDatabase();
this.mDb.beginTransactionWithListener(this);
for (int j = 0;; j++)
{
try
{
if (j >= i) {
this.mDb.setTransactionSuccessful();
this.mDb.endTransaction();
onEndTransaction();
return i;
} else {
if (insertInTransaction(paramUri, paramArrayOfContentValues[j]) != null) {
this.mNotifyChange = true;
}
this.mDb.yieldIfContendedSafely();
}
}
finally
{
this.mDb.endTransaction();
}
}
// return i;
}
protected abstract SQLiteOpenHelper createDatabaseHelper(Context context);
public int delete(Uri uri, String s, String as[])
{
try {
int i =0;
if(!applyingBatch()) {
mDb = mOpenHelper.getWritableDatabase();
mDb.beginTransactionWithListener(this);
i = deleteInTransaction(uri, s, as);
if(i <= 0)
mNotifyChange = false;
else
mNotifyChange = true;
mDb.setTransactionSuccessful();
mDb.endTransaction();
onEndTransaction();
} else {
i = deleteInTransaction(uri, s, as);
if(i > 0)
{
mNotifyChange = true;
return i;
}
}
return i;
} catch(Exception exception) {
exception.printStackTrace();
mDb.endTransaction();
//throw exception;
}
return 0;
}
protected abstract int deleteInTransaction(Uri uri, String s, String as[]);
protected SQLiteOpenHelper getDatabaseHelper()
{
return mOpenHelper;
}
public Uri insert(Uri uri, ContentValues contentvalues)
{
Uri uri1 = null;
try {
if(!applyingBatch()) {
mDb = mOpenHelper.getWritableDatabase();
mDb.beginTransactionWithListener(this);
uri1 = insertInTransaction(uri, contentvalues);
if(uri1 == null)
mNotifyChange = false;
else
mNotifyChange = true;
mDb.setTransactionSuccessful();
mDb.endTransaction();
onEndTransaction();
} else {
uri1 = insertInTransaction(uri, contentvalues);
if(uri1 != null)
{
mNotifyChange = true;
return uri1;
}
}
return uri1;
} catch(Exception exception) {
exception.printStackTrace();
// mDb.endTransaction();
// throw exception;
}
return uri1;
}
protected abstract Uri insertInTransaction(Uri uri, ContentValues contentvalues);
protected abstract void notifyChange();
public void onBegin()
{
onBeginTransaction();
}
protected void onBeginTransaction()
{
}
public void onCommit()
{
beforeTransactionCommit();
}
public boolean onCreate()
{
mOpenHelper = createDatabaseHelper(getContext());
return true;
}
protected void onEndTransaction()
{
if(mNotifyChange)
{
mNotifyChange = false;
notifyChange();
}
}
public void onRollback()
{
}
public int update(Uri uri, ContentValues contentvalues, String s, String as[])
{
try {
int i;
if(!applyingBatch()) {
mDb = mOpenHelper.getWritableDatabase();
mDb.beginTransactionWithListener(this);
i = updateInTransaction(uri, contentvalues, s, as);
if(i <= 0)
mNotifyChange = false;
else
mNotifyChange = true;
mDb.setTransactionSuccessful();
mDb.endTransaction();
onEndTransaction();
} else {
i = updateInTransaction(uri, contentvalues, s, as);
if(i > 0)
{
mNotifyChange = true;
return i;
}
}
return i;
} catch(Exception exception) {
exception.printStackTrace();
//mDb.endTransaction();
//throw exception;
}
return 0;
}
protected abstract int updateInTransaction(Uri uri, ContentValues contentvalues, String s, String as[]);
private static final int MAX_OPERATIONS_PER_YIELD_POINT = 500;
private static final int SLEEP_AFTER_YIELD_DELAY = 4000;
private static final String TAG = "SQLiteContentProvider";
private final ThreadLocal mApplyingBatch = new ThreadLocal();
protected SQLiteDatabase mDb;
private volatile boolean mNotifyChange;
private SQLiteOpenHelper mOpenHelper;
}
|
package com.cn.hello.spring.cloud.web.admin.feign.feign;
import org.springframework.stereotype.Component;
/**
* @program: spring-cloud-netflix
* @ClassName: AdminFallback
* @company: 鸿业(深圳)信息技术服务有限公司
* @author: Lamdong
* @create: 2019-11-26 12:53
**/
@Component
public class AdminFallback implements AdminService {
@Override
public String sayHi(String message) {
return "网络有问题,请重试";
}
}
|
// Factory design patten gives us the possibility to hide the detail of how to initialize the different instance.
public class ShapeFactory{
public Shape getShape(String shapeType){
if(ShapeType == null){
return null;
}
if(ShapeType.equalsIgnoreCase("rectangle")){
return new Rectangle();
}else if(ShapeType.equalsIgnoreCase("circle")){
return new Circle();
}
}
}
// use a Shape interface which can hide the detail implementation of a specific object
public interface Shape{
void draw();
}
// make the class which contains the implementation detail of the required method.
public class Rectangle implements Shape {
@Override
public void draw(){
System.out.println("rectanle");
}
}
public class Circle implements Shape {
@Override
public void draw(){
System.out.println("circle");
}
}
//sample class loader
public class FactoryPattern {
public static void main(String [] args){
Factory factory = new Factory();
Shape circle = factory.getShape("circle");
Shape rectangle = factory.getShape("rectangle");
circle.draw();
rectangle.draw();
}
}
|
package com.needii.dashboard.view;
import com.needii.dashboard.components.Messages;
import com.needii.dashboard.model.Shippers;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.view.document.AbstractXlsView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class ShippersExportExcel extends AbstractXlsView {
@Autowired
Messages messages;
@Override
protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"shippers-list.xls\"");
List<Shippers> shippersList = (List<Shippers>) model.get("shippers");
Sheet sheet = workbook.createSheet("Shippers list");
// Create header row
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("Mã");
header.createCell(1).setCellValue("Tên người vận chuyển");
header.createCell(2).setCellValue("Địa chỉ");
header.createCell(3).setCellValue("Trạng thái hiện tại");
header.createCell(4).setCellValue("Trạng thái");
header.createCell(5).setCellValue("Tạo lúc");
// Create data cells
int rowCount = 1;
for (Shippers shippers : shippersList) {
Row courseRow = sheet.createRow(rowCount++);
courseRow.createCell(0).setCellValue(shippers.getId());
courseRow.createCell(1).setCellValue(shippers.getUsername());
courseRow.createCell(2).setCellValue(shippers.getAddress());
courseRow.createCell(3).setCellValue(shippers.getShipperCurrentStatus());
courseRow.createCell(4).setCellValue(shippers.getStatus());
courseRow.createCell(5).setCellValue(shippers.getCreatedAtFormatVN());
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.tjenwellens.timetracker.macro;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;
import eu.tjenwellens.timetracker.ActivityResults;
import eu.tjenwellens.timetracker.R;
import eu.tjenwellens.timetracker.database.DatabaseHandler;
import eu.tjenwellens.timetracker.macro.macrosettings.MacroSettingsActivity;
import java.util.List;
/**
*
* @author Tjen
*/
public class MacroActivity extends Activity implements MacroHandler
{
public static int MACRO_START = 659244;
public static String MACRO_TITLE = "macro_title";
public static String MACRO_CALENDAR = "macro_calendar";
private MacroButtonPanel macroButtonPanel;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.macro);
reloadMacros();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private void reloadMacros()
{
if (macroButtonPanel == null)
{// init new panel
final LinearLayout macroContainer = (LinearLayout) findViewById(R.id.pnlMacro);
macroButtonPanel = new MacroButtonPanel(this, this);
macroContainer.addView(macroButtonPanel);
} else
{// reset current panel
macroButtonPanel.reset();
// final LinearLayout macroContainer = (LinearLayout) findViewById(R.id.pnlMacro);
// macroContainer.removeAllViews();
// macroButtonPanel = null;
}
// add to panel
macroButtonPanel.addAllButtons(loadDBMacros(this));
}
public static List<MacroI> loadDBMacros(Context context)
{
return DatabaseHandler.getInstance(context).getAllMacros();
}
@Override
public void launchActiviteit(MacroI macro)
{
Intent returnIntent = new Intent();
returnIntent.putExtra(MACRO_TITLE, macro.getActiviteitTitle());
returnIntent.putExtra(MACRO_CALENDAR, macro.getKalenderName());
setResult(RESULT_OK, returnIntent);
finish();
}
private void launchCancel()
{
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
private void launchMacroSettings()
{
Intent i = new Intent(this, MacroSettingsActivity.class);
startActivityForResult(i, ActivityResults.MACRO_DETAILS_START);
}
/*
*
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == Activity.RESULT_OK && requestCode == ActivityResults.MACRO_DETAILS_START)
{
reloadMacros();
}
}
/*
* Create menu
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.macro_menu, menu);
return true;
}
/*
* Handle menu
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_edit:
launchMacroSettings();
return true;
case R.id.menu_cancel:
launchCancel();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
|
package com.company;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import com.company.Enums.*;
//All functions to pull information from database,
public class HotelDB {
private static String url = "jdbc:mysql://38.39.89.83:3306/hotel?useSSL=false"; //URL of database being connected to
private static final String user = "access"; //username to connect to DB
private static final String pass = "root"; //DB password
private static Connection con; //Variable which holds the connection
//All functions are Static because this is a utility to connect to the DB rather than an actual object
//----------------------------------Connection---------------------------------------------------//
//Attempt to connect to the SQL SERVER
public static boolean createConnection() {
// This will load the MySQL driver, each DB has its own driver
//Attempt to connect to MYSQL Database, if you cannot connect, throw error
try {
con = DriverManager.getConnection(url, user, pass);
}
catch (Exception e) {
//Return false and show error
System.out.println("Oh No");
e.printStackTrace();
return false;
}
return true;
}
//----------------------------------Room---------------------------------------------------//
public static Room getRoom(int ID, Size size, View view, int floor, State state) {
//Select * where ID is not null will return all results alone
String query = "SELECT * FROM hotel.room WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ID != 0) {query = query + " AND id = " + String.valueOf(ID);}
if (size != null) {query = query + " AND size = " + size.name();}
if (view != null) {query = query + " AND view = " + view.name();}
if (floor != 0) {query = query + " AND floor = " + String.valueOf(floor);}
if (state != null) {query = query + " AND state = " + state.name();}
query = query + ";";
//If a connection cannot be created, let user know
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
//Attempt to retrieve class from database
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Room room = null;
if (rs.next()) { //If there was a result
//Store DB variables in local variables
int roomID = rs.getInt(0);
int beds = rs.getInt(1);
Size s = Size.valueOf(rs.getString(2));
View v = View.valueOf(rs.getString(3));
State ste = State.valueOf(rs.getString(4));
int fl = rs.getInt(5);
int booking_id = rs.getInt(6);
//Create and initalize Local Room object from DB Room table
room = new Room(roomID, beds, s, v, fl);
room.setState(ste);
Booking b = getRoomBooking(booking_id);
b.setRoom(room);
room.setBooking(b);
//Return the found Room as Java Room object
return room;
}
else {
//If no results found Inform user and return nothing
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) { //On exceptions, print exception, return null
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static ArrayList<Room> getRooms(int ID, Size size, View view, int floor, State state) {
//Select * where ID is not null will return all results alone
String query = "SELECT * FROM hotel.room WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ID != 0) {query = query + " AND id = " + String.valueOf(ID);}
if (size != null) {query = query + " AND size = " + size.name();}
if (view != null) {query = query + " AND view = " + view.name();}
if (floor != 0) {query = query + " AND floor = " + String.valueOf(floor);}
if (state != null) {query = query + " AND state = " + state.name();}
query = query + ";";
//If a connection cannot be created, let user know
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
//Attempt to retrieve class from database
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ArrayList<Room> rooms = new ArrayList<Room>();
while (rs.next()) { //Loop through all results
//Store DB variables in local variables
int roomID = rs.getInt(0);
int beds = rs.getInt(1);
Size s = Size.valueOf(rs.getString(2));
View v = View.valueOf(rs.getString(3));
State ste = State.valueOf(rs.getString(4));
int fl = rs.getInt(5);
int booking_id = rs.getInt(6);
Room room = new Room(roomID, beds, s, v, fl);
//Create and initalize Local Room object from DB Room table
room.setState(ste);
Booking b = getRoomBooking(booking_id);
b.setRoom(room);
room.setBooking(b);
//Add room to list
rooms.add(room);
}
return rooms;
}
catch (Exception e) { //If exception occurs, print exception and return null
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static int createRooms(int ID, int beds, Size size, View view, int floor, State state) {
String query = "USE hotel;\n INSERT INTO room VALUES (";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
query = query + "'" + String.valueOf(ID) + "', ";
query = query + "'" + String.valueOf(beds) + "', ";
query = query + "'" + size.name() + "'";
query = query + "'" + view.name() + "'";
query = query + "'" + state.name() + "'";
query = query + "'" + String.valueOf(floor) + "'";
query = query + ");";
//Attempt to create connection to DB, if fails inform user
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try { //Attempt to insert room
Statement st = con.createStatement();
System.out.println(query);
st.executeUpdate(query);
}
catch (Exception e) { //If issues occur print exception and return -1;
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return 0; //return 0 on success
}
//----------------------------------Customer---------------------------------------------------//
public static Customer getCustomer(int ID, String address, long phonenumber, int bookingID) {
//Select * where ID is not null will return all results alone
String query = "SELECT * FROM hotel.customer WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ID != 0) {query = query + " AND id = " + String.valueOf(ID);}
if (address != null) {query = query + " AND address = '" + address + "'";}
if (phonenumber != 0) {query = query + " AND phone_number = " + String.valueOf(phonenumber);}
if (bookingID != 0) {query = query + " AND booking_id = " + String.valueOf(bookingID);}
query = query + ";";
//Attempt to create Connection to DB, notify user if connection fails
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
//Attempt to retrieve results based on query
try {
//use connection to execute the SQL Query
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Customer cx = null;
if (rs.next()) { //If results exist
//Create and initialize Customer using retrieved information from DB
cx = new Customer(rs.getInt(1), rs.getLong(5), rs.getString(6));
cx.addMembership(null);// If memberships are added in the future, this will be changed to retrieve a membership
Booking b = getCustomerBooking(rs.getInt(1));
if (b != null) {
b.setClient(cx);
}
cx.setBooking(b);//get the booking information
return cx; //return the client
}
else { //If no results returned, inform user and return Null;
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static ArrayList<Customer> getCustomers(int ID, String address, long phonenumber, int bookingID) {
String query = "SELECT * FROM hotel.customer WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ID != 0) {query = query + " AND id = " + String.valueOf(ID);}
if (address != null) {query = query + " AND address = '" + address + "'";}
if (phonenumber != 0) {query = query + " AND phone_number = " + String.valueOf(phonenumber);}
if (bookingID != 0) {query = query + " AND booking_id = " + String.valueOf(bookingID);}
query = query + ";";
System.out.println(query);
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ArrayList<Customer> customers = new ArrayList<Customer>();
while (rs.next()) {
System.out.println("ID: " + rs.getInt(1) + " memID: " + rs.getString(2) + " Checked In: " + rs.getInt(3) + " bookingID: " + rs.getInt(4) + " phone number: " + rs.getLong(5) + " address: " + rs.getString(6));
Customer cx = new Customer(rs.getInt(1), rs.getLong(5), rs.getString(6));
cx.addMembership(null);// If memberships are added in the future, this will be changed to retrieve a membership
Booking b = getCustomerBooking(rs.getInt(1));
if (b != null) {
b.setClient(cx);
}
cx.setBooking(b);//get the booking information
customers.add(cx);
}
return customers;
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
private static Customer getBookingCustomer(int ID) {
//Same as regular customer however only used locally to retrieve customer from DB
String query = "SELECT * FROM hotel.customer WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ID != 0) {query = query + " AND id = " + String.valueOf(ID);}
query = query + ";";
System.out.println(query);
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Customer cx = null;
if (rs.next()) {
System.out.println("ID: " + rs.getInt(1) + " memID: " + rs.getString(2) + " Checked In: " + rs.getInt(3) + " bookingID: " + rs.getInt(4) + " phone number: " + rs.getLong(5) + " address: " + rs.getString(6));
cx = new Customer(rs.getInt(1), rs.getLong(5), rs.getString(6));
cx.addMembership(null);// If memberships are added in the future, this will be changed to retrieve a membership
return cx;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static int createCustomer(int ID, int checkedIn, int booking_id, long phone , String address, String notes, String important_notes, int ticketID) {
//Insert or Update customer in SQL customer
String query = "USE hotel;\n INSERT INTO customer VALUES (";
//Build query based on passed information
query = query + "'" + String.valueOf(ID) + "', ";
query = query + "'" + String.valueOf(0) + "', ";
query = query + "'" + String.valueOf(checkedIn) + "'";
query = query + "'" + String.valueOf(booking_id) + "'";
query = query + "'" + String.valueOf(phone) + "'";
query = query + "'" + address + "'";
query = query + "'" + notes + "'";
query = query + "'" + important_notes + "'";
query = query + "'" + String.valueOf(ticketID) + "'";
query = query + ");";
//If connection is not created Notify user
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
//Attempt to insert into DB
try {
Statement st = con.createStatement();
System.out.println(query);
st.executeUpdate(query);
}
catch (Exception e) { //If user cannot be inserted in DB print error and return -1
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return 0; //return 0 on success
}
//----------------------------------Bookings---------------------------------------------------//
static public Booking getBooking(int clientID, int roomID, Date checkInDate, Date checkOutDate) {
//Add date format to convert to sql date
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Build Query
String query = "SELECT * FROM hotel.booking WHERE customer_id IS NOT NULL";
if (clientID != 0) {query = query + " AND customer_id = " + String.valueOf(clientID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
//Convert date to sql date format and add to query
if (checkInDate != null) {
String currentTime = sdf.format(checkInDate);
query = query + " AND checkin_date = '" + String.valueOf(currentTime) + "'";
}
//Convert date to sql date format and add to query
if (checkOutDate != null) {
String currentTime = sdf.format(checkOutDate);
query = query + " AND checkout_date = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database"); //If connection cannot be created, will throw error
}
try {
//use connection to execute query
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Booking book = null;
if (rs.next()) { //If results are found
//Store DB variables in local variables
int CID = rs.getInt(1);
int RID = rs.getInt(2);
String CIDate = rs.getString(3);
Date in = sdf.parse(CIDate);
String CODate = rs.getString(4);
Date out = sdf.parse(CODate);
//Get Customer, Get Room then Return complete Booking
Customer c = getBookingCustomer(CID);
Room r = getRoom(RID, null, null, 0, null);
book = new Booking(c, r, in, out);
c.setBooking(book);
book.setClient(c);
return book;
}
else { //If no results found, inform user and return null
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
static public ArrayList<Booking> getBookings(int clientID, int roomID, Date checkInDate, Date checkOutDate) {
//Same as Bookings however returns all results not just first result
//Add date format to convert to sql date
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Build query
String query = "SELECT * FROM hotel.booking WHERE customer_id IS NOT NULL";
if (clientID != 0) {query = query + " AND customer_id = " + String.valueOf(clientID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
if (checkInDate != null) {
String currentTime = sdf.format(checkInDate);
query = query + " AND checkin_date = '" + String.valueOf(currentTime) + "'";
}
if (checkOutDate != null) {
String currentTime = sdf.format(checkOutDate);
query = query + " AND checkout_date = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
//inform user if connection cannot be created
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
//Attempt to execute query using connection
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ArrayList<Booking> bookings= new ArrayList<Booking>();
//loop through all results
while (rs.next()) {
//Store DB variables in local Variables
int CID = rs.getInt(1);
int RID = rs.getInt(2);
String CIDate = rs.getString(3);
Date in = sdf.parse(CIDate);
String CODate = rs.getString(4);
Date out = sdf.parse(CODate);
//Get Customer, Get Room then Return complete Booking
Customer c = getBookingCustomer(CID);
Room r = getRoom(RID, null, null, 0, null);
Booking book = new Booking(c, r, in, out);
c.setBooking(book);
book.setClient(c);
bookings.add(book);
}
return bookings; //Return array list of bookings
}
catch (Exception e) { //If exception occurs, return false
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
static private Booking getCustomerBooking(int clientID) {
//Special case of get booking, only used locally
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.booking WHERE customer_id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (clientID != 0) {query = query + " AND customer_id = " + String.valueOf(clientID);}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Booking book = null;
if (rs.next()) {
int RID = rs.getInt(2);
String CIDate = rs.getString(3);
Date in = sdf.parse(CIDate);
String CODate = rs.getString(4);
Date out = sdf.parse(CODate);
//Since it's a customer booking set customer to null, get room and return
Customer c = null;
Room r = getRoom(RID, null, null, 0, null);
book = new Booking(c, r, in, out);
return book;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
static private Booking getRoomBooking(int booking_id) {
//Special case of booking only used locally
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.booking WHERE customer_id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (booking_id != 0) {query = query + " AND booking_id = " + String.valueOf(booking_id);}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Booking book = null;
if (rs.next()) {
String CIDate = rs.getString(3);
Date in = sdf.parse(CIDate);
String CODate = rs.getString(4);
Date out = sdf.parse(CODate);
//Since it's a customer booking set customer to null, get room and return
Customer c = null;
Room r = null; //REMEMBER TO CHANGE THIS TO GET ROOM
book = new Booking(c, r, in, out);
return book;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static int createBooking(int ID, int customerID, int roomID, Date in, Date out) {
//Add date parser to convert java Date into MySQL date format
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//Insert into hotel booking table
String query = "USE hotel;\n INSERT INTO booking VALUES (";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
query = query + "'" + String.valueOf(ID) + "', ";
query = query + "'" + String.valueOf(customerID) + "', ";
query = query + "'" + String.valueOf(roomID) + "'";
String inDate = sdf.format(in);
query = query + "'" + String.valueOf(inDate) + "'";
String outDate = sdf.format(out);
query = query + "'" + String.valueOf(outDate) + "'";
query = query + ");";
//If connection cannot be created inform user
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
//Attempt to execute insert statement
Statement st = con.createStatement();
System.out.println(query);
st.executeUpdate(query);
}
catch (Exception e) { //If error occurs, print exception and return -1
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return 0; //return 0 on success
}
//----------------------------------Shift---------------------------------------------------//
static public Shift getShift(String employeeID, Date day, float time) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.shift WHERE employee_id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (employeeID != null) {query = query + " AND employee_id = '" + employeeID + "'";}
if (time != 0) {query = query + " AND time = " + String.valueOf(time);}
if (day != null) {
String currentTime = sdf.format(day);
query = query + " AND date = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Shift shift = null;
if (rs.next()) {
String UID = rs.getString(0);
String CIDate = rs.getString(1);
float thyme = rs.getInt(2);
Date SHDate = sdf.parse(CIDate);
shift = new Shift( UID, SHDate, thyme);
return shift;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
static public ArrayList<Shift> getShifts(String employeeID, Date day, float time) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.shift WHERE employee_id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (employeeID != null) {query = query + " AND employee_id = '" + employeeID + "'";}
if (time != 0) {query = query + " AND time = " + String.valueOf(time);}
if (day != null) {
String currentTime = sdf.format(day);
query = query + " AND date = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ArrayList<Shift> shifts = new ArrayList<Shift>();
while (rs.next()) {
String UID = rs.getString(0);
String CIDate = rs.getString(1);
float thyme = rs.getInt(2);
Date SHDate = sdf.parse(CIDate);
Shift shift = new Shift( UID, SHDate, thyme);
shifts.add(shift);
}
return shifts;
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
public static int createBooking(int ID, Date day, float time, int changed) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "USE hotel;\n INSERT INTO booking VALUES (";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
query = query + "'" + String.valueOf(ID) + "', ";
String inDate = sdf.format(time);
query = query + "'" + String.valueOf(inDate) + "'";
query = query + "'" + String.valueOf(changed) + "', ";
query = query + ");";
System.out.println(query);
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
System.out.println(query);
st.executeUpdate(query);
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return -1;
}
//----------------------------------Wake_up---------------------------------------------------//
static public WakeUpTimer getWakeUp(int id, Date time) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.wake_up WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (id != 0) {query = query + " AND id = " + String.valueOf(id);}
if (time != null) {
String currentTime = sdf.format(time);
query = query + " AND date = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
WakeUpTimer timer = null;
if (rs.next()) {
int ID = rs.getInt(0);
String CIDate = rs.getString(1);
Date SHDate = sdf.parse(CIDate);
timer = new WakeUpTimer( ID, SHDate);
return timer;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get RoomService Ticket---------------------------------------------------//
public static RoomServiceTicket getRoomServiceTicket(int ticketID, int roomID, Date openTime) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.room_service_ticket WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ticketID != 0) {query = query + " AND id = " + String.valueOf(ticketID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
if (openTime != null) {
String currentTime = sdf.format(openTime);
query = query + " AND open_time = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
System.out.println(query);
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
RoomServiceTicket tckt = null;
if (rs.next()) {
//Store from DB in local variables
int RID = rs.getInt(1);
String openT = rs.getString(1);
Date dateOpen = sdf.parse(openT);
String reqT = rs.getString(5);
Date dateReq = sdf.parse(reqT);
String desc = rs.getString(6);
String specReq = rs.getString(7);
tckt = new RoomServiceTicket(RID, dateOpen, dateReq, desc, specReq);
return tckt;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get Maintenance Ticket---------------------------------------------------//
public static MaintenanceTicket getMaintenanceTicket(int ticketID, int roomID, Date openTime) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.maintenance_ticket WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ticketID != 0) {query = query + " AND id = " + String.valueOf(ticketID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
if (openTime != null) {
String currentTime = sdf.format(openTime);
query = query + " AND open_time = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
MaintenanceTicket tckt = null;
if (rs.next()) {
//Store from DB in local variables
int RID = rs.getInt(1);
String openT = rs.getString(2);
Date dateOpen = sdf.parse(openT);
int comp = rs.getInt(3);
String desc = rs.getString(4);
tckt = new MaintenanceTicket(desc, RID, dateOpen, (comp != 0) );
return tckt;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get cleaning Ticket---------------------------------------------------//
public static CleaningTicket getCleaningTicket(int ticketID, int roomID, Date openTime) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.cleaning_ticket WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ticketID != 0) {query = query + " AND id = " + String.valueOf(ticketID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
if (openTime != null) {
String currentTime = sdf.format(openTime);
query = query + " AND open_time = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
CleaningTicket tckt = null;
if (rs.next()) {
//Store from DB in local variables
int RID = rs.getInt(1);
String openT = rs.getString(2);
Date dateOpen = sdf.parse(openT);
int comp = rs.getInt(3);
String desc = rs.getString(4);
tckt = new CleaningTicket(desc, RID, dateOpen, (comp != 0) );
return tckt;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get complaint Ticket---------------------------------------------------//
public static ComplaintTicket getComplaintTicket(int ticketID, int roomID, Date openTime) {
//Add date parser to convert java Date into MySQL date format
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.complaint_ticket WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (ticketID != 0) {query = query + " AND id = " + String.valueOf(ticketID);}
if (roomID != 0) {query = query + " AND room_id = " + String.valueOf(roomID);}
if (openTime != null) {
String currentTime = sdf.format(openTime);
query = query + " AND open_time = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
ComplaintTicket tckt = null;
if (rs.next()) {
//Store from DB in local variables
int RID = rs.getInt(1);
String openT = rs.getString(2);
Date dateOpen = sdf.parse(openT);
int comp = rs.getInt(3);
String desc = rs.getString(4);
tckt = new ComplaintTicket(desc, RID, dateOpen, (comp != 0) );
return tckt;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get Order Request---------------------------------------------------//
public static ArrayList<OrderRequest> getOrderRequest(String reqID, int complete, int denied, Date openTime) {
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String query = "SELECT * FROM hotel.order_request WHERE requester_id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
if (reqID != null) {query = query + " AND requester_id = '" + reqID + "'";}
if (complete != -1) {query = query + " AND complete = " + String.valueOf(complete);}
if (denied != -1) {query = query + " AND denied = " + String.valueOf(denied);}
if (openTime != null) {
String currentTime = sdf.format(openTime);
query = query + " AND open_time = '" + String.valueOf(currentTime) + "'";
}
query = query + ";";
System.out.println(query);
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
ArrayList<OrderRequest> orders = new ArrayList<OrderRequest>();
try {
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
//System.out.println("ID: " + rs.getInt(1) + " memID: " + rs.getString(2) + " Checked In: " + rs.getInt(3) + " bookingID: " + rs.getInt(4) + " phone number: " + rs.getLong(5) + " address: " + rs.getString(6));
//Store from DB in local variables
String RID = rs.getString(0);
String item = rs.getString(1);
int quan = rs.getInt(2);
String openT = rs.getString(2);
Date dateOpen = sdf.parse(openT);
int comp = rs.getInt(3);
int den = rs.getInt(4);
orders.add(new OrderRequest(RID, item, quan, dateOpen, (comp != 0), (den != 0) ));
}
return orders;
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Get Employee---------------------------------------------------//
public static Employee getEmployee(String ID, PermissionType permission) {
//Using hotelDB employee
String query = "SELECT * FROM hotel.employee WHERE id IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first Employee which matches the description
if (ID != null) {query = query + " AND id = '" + ID +"'";}
if (permission != null) {query = query + " AND permission_level = " + permission.name();}
query = query + ";";
//If connection cannot be created, will throw error
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
//Attempt to execute statement using connection
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
Employee emp = null;
if (rs.next()) {
//Store from DB in local variables
String name = rs.getString(2);
String role = rs.getString(4);
PermissionType perm = PermissionType.valueOf(rs.getString(1));
Float wage = rs.getFloat(3);
emp = new DeskAttendant(perm, name, role, wage );
return emp;
}
else {
System.out.println("No results found matching query");
return null;
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return null;
}
}
//----------------------------------Accounts---------------------------------------------------//
public static int Login(String username, String password) {
//Using hotel accounts table
String query = "SELECT * FROM hotel.accounts WHERE type IS NOT NULL";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
query = query + " AND user = " + username + "'";
query = query + ";";
//If connection cannot be created, will throw error
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
//attempt to use connection to execute Query
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
//If no user found return -1
if (!rs.next()) {
return -1;
}
if (rs.next()) {
//Store from DB in local variables
String user = rs.getString(0);
String pass = rs.getString(1);
//Compare username and password provided with DB username and password
if (user == username && pass == password) {
return rs.getInt(2); //type of account 0 is normal, 1 is employee
}
}
}
catch (Exception e) {
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return -1;
}
public static int createAccount(String username, String password, int type) {
//Insert into hotel table accounts
String query = "USE hotel;\n INSERT INTO accounts VALUES (";
//Build query based on passed information, if none are passed the query will just return the first customer which matches the description
query = query + "'" + username + "', ";
query = query + "'" + password + "', ";
query = query + "'" + String.valueOf(type) + "'";
query = query + ");";
//Attempt to create Connection
if (!createConnection()) {
System.out.println("Could not connect to Database");
}
try {
//attempt to execute insert statement
Statement st = con.createStatement();
System.out.println(query);
st.executeUpdate(query);
}
catch (Exception e) {
//If account is not inserted print error and return -1
System.out.println("Oh No");
e.printStackTrace();
return -1;
}
return 0;
}
}
|
package me.ewriter.chapter2.weatherobservable;
/**
* Created by Zubin on 2016/10/12.
* 这个和上面weather 包下面的区别主要就是这里的观察者模式使用的是java 里面自带的Observable 和 observer
* 但是这种方式有个缺点就是必须使用extends 继承,使用还是有不方便
*/
public class WeatherStation {
public static void main(String[] args) {
WeatherData weatherData = new WeatherData();
//其他几个观察者类似,就不再重复写了
CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData);
weatherData.setMeasurements(80, 65, 30.4f);
}
}
|
package com.cyou.paycallback.resource.impl;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import com.cyou.paycallback.resource.Resource;
import com.cyou.paycallback.util.StringUtils;
public class ClassPathResource implements Resource {
private String classPath;
private File classFile;
public ClassPathResource() {
// TODO Auto-generated constructor stub
}
public ClassPathResource(String classPath) {
this.classPath = classPath;
}
public List<File> getFile() {
if (StringUtils.isEmpty(classPath))
throw new NullPointerException("classPath is null");
classPath = classPath.substring(classPath.indexOf(":") + 1);
List<File> result = new ArrayList<File>();
String[] paths = classPath.split(",");
for (String path : paths) {
String realPath = Thread.currentThread().getContextClassLoader().getResource(path).getPath();
classFile = new File(realPath);
getFiles(classFile, result);
}
// String[] paths = classPath.split(",");
// FileInputStream fileInputStream = null;
// FileChannel outChannel = null;
// try {
// for (int i = 0; i < paths.length; i++) {
// String path =
// Thread.currentThread().getContextClassLoader().getResource(paths[i]).getPath();
// File file = new File(path);
// if (i == 0) {
// classFile = new File(path);
// outChannel = new FileOutputStream(classFile).getChannel();
// } else {
// fileInputStream = new FileInputStream(file);
// FileChannel fc = fileInputStream.getChannel();
// ByteBuffer bb = ByteBuffer.allocate(BUFFIZE);
// while (fc.read(bb) != -1) {
// bb.flip();
// outChannel.write(bb);
// bb.clear();
// }
// fc.close();
// }
// }
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// } finally {
// try {
// if (outChannel != null) {
// outChannel.close();
// }
// } catch (IOException ignore) {
// }
// }
return result;
}
private List<File> getFiles(File file, List<File> fileList) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
getFiles(f, fileList);
}
}
} else {
fileList.add(file);
}
return fileList;
}
@Override
public InputStream getInputStream() {
// TODO Auto-generated method stub
return null;
}
public String getClassPath() {
return classPath;
}
public void setClassPath(String classPath) {
this.classPath = classPath;
}
@Override
public boolean exists() {
return classFile == null ? false : classFile.exists();
}
}
|
/*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.converter.impl;
import xyz.noark.core.annotation.DateTimeFormat;
import xyz.noark.core.annotation.TemplateConverter;
import xyz.noark.core.converter.Converter;
import xyz.noark.core.exception.ConvertException;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
/**
* Date类型的转化器.
*
* @author 小流氓[176543888@qq.com]
* @since 3.1
*/
@TemplateConverter(Date.class)
public class DateConverter implements Converter<Date> {
@Override
public String buildErrorMsg() {
return "不是一个Date类型的字符串";
}
@Override
public Date convert(Field field, String value) throws Exception {
return this.convert(field.getAnnotation(DateTimeFormat.class), value);
}
@Override
public Date convert(Parameter parameter, String value) throws Exception {
if (value == null) {
return null;
}
return this.convert(parameter.getAnnotation(DateTimeFormat.class), value);
}
private Date convert(DateTimeFormat format, String value) throws ParseException {
return new SimpleDateFormat(format == null ? "yyyy-MM-dd HH:mm:ss" : format.pattern()).parse(value);
}
@Override
public Date convert(Field field, Map<String, String> data) throws Exception {
throw new ConvertException("DateConverter无法转化Map类型的配置...");
}
}
|
package com.sinodynamic.hkgta.service.crm.backoffice.membership;
import com.sinodynamic.hkgta.entity.crm.CustomerProfile;
import com.sinodynamic.hkgta.service.IServiceBase;
import com.sinodynamic.hkgta.util.ResponseMsg;
public interface EditMemberProfileService extends IServiceBase<CustomerProfile>{
public ResponseMsg editMemberProfile(CustomerProfile dto,String userId);
}
|
package me.basiqueevangelist.datapackify.mixins;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import net.minecraft.village.TradeOffers;
import net.minecraft.village.VillagerProfession;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.gen.Accessor;
import java.util.Map;
@Mixin(TradeOffers.class)
public interface TradeOffersAccessor {
@Accessor("PROFESSION_TO_LEVELED_TRADE")
@Mutable
static void setTrades(Map<VillagerProfession, Int2ObjectMap<TradeOffers.Factory[]>> map) {
throw new UnsupportedOperationException("Mixin failed to apply");
}
@Accessor("WANDERING_TRADER_TRADES")
@Mutable
static void setWanderingTrades(Int2ObjectMap<TradeOffers.Factory[]> map) {
throw new UnsupportedOperationException("Mixin failed to apply");
}
}
|
package com.example.sosso.newsapplication.network;
import com.example.sosso.newsapplication.QueryResult;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ArticleService {
@GET("top-headlines")
Call<QueryResult> listNews(@Query("country") String country, @Query("apiKey") String apiKey);
}
|
package OOP.Functions;
public class Main {
public static void main(String[] args) {
Box Box1 = new Box();
Box Box2 = new Box();
Box1.length = 5;
Box1.width = 4;
Box1.height= 10;
Box2.length = 12;
Box2.width = 40;
Box2.height= 3;
Box1.getVolume();
Box2.getVolume();
int volume1 = Box1.volumeReturn();
int volume2 = Box2.volumeReturn();
System.out.println(volume1);
System.out.println(volume2);
}
}
|
/**
* 湖北安式软件有限公司
* Hubei Anssy Software Co., Ltd.
* FILENAME : SiteTypeVo.java
* PACKAGE : com.anssy.venturebar.site.vo
* CREATE DATE : 2016-8-17
* AUTHOR : make it
* MODIFIED BY :
* DESCRIPTION :
*/
package com.anssy.venturebar.site.vo;
/**
* @author make it
* @version SVN #V1# #2016-8-17#
*/
public class SiteTypeVo {
/**
* 类型(场地)
*/
private Long type;
private Long[] types;
/**
* 搜索词组
*/
private String search;
/**
* 省ID
*/
private Long provinceId;
/**
* 市ID
*/
private Long cityId;
/**
* 区县ID
*/
private Long areaId;
private int being;
private int end;
public Long getType() {
return type;
}
public void setType(Long type) {
this.type = type;
}
public Long[] getTypes() {
return types;
}
public void setTypes(Long[] types) {
this.types = types;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public Long getProvinceId() {
return provinceId;
}
public void setProvinceId(Long provinceId) {
this.provinceId = provinceId;
}
public Long getCityId() {
return cityId;
}
public void setCityId(Long cityId) {
this.cityId = cityId;
}
public Long getAreaId() {
return areaId;
}
public void setAreaId(Long areaId) {
this.areaId = areaId;
}
public int getBeing() {
return being;
}
public void setBeing(int being) {
this.being = being;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
|
package rl4j;
public class CosineSimilarity extends Similarity {
@Override
public double similarity(double[] a, double[] b, double threshold) {
if (a.length != b.length) {
throw new IllegalArgumentException("The two must be the same length");
}
int n_aIb = 0;
int n_a = 0;
int n_b = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] >= threshold) {
n_a++;
}
if (b[i] >= threshold) {
n_b++;
}
if (a[i] >= threshold && b[i] >= threshold) {
n_aIb++;
}
}
double combinedNorms = Math.sqrt(n_a * n_b);
return combinedNorms == 0 ? 0 : ((double) n_aIb / combinedNorms);
}
}
|
package edu.mit.cameraCulture.vblocks.predefined;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import edu.mit.cameraCulture.vblocks.EngineActivity;
import edu.mit.cameraCulture.vblocks.Module;
import edu.mit.cameraCulture.vblocks.Sample;
import edu.mit.cameraCulture.vblocks.Module.ExecutionCode;
import edu.mit.cameraCulture.vblocks.utils.Storage;
public class TakeRawPicture extends Module{
public static final String REGISTER_SERVICE_NAME = "Take Raw Picture";
private Bitmap bitmapImg;
// Mat used by the module
Mat mYUV_Mat;
// Image Properties
private int imgWidth;
private int imgHeight;
public TakeRawPicture() {
super(REGISTER_SERVICE_NAME);
}
public ExecutionCode execute(Sample image) {
//convert to bitmap and save
// Initialize an instance of Storage, used to save the image in the phone
Storage mStorage = new Storage(this.mContext);
mStorage.save(image.getImageData());
imgWidth = image.getWidth();
imgHeight = image.getHeight();
mYUV_Mat = image.getYUVMat();
// Transform mYUV_Mat to RGB. Since YUV Mat is unchanged, it has the raw image.
Mat mRgb_Mat = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC4 );
Imgproc.cvtColor(mYUV_Mat, mRgb_Mat, Imgproc.COLOR_YUV420sp2RGB, 4);
bitmapImg = Bitmap.createBitmap(imgWidth, imgHeight, Bitmap.Config.ARGB_8888);
// Convert mRgb_Mat to bitmap
Utils.matToBitmap(mRgb_Mat, bitmapImg);
mStorage.save(bitmapImg);
System.gc();
return null;
}
public String getName() {
return "Take Raw Picture";
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
public static String getModuleName(){
return "Take Raw Picture";
}
public void onCreate(EngineActivity context){
super.onCreate(context);
}
}
|
package vo;
public enum TeamSortBy {
name,// 队伍名称
matchNo, // 比赛场数
hitNo,// 投篮命中数
handNo, // 投篮出手次数
threeHitNo, // 三分命中数
threeHandNo, // 三分出手数
penaltyHitNo, // 罚球命中数
penaltyHandNo, // 罚球出手数
offenseRebs, // 进攻篮板数
defenceRebs, // 防守篮板数
rebs, // 篮板数
assistNo,// 助攻数
stealsNo, // 抢断数
blockNo, // 盖帽数
mistakesNo, // 失误数
foulsNo, // 犯规数
points, // 比赛得分
hitRate, // 投篮命中率
threeHitRate,// 三分命中率
penaltyHitRate,// 罚球命中率
winRate, // 胜率
offenseRound, // 进攻回合
offenseEfficiency,// 进攻效率
defenceEfficiency,// 防守效率
orebsEfficiency,// 进攻篮板效率
drebsEfficiency,//防守篮板效率
stealsEfficiency,// 抢断效率
assistEfficiency// 助攻率
}
|
import java.util.ArrayList;
import java.util.Random;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Spinner;
import javafx.scene.layout.Border;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class BoardGame extends Application {
Random rnd = new Random();
Player currentPlayer;
ArrayList players = new ArrayList<Player>();
int currentPlayerIndex=0;
Spinner snakecounter= new Spinner(2, 6, 1,1);
Spinner laddercounter= new Spinner(2, 6, 1,1);
Paint[] fills = new Paint[4];
Circle playerCircle = new Circle(15.0);
Label winnerLbl = new Label();
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.TOP_CENTER);
Button rollDice = new Button("Roll Dice");
HBox hbox = new HBox(5.0,rollDice);
hbox.setAlignment(Pos.CENTER);
VBox vbox = new VBox(5.0, grid,hbox);
StackPane root = new StackPane();
Canvas canvas = new Canvas(500, 650);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setLineWidth(5);
vbox.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 500, 650);
GameBoard.initialiseSquares();
for(Integer i =1;i<101;i++){
GridTiles sq = GameBoard.squares[i];
grid.add(sq,sq.getGridX(),sq.getGridY());
}
playerCircle.setFill(new Color(0, 0, 0, 0));
Button addPlayer = new Button("Add Player");
addPlayer.setOnAction(e-> {
if(Player.NumberOfPlayers<4){
Player pl = new Player();
players.add(pl);
grid.add(pl,0,9);
fills[Player.NumberOfPlayers-1]=pl.getFill();
playerCircle.setFill(fills[0]);
}
});
grid.setGridLinesVisible(true);
root.getChildren().add(canvas);
root.getChildren().add(vbox);
Rectangle winRect = new Rectangle(500, 650);
Rectangle winRect2 = new Rectangle(500, 650);
hbox.getChildren().add(addPlayer);
rollDice.setOnAction(e->{
if(Player.NumberOfPlayers==0){
}else{
currentPlayer=(Player)players.get(currentPlayerIndex);
currentPlayer.move( getSpinnerNum());
currentPlayerIndex++;
if(currentPlayerIndex>=Player.NumberOfPlayers)
currentPlayerIndex-=Player.NumberOfPlayers;
playerCircle.setFill(fills[currentPlayerIndex]);
if(Player.winnerNum>=0){
winnerLbl.setText("Player "+Player.winnerNum+" wins!");
winRect.setFill(fills[Player.winnerNum-1]);
winRect2.setFill(fills[Player.winnerNum-1]);
winnerLbl.setBorder(Border.EMPTY);
root.getChildren().add(winRect);
root.getChildren().add(winRect2);
root.getChildren().add(winnerLbl);
}
}
});
{
GameBoard.snakes=3;
GameBoard.ladders=3;
gc.clearRect(0, 0, 500, 650);
GameBoard.initialiseSnL();
for(Integer i=1;i<101;i++){
if(GameBoard.squares[i].getDestSquare()!=null){
if(GameBoard.squares[i].getDestSquare().getSqNumber()<GameBoard.squares[i].getSqNumber())
gc.setStroke(Color.RED);
else if(GameBoard.squares[i].getDestSquare().getSqNumber()>GameBoard.squares[i].getSqNumber())
gc.setStroke(Color.GREEN);
gc.strokeLine((GameBoard.squares[i].getGridX())*50+25, (GameBoard.squares[i].getGridY())*50+25,
(GameBoard.squares[i].getDestSquare().getGridX())*50+25,
(GameBoard.squares[i].getDestSquare().getGridY())*50+25);
}
}
primaryStage.setScene(scene);
primaryStage.centerOnScreen();
}
primaryStage.setTitle("Snakes and Ladders");
primaryStage.show();
}
public int getSpinnerNum() {
// TODO Auto-generated method stub
Integer num = rnd.nextInt(6)+1;
return num;
}
public static void main(String[] args) {
launch(args);
}
}
|
package com.example.netflix_project.src.main.home.Adapter;
import androidx.recyclerview.widget.RecyclerView;
public class YoutubeAdapter {
}
|
package com.karya.service;
import java.util.List;
import com.karya.model.Login001MB;
import com.karya.model.Menu001MB;
public interface ILoginService {
public Login001MB getLoginResult(String username, String password);
public List<Menu001MB> getMenuLink(String domain);
}
|
package locale;
public class lang extends lang_en {}
|
package Client;
import Dao.model.Comment;
import Dao.model.HotGoods;
import Dao.model.User;
import com.google.code.kaptcha.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2014/9/7 0007.
*/
@Controller
public class LoginClient {
private static Logger logger = LoggerFactory.getLogger(LoginClient.class);
@RequestMapping(value = "/login/show", method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
model.addAttribute(new User());
return "publishGoods";
}
@RequestMapping(value = "/login/result", method = RequestMethod.POST)
@ResponseBody
public String getLoginInfo(ModelMap model,
@RequestParam(value="username", required=true) String username,
@RequestParam(value="password", required=true) String password,
@RequestParam(value = "verifyCode") String verifyCode,
HttpServletRequest request,
HttpSession httpSession){
// System.out.println(username);
// System.out.println(password);
String code = (String)request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
code = code.toLowerCase();
verifyCode = verifyCode.toLowerCase();
if (verifyCode.equals(code)){
int userId = new RestTemplate().getForObject(
"http://localhost:8080/user/userId/{username}/{password}",
Integer.class, username, password);
// Comment[] comments = new RestTemplate().getForObject(
// "http://localhost:8080/comment/{userId}",
// Comment[].class,userId);
// model.addAttribute("message","success login");
// model.addAttribute("List",comments);
if(userId != 0){
httpSession.setAttribute("username", username);
httpSession.setAttribute("userId", userId);
httpSession.setAttribute("flag", true);
return "ok";
}
else
return "error";
}
else {
model.addAttribute("message","验证码错误");
return "error";
}
}
@RequestMapping(value = "/logout",method = RequestMethod.GET)
public String logout(HttpSession httpSession,Model model){
List<HotGoods> hotGoodsList = new RestTemplate().getForObject(
"http://localhost:8080/hotGoods", ArrayList.class);
model.addAttribute("hotGoodsList",hotGoodsList);
model.addAttribute(new User());
httpSession.removeAttribute("userId");
httpSession.setAttribute("flag",false);
return "redirect:/";
}
}
|
import java.awt.*;
import java.util.Scanner;
public class RectangleFun {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Width: ");
int userWidth = scan.nextInt();
System.out.print("Height: ");
int userHeight = scan.nextInt();
System.out.print("X: ");
int userXcord = scan.nextInt();
System.out.print("Y: ");
int userYcord = scan.nextInt();
Rectangle rec = new Rectangle(userXcord, userYcord, userWidth, userHeight);
double userPerimeter = 2 * (rec.getHeight() + rec.getWidth()); //replace height with length, FIX THIS
System.out.println("Peremiter: " + userPerimeter);
rec.setLocation((userXcord - 4),(userYcord + 2));
System.out.print("New location is (" + rec.getX() + "," + rec.getY() + ")");
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hw3;
import hw3.q01.Profiler;
import hw3.q01.MethodProfile;
import java.util.List;
import hw3.q02.*;
import hw3.q03.TextEditor;
import hw3.q04.ExpressionTree;
import hw3.q05.LeafInfo;
import hw3.q05.SearchTree;
import hw3.q05.SearchTreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
/**
*
* @author ribb0013
*/
public class Application {
public static void main(String[] args)
{
// Profiler.getSingleton().clear();
// Profiler profiler = Profiler.getSingleton();
// profiler.add("play"); // 1
// profiler.add("playOneLine"); // 4
// profiler.add("playOneLine");
// profiler.add("playOneLine");
// profiler.add("playOneLine");
// profiler.add("playOneMove"); // 10
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.add("playOneMove");
// profiler.getNumberOfMethodCalls();
// MethodProfile getProfile = profiler.getProfile("playOneLine");
// System.out.println(getProfile.percentOfCalls);
// List<MethodProfile> myList = profiler.getProfiles();
// for (int i = 0; i < myList.size(); i++) {
// System.out.println(myList.get(i).name);
// System.out.println(myList.get(i).count);
// System.out.println(myList.get(i).percentOfCalls);
// }
// FibonacciSequence instance = new FibonacciSequence();
// int expected = 0;
// int actual = instance.getFaster(0);
//
// int a = profiler.getNumberOfMethodCalls("get");
// System.out.println(a);
//
//
// TextEditor instance = new TextEditor();
// System.out.println("hackerSetValue");
// instance.setValue("12345");
// instance.replace(1,2,"ab");
// String result = instance.getValue();
//
// System.out.println(result);
// instance.hackerSetValue("ABCDE");
//
// //now ABCDE
// instance.undo();
//
// //now 12CDE
//
// result = instance.getValue();
// System.out.println(result);
// String e = "* + 8 4 - 7 / 6 3";
// ExpressionTree tree = new ExpressionTree(e);
// System.out.println(tree.getStructure());
// System.out.println(tree.getExpressionAsInfix());
// System.out.println(tree.getExpressionAsPostfix());
// System.out.println(tree.getExpressionAsPrefix());
// System.out.println("val is "+tree.getValue());
// System.out.println("testGetExpressionAsPrefixOneOperator_Addition");
//// String testPrefixExpr = "* + 8 4 - 7 / 6 3";
// String testPrefixExpr = "+ - 8 2 5";
// ExpressionTree instance = new ExpressionTree(testPrefixExpr);
//
// String expResult = "(*(+ 8 4)(- 7(/ 6 3)))";
// String result = instance.getExpressionAsPrefix();
// System.out.println(result);
// System.out.println("testGetExpressionAsPostfixOneOperator_Addition");
// String testPrefixExpr = "* + 8 4 - 7 / 6 3";
// ExpressionTree instance = new ExpressionTree(testPrefixExpr);
//
// String expResult = "((8 4 +)(7 (6 3 /)-)*)";
// String result = instance.getExpressionAsPostfix();
// System.out.println(expResult);
// System.out.println(result);
// System.out.println("testPerformanceOfGetFaster");
//
// FibonacciSequence instance = new FibonacciSequence();
// Profiler profiler = Profiler.getSingleton();
//
// profiler.clear();
// instance.getFaster(0);
// int expected = 1;
// int actual = profiler.getNumberOfMethodCalls("getFaster");
//// assertEquals("perormance of fib 0", expected, actual);
////
// profiler.clear();
// instance.getFaster(1);
// expected = 1;
// actual = profiler.getNumberOfMethodCalls("getFaster");
//// assertEquals("perormance of fib 1", expected, actual);
////
// profiler.clear();
// instance.getFaster(2);
// int expected = 3;
// int actual = profiler.getNumberOfMethodCalls("getFaster");
//// assertEquals("perormance of fib 2", expected, actual);
////
// profiler.clear();
// instance.getFaster(5);
// expected = 9;
// actual = profiler.getNumberOfMethodCalls("getFaster");
//// assertEquals("perormance of fib 5", expected, actual);
////
// profiler.clear();
// instance.getFaster(13);
// expected = 25;
// actual = profiler.getNumberOfMethodCalls("getFaster");
//// assertEquals("perormance of fib 13", expected, actual);
////
// profiler.clear();
// instance.getFaster(20);
// expected = 39;
// actual = profiler.getNumberOfMethodCalls("getFaster");
// assertEquals("perormance of fib 20", expected, actual);
SearchTree tree = new SearchTree();
List<SearchTreeNode> list = new LinkedList<>();
SearchTreeNode n = new SearchTreeNode();
n.data = "G";
n.children = new LinkedList<>();
list.add(n);
n = new SearchTreeNode();
n.data = "F";
n.children = new LinkedList<>();
for (SearchTreeNode node : list) {
n.children.add(node);
}
list.clear();
SearchTreeNode e = new SearchTreeNode();
e.data = "E";
e.children = new LinkedList<>();
for (SearchTreeNode node : list) {
e.children.add(node);
};
list.add(e);
list.add(n);
n = new SearchTreeNode();
n.data = "B";
n.children = new LinkedList<>();
for (SearchTreeNode node : list) {
n.children.add(node);
}
list.clear();
list.add(n);
n = new SearchTreeNode();
n.data = "C";
n.children = new LinkedList<>();
list.add(n);
n = new SearchTreeNode();
n.data = "D";
n.children = new LinkedList<>();
list.add(n);
n = new SearchTreeNode();
n.data = "A";
n.children = new LinkedList<>();
for (SearchTreeNode node : list) {
n.children.add(node);
}
tree.root = n;
// String struct = tree.getTreeStructure();
// System.out.println(struct);
// System.out.println(tree.getHeight());
//
// List<LeafInfo> leafList = new ArrayList<>();
//
// leafList = tree.getLevel();
//
// for (int i = 0; i < leafList.size(); i++) {
// System.out.print(leafList.get(i).item);
// System.out.println(leafList.get(i).level);
// }
// List<String> alist = new ArrayList<>();
// alist = tree.findBFS("G");
// System.out.println(alist.size());
//
// alist = tree.getPath("G");
// System.out.println(alist.size());
//
// for (int i = 0; i < alist.size(); i++) {
//
// System.out.println(alist.get(i));
// }
//
// System.out.println("findBFS2");
// List<String> actualPath = new LinkedList<>();
// actualPath.add("A");
// Profiler.getSingleton().clear();
// List<String> path = tree.findBFS("A");
// int actual = Profiler.getSingleton().getNumberOfMethodCalls();
// int expected = 0;
//
// System.out.println(actual);
// List<String> alist = new ArrayList<>();
// alist = tree.getLeaves();
//
// for (int i = 0; i < alist.size(); i++) {
// System.out.println(alist.get(i));
//
// }
//
// alist = tree.getPath("E");
// System.out.println(alist);
//
// tree.findDFS("G");
//
// List<String> actualPath = new LinkedList<>();
// actualPath.add("A");
// actualPath.add("B");
// actualPath.add("F");
// actualPath.add("G");
//
// int expected = 4;
// int actual = Profiler.getSingleton().getNumberOfMethodCalls("getChild");
//
// System.out.println(actual);
//
// }
//
// Profiler.getSingleton().clear();
// Profiler.getSingleton().clear();
// List<String> alist = new ArrayList<>();
// alist = tree.findBFS("G");
//
// System.out.println(Profiler.getSingleton().getNumberOfMethodCalls("getChild"));
//// int actual = Profiler.getSingleton().getNumberOfMethodCalls("getChild");
//// System.out.println(actual);
////
// for (int i = 0; i < alist.size(); i++) {
// System.out.println(alist.get(i));
//
// }
// SearchTree tree = new SearchTree();
// SearchTree instance = getTree();
// List<String> path = tree.findDFS("G");
// System.out.println(path);
// List<String> path = tree.findIDDFS("G");
List<String> path = tree.findDL("G", 4);
System.out.println(path);
}
}
|
package five.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* @author Tedikova O.
* @version 1.0
*/
public class ByteArrayIOTricks {
/**
* Writes array of bytes to {@link ByteArrayOutputStream} and then retrieves resulting array
*
* @param sourceBytes array of bytes
* @return resulting array of bytes
* @throws IOException in case of input/output exceptions
*/
public static byte[] rewriteBytes(byte[] sourceBytes) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(sourceBytes);
return outputStream.toByteArray();
}
/**
* Reads array of bytes from {@link ByteArrayInputStream} and then returns read array
*
* @param sourceBytes array of bytes
* @return read array of bytes
* @throws IOException in case of input/output exceptions
*/
public static byte[] readBytes(byte[] sourceBytes) throws IOException {
ByteArrayInputStream inputStream = new ByteArrayInputStream(sourceBytes);
int length = sourceBytes.length;
byte[] buffer = new byte[length];
int i = 0;
while (i < length) {
i += inputStream.read(buffer, i, length - i);
}
return buffer;
}
}
|
package com.hopu.bigdata.controller;
import com.hopu.bigdata.model.Userinfo;
import com.hopu.bigdata.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.security.Principal;
@Controller
public class IndexController {
@Autowired
private UserService userService;
@GetMapping({"/", "/index", "/home"})
public String index(@AuthenticationPrincipal Principal principal, Model model){
return "index";
}
}
|
package com.hp.roam.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
public class HttpUtils {
public static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
public static final ObjectMapper mapper = new ObjectMapper();
/**
* 设置上网代理
*/
public static HttpHost proxy = new HttpHost("web-proxy.cn.hpicorp.net", 8080, "http");
// public static final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
// .setSocketTimeout(60000).setConnectionRequestTimeout(10000).setProxy(proxy).build();
public static final RequestConfig requestConfig =
RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).setConnectionRequestTimeout(10000).build();
public static void getPic(String url, String filePath) {
logger.info("HttpUtils.getFile start......");
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(url);
get.setConfig(requestConfig);
InputStream in = null;
OutputStream out = null;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
in = entity.getContent();
long length = entity.getContentLength();
if (length <= 0) {
logger.info("下载文件不存在!");
}
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
}
out = new FileOutputStream(file);
byte[] buffer = new byte[4096];
int readLength = 0;
while ((readLength = in.read(buffer)) > 0) {
byte[] bytes = new byte[readLength];
System.arraycopy(buffer, 0, bytes, 0, readLength);
out.write(bytes);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("HttpUtils.getFile ended......");
}
}
/**
* 上传文件 带参数
*
* @return
*/
@SuppressWarnings("deprecation")
public static String postFile(File file, Map<String, String> params, String uploadUrl) {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost post = new HttpPost(uploadUrl);
HttpEntity reqEntity = null;
post.setConfig(requestConfig);
FileBody fileBody = new FileBody(file);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
try {
// 循环将params 加入到参数中
Set<Entry<String, String>> ketSet = params.entrySet();
for (Iterator<Entry<String, String>> iterator = ketSet.iterator(); iterator.hasNext();) {
Entry<String, String> entry = (Entry<String, String>) iterator.next();
if(!StringUtils.isEmpty(entry.getKey())){
StringBody comment = new StringBody((String) entry.getValue(), Charset.forName("UTF-8"));
builder.addPart((String) entry.getKey(), comment);
}
}
reqEntity = builder.build();
post.setEntity(reqEntity);
response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* get方法 获取
*
* @return
*/
public static String get(List<NameValuePair> params, String url) {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
try {
String str = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
logger.info("the param is" + str);
HttpGet get = new HttpGet(url + "?" + str);
get.setConfig(requestConfig);
response = client.execute(get);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* post方式提交数据 form表单形式提交
*
* @return
*/
public static String post(List<NameValuePair> params, String url) {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost post = new HttpPost(url);
post.setConfig(requestConfig);
try {
HttpEntity reqEntity = new UrlEncodedFormEntity(params);
post.setEntity(reqEntity);
response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
logger.info("the method post result is -------" + result);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* use json params to post
* @param params
* @param url
* @return
*/
public static String postJson(String params, String url) {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPost post = new HttpPost(url);
post.setConfig(requestConfig);
try {
HttpEntity reqEntity = new StringEntity(params, "UTF-8");
post.setHeader("Content-type", "application/json");
post.setEntity(reqEntity);
response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* put方式 提交数据
*
* @param params
* @param url
* @return
*/
public static String put(String params, String url) {
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpPut put = new HttpPut(url);
put.setConfig(requestConfig);
try {
HttpEntity reqEntity = new StringEntity(params, "UTF-8");
put.setHeader("Content-type", "application/json");
put.setEntity(reqEntity);
response = client.execute(put);
String result = EntityUtils.toString(response.getEntity());
logger.info("the method put result is -------" + result);
Integer status = response.getStatusLine().getStatusCode();
return String.valueOf(status);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 获取网页内容
* @param url
* @return
*/
public static String getContent(String url){
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = null;
HttpGet get = new HttpGet(url);
get.setConfig(requestConfig);
try {
response = client.execute(get);
String result = EntityUtils.toString(response.getEntity());
return result;
} catch (Exception e) {
e.printStackTrace();
}finally{
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
|
package com.san.diseaseXUser;
import com.san.disease.Disease;
import com.san.user.User;
import java.io.Serializable;
public class DiseaseXUserPK implements Serializable {
private User user;
private Disease disease;
}
|
package by.herzhot.impl;
import by.herzhot.BaseDao;
import by.herzhot.ISupplierDao;
import by.herzhot.Supplier;
/**
* @author Herzhot
* @version 1.0
* 09.08.2016
*/
public class SupplierDaoImpl extends BaseDao<Supplier> implements ISupplierDao {
@Override
protected Class<Supplier> getPersistentClass() {
return Supplier.class;
}
}
|
package com.sun.tools.xjc.generator.annotation.spec;
import javax.xml.bind.annotation.XmlElementDecl;
import com.sun.codemodel.JAnnotationWriter;
import com.sun.codemodel.JType;
public interface XmlElementDeclWriter
extends JAnnotationWriter<XmlElementDecl>
{
XmlElementDeclWriter name(String value);
XmlElementDeclWriter namespace(String value);
XmlElementDeclWriter defaultValue(String value);
XmlElementDeclWriter scope(Class value);
XmlElementDeclWriter scope(JType value);
XmlElementDeclWriter substitutionHeadNamespace(String value);
XmlElementDeclWriter substitutionHeadName(String value);
}
|
/*
* Copyright (c) 2013 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.authn.remote;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.server.api.TranslationProfileManagement;
import pl.edu.icm.unity.server.authn.AbstractVerificator;
import pl.edu.icm.unity.server.authn.AuthenticationException;
import pl.edu.icm.unity.server.authn.AuthenticationResult;
import pl.edu.icm.unity.server.authn.CredentialExchange;
import pl.edu.icm.unity.server.utils.LogRecorder;
/**
* Base class that is nearly mandatory for all remote verificators. The remote verificator should extend it
* by implementing a {@link CredentialExchange} of choice. The implementation should obtain the
* {@link RemotelyAuthenticatedInput} (the actual coding should be done here) and before returning it should
* be processed by {@link #getResult(RemotelyAuthenticatedInput)} to obtain the final authentication result.
* <p>
* Additionally (to enable compatibility with sandbox authN facility) the extension must call
* {@link #startAuthnResponseProcessing(String...)} at the beginning of authN response verification and
* {@link #finishAuthnResponseProcessing(RemoteAuthnState, AuthenticationException, RemotelyAuthenticatedInput)} in case of any
* exception produced during verification.
*
* @author K. Benedyczak
*/
public abstract class AbstractRemoteVerificator extends AbstractVerificator
{
private TranslationProfileManagement profileManagement;
private InputTranslationEngine trEngine;
public AbstractRemoteVerificator(String name, String description, String exchangeId,
TranslationProfileManagement profileManagement, InputTranslationEngine trEngine)
{
super(name, description, exchangeId);
this.profileManagement = profileManagement;
this.trEngine = trEngine;
}
/**
* This method is calling {@link #processRemoteInput(RemotelyAuthenticatedInput)} and then
* {@link #assembleAuthenticationResult(RemotelyAuthenticatedContext)}.
* Usually it is the only one that is used in subclasses, when {@link RemotelyAuthenticatedInput}
* is obtained in an implementation specific way.
*
* @param input
* @return
* @throws EngineException
*/
protected AuthenticationResult getResult(RemotelyAuthenticatedInput input, String profile,
RemoteAuthnState state) throws AuthenticationException
{
RemoteAuthnStateImpl stateCasted = (RemoteAuthnStateImpl)state;
stateCasted.remoteInput = input;
RemoteVerificatorUtil util = new RemoteVerificatorUtil(identityResolver, profileManagement, trEngine);
AuthenticationResult result = util.getResult(input, profile, stateCasted.isInSandboxMode());
finishAuthnResponseProcessing(state, result.getRemoteAuthnContext());
return result;
}
/**
* Should be called at the beginning of authN response verification
* @param loggingFacilities logging facilities relevant for the verification process
* @return
*/
protected RemoteAuthnState startAuthnResponseProcessing(SandboxAuthnResultCallback callback,
String... loggingFacilities)
{
RemoteAuthnStateImpl ret = new RemoteAuthnStateImpl(loggingFacilities, callback);
return ret;
}
/**
* Should be called at the end of properly finished verification. Handled internally.
* @param state
* @param context
*/
private void finishAuthnResponseProcessing(RemoteAuthnState state, RemotelyAuthenticatedContext context)
{
RemoteAuthnStateImpl stateCasted = (RemoteAuthnStateImpl)state;
if (stateCasted.isInSandboxMode())
{
LogRecorder recorder = stateCasted.logRecorder;
recorder.stopLogRecording();
stateCasted.sandboxCallback.sandboxedAuthenticationDone(
new RemoteSandboxAuthnContext(context,
recorder.getCapturedLogs().toString()));
}
}
/**
* Should be called at the end of failed verification.
* @param state
* @param error
* @param remoteInput can be null if failure was upon input assembly.
*/
protected void finishAuthnResponseProcessing(RemoteAuthnState state, Exception error)
{
RemoteAuthnStateImpl stateCasted = (RemoteAuthnStateImpl)state;
if (stateCasted.isInSandboxMode())
{
LogRecorder recorder = stateCasted.logRecorder;
recorder.stopLogRecording();
stateCasted.sandboxCallback.sandboxedAuthenticationDone(
new RemoteSandboxAuthnContext(error, recorder.getCapturedLogs().toString(),
stateCasted.remoteInput));
}
}
private class RemoteAuthnStateImpl implements RemoteAuthnState
{
private LogRecorder logRecorder;
private RemotelyAuthenticatedInput remoteInput;
private SandboxAuthnResultCallback sandboxCallback;
public RemoteAuthnStateImpl(String[] facilities, SandboxAuthnResultCallback sandboxCallback)
{
this.sandboxCallback = sandboxCallback;
logRecorder = new LogRecorder(facilities);
if (isInSandboxMode())
logRecorder.startLogRecording();
}
boolean isInSandboxMode()
{
return sandboxCallback != null;
}
}
/**
* Marker interface only. Implementation is an object holding a state of remote authentication. Currently used
* merely in sandbox mode.
* @author K. Benedyczak
*/
public interface RemoteAuthnState
{
}
}
|
package ru.otus.sua.L16;
import ru.otus.sua.L16.sts.CallbackHandler;
import ru.otus.sua.L16.sts.SocketTransferServiceClient;
import ru.otus.sua.L16.sts.SocketTransferServiceServer;
import ru.otus.sua.L16.sts.abstractions.Pollable;
import ru.otus.sua.L16.sts.abstractions.SocketTransferService;
import ru.otus.sua.L16.sts.entities.PingMsg;
import java.io.IOException;
public class TestRun {
public static void main(String[] args) throws InterruptedException, IOException {
SocketTransferService stsSrv =
new SocketTransferServiceServer(11121, "STS-SERVER");
pause();
SocketTransferService stsClnt =
new SocketTransferServiceClient(11121, "localhost", "STS-CLIENT");
pause();
stsSrv.send(new PingMsg("FromServer"));
pause();
System.out.println("check by client: " + stsClnt.poll());
System.out.println("check by client: " + stsClnt.poll());
pause();
stsClnt.send(new PingMsg("FromClient"));
pause();
System.out.println("check by server: " + stsSrv.poll());
System.out.println("check by server: " + stsSrv.poll());
pause();
CallbackHandler callback = new CallbackHandler(
10,1000,
(m)->System.out.println("by callback: " + m),
(Pollable) stsSrv);
callback.start();
pause();
for (int i = 0; i < 5; i++) {
stsClnt.send(new PingMsg("Check callbacking on arrived message FromClient " + i));
}
pause();
pause();
pause();
System.out.println("closing:");
stsClnt.close();
stsSrv.close();
callback.close();
pause();
SocketTransferService stsClnt2 =
new SocketTransferServiceClient(13121, "localhost", "NEVER-CLIENT");
pause();
pause();
stsClnt2.close();
pause();
}
private static void pause() throws InterruptedException {
Thread.sleep(1234);
System.out.println(".");
}
}
|
package com.parry.kevin.toppromo;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHandler extends SQLiteOpenHelper {
private static final int VERSION_BDD = 2;
private static final String NOM_BDD = "myDataBase.db";
private static final String METIER_KEY = "Id";
private static final String METIER_NOM = "Nom";
private static final String METIER_ADRESSE = "Adresse";
private static final String METIER_CP = "CodePostal";
private static final String METIER_VILLE = "Ville";
private static final String METIER_TABLE_NAME = "Magasins";
private static final String METIER_TABLE_CREATE = "CREATE TABLE " + METIER_TABLE_NAME + " (" + METIER_KEY + " INTEGER PRIMARY KEY, "
+ METIER_NOM + " TEXT, "
+ METIER_ADRESSE + " TEXT, "
+ METIER_CP + " TEXT, "
+ METIER_VILLE + " TEXT);";
private static final String METIER_TABLE_DROP = "DROP TABLE IF EXISTS " + METIER_TABLE_NAME + ";";
public DataBaseHandler(Context context) {
super(context, NOM_BDD, null, VERSION_BDD);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i("", "Creating database [" + METIER_TABLE_NAME + " v." + VERSION_BDD + "]...");
db.execSQL(METIER_TABLE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i("", "Upgrading database [" + METIER_TABLE_NAME + " v." + oldVersion + "] to [" + METIER_TABLE_NAME + " v." + newVersion + "]...");
db.execSQL(METIER_TABLE_DROP);
onCreate(db);
}
}
|
package hello;
import io.spring.guides.gs_producing_web_service.GetClientRequest;
import io.spring.guides.gs_producing_web_service.GetClientResponse;
import io.spring.guides.gs_producing_web_service.GetPlaceResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
@Endpoint
public class ClientEnd {
private static final String NAMESPACE_URI = "http://spring.io/guides/gs-producing-web-service";
private ClientRepository clientRepository;
@Autowired
public ClientEnd(ClientRepository clientRepository) {
this.clientRepository = clientRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getClientRequest")
@ResponsePayload
public GetClientResponse getClient(@RequestPayload GetClientRequest request) {
GetClientResponse response = new GetClientResponse();
response.setClient(clientRepository.findCountry(request.getId()));
return response;
}
@PayloadRoot(localPart = "", namespace = NAMESPACE_URI)
@ResponsePayload
public GetPlaceResponse getPlace() {
GetPlaceResponse response = new GetPlaceResponse();
return response;
}
}
|
package ac.za.cput.adp3.xyzcongolmerate.factory.user;
import ac.za.cput.adp3.xyzcongolmerate.domain.user.UserDemography;
import org.junit.Assert;
import org.junit.Test;
import java.util.Calendar;
import java.util.GregorianCalendar;
import static org.junit.Assert.*;
public class UserDemographyFactoryTest {
@Test
public void buildUserDemography() {
Calendar cal = new GregorianCalendar(1994, 07, 19);
UserDemography userDemography = UserDemographyFactory.buildUserDemography("xyz.phil@outlook.com",
"Mr", "GF","Black",cal.getTime());
Assert.assertNotNull(userDemography);
System.out.println(userDemography.toString());
}
}
|
package com.krt.gov.common.utils;
import javax.servlet.http.HttpServletRequest;
public class CommonUtil {
public static String getIconUrl(String file) {
return "https://iot.krtyun.com/iot-mqttgov/dist/img/icon/"+file;
}
public static String getLayoutUrl(String file) {
return "https://iot.krtyun.com/iot-mqttgov/dist/img/layout/"+file;
}
}
|
package dayEXTRA;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class MeanMeMo {
protected static Scanner input;
public static void main(String[] args) {
// TODO Auto-generated method stub
// statistik(new int[] {5,2,5,5,2,1,2,9,7,8,3,9,2,1,4,5,2,2,4,6,2,1,2});
// statistik(new int[] { 9, 2, 1, 2, 1, 31, 23, 12, 4, 10, 11, 12, 13, 14, 121,
// 2, 3, 12, 31, 231, 2312, 41, 54, 6, 4, 8, 5, 6, 7, 4, 3, 54, 35 });
// mean(new int[] {3, 2, 0, -12, 9, 8, 8, 3, 2});
// mean(new int[] {1, 2, 4, 7, 7, 10, 2, 4, 5, 9});
// median(new int[] {1, 2, 4, 7, 7, 10, 2, 4, 5, 9});
input = new Scanner(System.in);
System.out.printf("Masukan Input : ");
String n = input.nextLine();
String[] arrayString = n.split(" ");
int[] arrayInput = new int[arrayString.length];
for (int i = 0; i < arrayString.length; i++) {
arrayInput[i] = Integer.parseInt(arrayString[i]);
}
//sortManual(arrayInput);
modus(arrayInput);
median(arrayInput);
mean(arrayInput);
}// Main
public static void sortManual(int[] arr) {
int temp = 0;
//Loop iterasi
for (int i = 0; i < arr.length; i++) {
//loop pembanding
for (int j = 0; j < (arr.length - 1); j++) {
//if arr[before] > arr[after]
if (arr[j] > arr[j+1]) {
//simpan arr[before] ke temp
temp = arr[j];
//berikan nilai arr[after] kepada arr[before]
arr[j] = arr[j+1];
//berikan nilai sementara kepada arr[after]
arr[j+1] = temp;
}
}
}
// Cek hasil BubbleSort
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+ " ");
}
}
public static void modus(int[] arr) {
HashMap<Integer, Integer> dataInput = new HashMap<Integer, Integer>();
//Arrays.sort(arr);
// looping sebanyak panjang array
for (int i = 0; i < arr.length; i++) {
// .containsKey berfungsi sebagai pembanding
// apakah ada nilai (array ke-i)
// dibagian key pada Map
// Bernilai TRUE apabila nilai tersebut sudah diinisialisasi
if (dataInput.containsKey(arr[i])) {
// .get will return value to which the specified key is mapped
// yang mana value ini adalah jumlah kemunculan
int value = dataInput.get(arr[i]);
value++;
// update jumlah kemunculan nilai
dataInput.put(arr[i], value);
} else {
// berikan key-dataInput dengan nilai array ke-i
// berikan value-dataInput dengan nilai inisialisasi jumlah kemunculan yaitu 1
dataInput.put(arr[i], 1);
}
}
// int maxValueInMap=(Collections.max(dataInput.values()));
int key = Collections.max(dataInput.entrySet(), Map.Entry.comparingByValue()).getKey();
int value = Collections.max(dataInput.values());
System.out.println("\nModus : " + key + "\nValue : " + value);
}
public static void median(int[] arr) {
//Arrays.sort(arr);
sortManual(arr);
float med = 0;
if (arr.length % 2 == 0) {
med = (float) (arr[(arr.length - 1) / 2] + arr[((arr.length - 1) / 2) + 1]) / 2;
} else {
med = (float) (arr[arr.length / 2]);
}
System.out.println("Median : " + med);
}
public static void mean(int[] arr) {
double sum = 0;
double mean = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
mean = (double) (sum / arr.length);
System.out.println("Mean : " + mean);
}
}// Class
|
package com.appfountain.model;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.text.format.DateFormat;
/**
*
* {"up":0,"useful":0,"user_id": 1,
* "user_name":"aaaaaa","body":"bodddddddddddddd", "created"
* :"2013-10-05T06:34:03","question_id":1,"updated":"2013-10-05T06:34:03"
* ,"id":3,"down":0}
*/
public class Comment implements Serializable{
private static final long serialVersionUID = 7791890472926200527L;
private final int id;
private final int question_id;
private final int user_id;
private final String user_name;
private final String body;
private final int refer_comment_id;
private final String refer_comment_user_name;
private final String created;
private Date _created = null;
private final String updated;
private Date _updated = null;
private int up;
private final int down;
private Boolean useful;
private String evaluation;
public Comment(int id, int questionId, int userId, String userName,
String body, int referCommentId, String referCommentUserName, String created, String updated, int up, int down,
Boolean useful, String evaluation) {
this.id = id;
this.question_id = questionId;
this.user_id = userId;
this.user_name = userName;
this.body = body;
this.refer_comment_id = referCommentId;
this.refer_comment_user_name = referCommentUserName;
this.created = created;
this.updated = updated;
this.up = up;
this.down = down;
this.useful = useful;
this.evaluation = evaluation;
}
public int getId() {
return id;
}
public int getQuestionId() {
return question_id;
}
public int getUserId() {
return user_id;
}
public String getUserName() {
return user_name;
}
public String getBody() {
return body;
}
public String getBody(int maxBodySize) {
if (body.length() > maxBodySize)
return body.substring(0, maxBodySize);
return body;
}
public int getReferCommentId() {
return refer_comment_id;
}
public String getReferCommentUserName() {
return refer_comment_user_name;
}
public CharSequence getCreatedString() {
return DateFormat.format("yyyy/MM/dd kk:mm", getCreated());
}
public Date getCreated() {
if (_created == null) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss", Locale.JAPAN);
String date = created.replaceAll("\\+0([0-9]){1}00", "");
try {
_created = formatter.parse(date);
} catch (ParseException e) {
_created = new Date();
}
}
return _created;
}
public CharSequence getUpdatedString() {
return DateFormat.format("yyyy/MM/dd kk:mm", getUpdated());
}
public Date getUpdated() {
if (_updated == null) {
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss", Locale.JAPAN);
String date = updated.replaceAll("\\+0([0-9]){1}00", "");
try {
_updated = formatter.parse(date);
} catch (ParseException e) {
_updated = new Date();
}
}
return _updated;
}
public int getUp() {
return up;
}
public int incrementUp() {
return ++up;
}
public int decrementUp() {
return --up;
}
public int getDown() {
return down;
}
public Boolean isUseful() {
return useful;
}
public Boolean isUpEvaluation() {
return evaluation != null && evaluation.equals("up");
}
public void evaluate() {
if (isUpEvaluation()) {
evaluation = "none";
} else {
evaluation = "up";
}
}
public void usefulEvaluate() {
this.useful = !useful;
}
public boolean isReply() {
return refer_comment_id != 0;
}
}
|
/*
* 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 utilidades;
/**
*
* @author josue
*/
//Clase usada para implementar el patron factory en los objetos jefe y empleado
public abstract class Persona {
private double salario;
private String nombreEmpleado;
private int ced;
public Persona(double salario, String nombreEmpleado, int ced) {
this.salario = salario;
this.nombreEmpleado = nombreEmpleado;
this.ced = ced;
}
public double getSalario() {
return salario;
}
public String getNombre() {
return nombreEmpleado;
}
public int getCed() {
return ced;
}
public void setSalario(double salario) {
this.salario = salario;
}
public void setNombre(String nombreEmpleado) {
this.nombreEmpleado = nombreEmpleado;
}
public void setCed(int ced) {
this.ced = ced;
}
}
|
package com.tridevmc.movingworld.common.config.priority;
import com.google.common.collect.Lists;
import com.tridevmc.compound.config.ConfigType;
import com.tridevmc.compound.config.ConfigValue;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.List;
import java.util.stream.Collectors;
@ConfigType(ModConfig.Type.SERVER)
public class MovingWorldAssemblePriorityConfig {
@ConfigValue(comment = "A list of blocks that should be removed from the world last during assembly.")
public List<Block> lowPriorityAssemblyBlocks = Lists.newArrayList(Blocks.REDSTONE_WIRE, Blocks.OBSIDIAN);
@ConfigValue(comment = "A list of blocks that should be removed from the world first during assembly.")
public List<Block> highPriorityAssemblyBlocks = Lists.newArrayList(Blocks.NETHER_PORTAL, Blocks.PISTON, Blocks.PISTON_HEAD, Blocks.STICKY_PISTON, Blocks.MOVING_PISTON);
@ConfigValue(comment = "A list of blocks that should be set to the world last during disassembly.")
public List<Block> lowPriorityDisassemblyBlocks = Lists.newArrayList(Blocks.REDSTONE_WIRE, Blocks.NETHER_PORTAL);
@ConfigValue(comment = "A list of blocks that should be set to the world first during disassembly.")
public List<Block> highPriorityDisassemblyBlocks = Lists.newArrayList(Blocks.NETHER_PORTAL, Blocks.PISTON, Blocks.PISTON_HEAD, Blocks.STICKY_PISTON, Blocks.MOVING_PISTON);
public MovingWorldAssemblePriorityConfig() {
List<Block> poweredBlocks = this.getPoweredBlocks();
this.highPriorityAssemblyBlocks.addAll(poweredBlocks);
this.lowPriorityDisassemblyBlocks.addAll(poweredBlocks);
}
private List<Block> getPoweredBlocks() {
return ForgeRegistries.BLOCKS.getValues().stream()
.filter((b) -> b.getDefaultState().getProperties().stream()
.anyMatch((p) -> p.getName().equals("powered")))
.collect(Collectors.toList());
}
}
|
package usc.cs310.ProEvento.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import usc.cs310.ProEvento.model.EventNotification;
import usc.cs310.ProEvento.model.FollowRequestNotification;
import usc.cs310.ProEvento.model.Invitation;
import usc.cs310.ProEvento.model.User;
import java.util.List;
@Repository
public class FollowRequestNotificationDao {
@Autowired
private SessionFactory sessionFactory;
public boolean createFollowRequestNotification(FollowRequestNotification notification){
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
session.saveOrUpdate(notification);
session.getTransaction().commit();
return true;
} catch (Exception e) {
e.printStackTrace();
if (session != null) {
session.getTransaction().rollback();
}
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public FollowRequestNotification getFollowRequestNotificationById(long id){
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
FollowRequestNotification notification = (FollowRequestNotification) session.get(FollowRequestNotification.class, id);
session.getTransaction().commit();
return notification;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public List<FollowRequestNotification> getFollowRequestByReceiverId(long id){
try (Session session = sessionFactory.openSession()) {
session.beginTransaction();
Query query = session.createQuery("SELECT i FROM FollowRequestNotification i JOIN i.receivers r WHERE r.id = :receiverId");
query.setParameter("receiverId", id);
List<FollowRequestNotification> notifications = (List<FollowRequestNotification>) query.list();
session.getTransaction().commit();
return notifications;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean updateFollowRequest(FollowRequestNotification notification){
return createFollowRequestNotification(notification);
}
public boolean deleteFollowRequest(FollowRequestNotification notification){
Session session = sessionFactory.openSession();
try {
session.getTransaction().begin();
session.delete(notification);
session.getTransaction().commit();
return true;
} catch (Exception e) {
e.printStackTrace();
if (session != null) {
session.getTransaction().rollback();
}
return false;
} finally {
if (session != null) {
session.close();
}
}
}
}
|
package com.youthlin.example.kafka;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.serialization.StringSerializer;
import java.util.Properties;
/**
* @author youthlin.chen
* @date 2019-06-03 17:15
*/
public class ProducerFastStart {
public static final String BROKER_LIST = "localhost:9092";
public static final String TOPIC = "topic-demo";
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, CompanySerializer.class.getName());
properties.put("bootstrap.servers", BROKER_LIST);
KafkaProducer<String, Company> producer = new KafkaProducer<>(properties);
Company company = new Company();
company.setName("Qunar");
company.setAddress("北京海淀");
ProducerRecord<String, Company> record = new ProducerRecord<>(TOPIC, company);
producer.send(record);
producer.close();
}
}
|
package Metaphase01;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Queue;
import java.util.Vector;
/**
* 自定义比较器MyComparator
*
*/
class myPriorityQueue<E extends Comparable<E>>{ //类型擦除为Comparable,变为可比较对象
private E[] queue; //存放元素的容器
private int size; //有效元素个数
private static int DEFAULT_CAPACITY = 5;
public myPriorityQueue(){
this(DEFAULT_CAPACITY);
}
public myPriorityQueue(int initCapacity){
queue = (E[]) new Comparable[initCapacity];
}
public E element(int index){
if(index <0||index>=size){
return null;
}else {
return queue[index];
}
}
public void add(E value){
ensureCapacity();
//添加一个元素后仍然保持是小根堆
//盘满 扩容
if(size == queue.length){
queue = Arrays.copyOf(queue, queue.length*2);
}
//当前队列为空
if(size == 0){
queue[0] = value;
size++;
}else{
//当前队列不为空,需要调整当前对列为小根堆
adjust(size,value);
size++;
}
}
private void ensureCapacity() {
if(size == queue.length){
queue = Arrays.copyOf(queue,queue.length*2);
}
}
//模拟调整小根堆
public void adjust(int index, E value){
while(index > 0){
int parentIndex = (index - 1)/2;
if(parentIndex>=0&&queue[parentIndex].compareTo(value) > 0){
queue[index] = queue[parentIndex];
index = parentIndex;
}else{
break;
}
}
queue[index] = value;
}
public boolean remove(){
//空的队列
if(size == 0){
return false;
}
//当前队列只有一个元素
int index = --size;
if(index == 0){
queue[index] = null;
return true;
}
//多个元素
queue[0] = null;
adjustDown(0, queue[index]);
return true;
}
//上往下调整
private void adjustDown(int index, E value) {
int leftChild = index*2+1;
while(leftChild < size){
int rightChild = leftChild +1;
if(rightChild<size&&queue[leftChild].compareTo(queue[rightChild])>0){
leftChild++;
}
if(value.compareTo(queue[leftChild])<=0){
break;
}
queue[index] =queue[leftChild];
index = leftChild;
leftChild = leftChild*2+1;
}
queue[index] = value;
}
/*public E remove(){
if(size == 0){
return null;
}else{
int s = --size;
E result = (E) queue[0];
System.arraycopy(queue,1,queue,0,size);
queue[size] = null;
return result;
}
}*/
public E peek(){
if(size == 0){
return null;
}else{
return queue[0];
}
}
@Override
public String toString() {
String strs = new String();
for(int i = 0;i<size;i++){
strs = strs + (Object) element(i) +" ";
}
/*return "myPriorityQueue{" +
"queue=" + Arrays.toString(queue) +
", size=" + size +
'}';*/
return strs;
}
public int size() {
return size;
}
}
public class PriorityQue {
public static void main(String[] args) {
myPriorityQueue<Integer> queue = new myPriorityQueue<>();
queue.add(2);
queue.add(5);
queue.add(3);
queue.add(7);
queue.add(9);
queue.add(4);
queue.add(6);
System.out.println(queue.peek());
System.out.println();
// for(int i =0;i<queue.size();i++){
// System.out.print(queue.element(i)+" ");
// }
System.out.println(queue);
System.out.println();
int m = queue.size();
for(int i =0;i < m-1;i++) {
System.out.print(queue.remove()+" ");
}
System.out.println();
System.out.println(queue.peek());
}
}
|
/**
*/
package iso20022;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Conversation</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* exchange of one or more MessageInstances amongst MessagingEndpoints
* <!-- end-model-doc -->
*
*
* @see iso20022.Iso20022Package#getConversation()
* @model
* @generated
*/
public interface Conversation extends ModelEntity {
} // Conversation
|
import java.util.Scanner;
public class prob08 {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int iterations = reader.nextInt();
reader.nextLine();
String word = reader.nextLine();
for(int i = 0; i<iterations; i++){
String output = "";
int counter = word.length();
for(int s = 0; s<word.length();s++){
for(int t = 0; t<counter; t++){
System.out.print(" ");
}
int numOfLetters = word.length()-counter;
output += word.substring(0, 0+numOfLetters);
System.out.println(output);
output = "";
counter--;
}
for(int s = 0; s<word.length(); s++){
output = word.substring(s, word.length());
System.out.println(output);
output = "";
}
word = reader.nextLine();
}
}
}
|
package com.example.MongoDBConnect.repository;
import com.example.MongoDBConnect.document.Mascota;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author Edinson Ayui
*/
public interface MascotaRepository extends MongoRepository<Mascota, Integer> {
}
|
package com.metoo.kuaidi100.test;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import com.metoo.core.tools.Md5Encrypt;
import com.metoo.kuaidi100.post.HttpRequest;
import com.metoo.kuaidi100.utils.MD5;
public class Query {
public static void main(String[] args) throws Exception {
String param ="{\"com\":\"yunda\",\"num\":\"1202443176364\"}";
String customer ="EF91A38461385824F6FB14D0C594E54E";
String key = "CNbeXYJm2595";
String sign =MD5.encode(param+key+customer);
HashMap<String, String> params = new HashMap<String, String>();
params.put("param",param);
params.put("sign",sign);
params.put("customer",customer);
String resp;
try {
resp = new HttpRequest().postData("http://poll.kuaidi100.com/poll/query.do", params, "utf-8").toString();
System.out.println(resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
package moe.tristan.easyfxml.model.beanmanagement;
import java.lang.ref.WeakReference;
import java.util.Objects;
import moe.tristan.easyfxml.EasyFxml;
/**
* Selectors are special wrappers around a value used in an {@link AbstractInstanceManager} to distinguish multiple
* children of the mapped class amongst themselves. It uses a weak reference as a way to store the actual selector
* value. The overriding of equals and hashCode makes it transparent to use.
* <p>
* Its main use is to avoid confusion in the multiple signatures of {@link EasyFxml}.
*
* @see AbstractInstanceManager
* @see EasyFxml
*/
public final class Selector {
private final WeakReference<?> reference;
/**
* Creates a Selector from a given object.
*
* @param reference The actual value of the selector to use in map-based storage implementations.
*/
public Selector(Object reference) {
this.reference = new WeakReference<>(reference);
}
/**
* @return the backing reference.
*/
@SuppressWarnings("WeakerAccess")
public WeakReference getReference() {
return reference;
}
/**
* Two Selectors are equals iff the values backing their weak references are the same. Null is supported.
*
* @param o The other selector to check for equality with.
*
* @return true if this selector and the one passed as parameter have the same backing value.
*/
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Selector)) {
return false;
}
final Object thisRef = reference.get();
final Object oRef = ((Selector) o).getReference().get();
return Objects.equals(thisRef, oRef);
}
/**
* @return The hashcode of the backing value. 0 if it is null. See {@link Objects#hashCode(Object)}.
*/
@Override
public int hashCode() {
final Object thisRef = reference.get();
return Objects.hashCode(thisRef);
}
}
|
package pages;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class End_To_End_Journey {
private static final Logger logger = LogManager.getLogger(End_To_End_Journey.class);
protected WebDriver driver;
WebDriverWait Wait;
@FindBy(xpath = "//a[@class='login']")
private WebElement clklogin;
@FindBy(id = "email")
private WebElement emailid;
@FindBy(id = "passwd")
private WebElement password;
@FindBy(id = "SubmitLogin")
private WebElement login;
@FindBy(xpath = "//*[@id=\"block_top_menu\"]/ul/li[3]/a")
private WebElement category;
@FindBy(xpath = "//*[@title='Faded Short Sleeve T-shirts']")
private WebElement selectedcategory;
@FindBy(xpath = "//span[@id='our_price_display']")
private WebElement price;
@FindBy(xpath = "//i[@class='icon-plus']")
private WebElement quantity;
@FindBy(xpath = "//select[@id='group_1']")
private WebElement sizes;
@FindBy(xpath = "//button[@class='exclusive']")
private WebElement cart;
public End_To_End_Journey(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clklogin() {
clklogin.click();
logger.info("User clik on sign-in link");
}
public void signin() {
emailid.sendKeys("sachin92@gmail.com");
password.sendKeys("Mysachin@12345");
login.click();
Wait = new WebDriverWait(driver,3);
WebElement login = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='account']")));
String loginname = login.getText();
Assert.assertTrue(loginname.contains("sachin testing"));
logger.info("User entered valid login details");
}
public void productcategory() {
category.click();
// Wait = new WebDriverWait(driver,3);
// WebElement stock = Wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[@class='availability']/span")));
// String actual = stock.getText().trim();
// String expected = "In Stock";
// Assert.assertEquals(expected, actual);
selectedcategory.click();
logger.info("Faded Short Sleeve T-shirts is selected");
}
public void fetchprice() {
System.out.println("Selected product price is " + " : " + " "+ price.getText());
}
public void quantity() {
quantity.click();
}
public void size() {
Select size = new Select(sizes);
size.selectByValue("3");
}
public void addtocart() {
cart.click();
}
}
|
package http;
import org.junit.Test;
import java.net.HttpURLConnection;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.fail;
public class ConnectToAPITest {
@Test
public void testHttpConnectionToExampleApi() {
try {
String requestURL = "<API REQUEST URL>";
HttpURLConnection con = ConnectToAPI.makeHttpGetRequest(requestURL);
assertEquals(con.getResponseCode(), 200);
} catch (Exception ioq) {
fail("HTTP connection threw error:" + ioq.getLocalizedMessage());
}
}
/**
* Testida vaja koodi parse'mist jne.
*/
}
|
package au.gov.nsw.records.digitalarchive.base;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.StringTokenizer;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import au.gov.nsw.records.digitalarchive.ORM.FullAgencyList;
import au.gov.nsw.records.digitalarchive.ORM.Keyword;
import au.gov.nsw.records.digitalarchive.service.FullAgencyListService;
import au.gov.nsw.records.digitalarchive.service.FullAgencyListServiceImpl;
import au.gov.nsw.records.digitalarchive.service.KeywordService;
import au.gov.nsw.records.digitalarchive.service.KeywordServiceImpl;
import au.gov.nsw.records.digitalarchive.service.PublisherPublicationService;
import au.gov.nsw.records.digitalarchive.service.PublisherPublicationServiceImpl;
public class JSONFactory extends BaseLog
{
@SuppressWarnings("unchecked")
public String keywordJSON() throws Exception
{
KeywordService ks = new KeywordServiceImpl();
JSONArray keywords = new JSONArray();
List<Keyword> list = ks.browseKeywords();
Keyword keyword = null;
int i = 0;
Iterator<Keyword> it = list.iterator();
while (it.hasNext())
{
keyword = (Keyword)it.next();
keywords.add(new JSONFormat(keyword.getKeywordId().toString(), keyword.getKeyword()));
i++;
}
StringWriter out = new StringWriter();
try {
keywords.writeJSONString(out);
} catch (IOException e) {
logger.info("In class JSONFactory:tagJSON()\n");
e.printStackTrace();
}
return out.toString();
}
@SuppressWarnings("unchecked")
public String keywordJSON(String keyword) throws Exception
{
KeywordService ks = new KeywordServiceImpl();
JSONArray keywords = new JSONArray();
String keywordArray[];
StringTokenizer st = new StringTokenizer(keyword, ",");
keywordArray = new String[st.countTokens()];
int i = 0;
while(st.hasMoreTokens())
{
keywordArray[i] = st.nextToken();
i++;
}
for(int j = 0; j < keywordArray.length; j++)
{
keywords.add(new JSONFormat(ks.loadKeyword(Integer.valueOf(keywordArray[j])).getKeywordId().toString(), ks.loadKeyword(Integer.valueOf(keywordArray[j])).getKeyword()));
}
StringWriter out = new StringWriter();
keywords.writeJSONString(out);
return out.toString();
}
@SuppressWarnings("unchecked")
public String AgenciesJSON(String agencyName) throws Exception
{
FullAgencyListService fas = new FullAgencyListServiceImpl();
JSONArray agencies = new JSONArray();
List<FullAgencyList> list = fas.list4AutoComplete(agencyName);
FullAgencyList fList = null;
int i = 0;
Iterator<FullAgencyList> it = list.iterator();
while (it.hasNext())
{
fList = (FullAgencyList)it.next();
agencies.add(new JSONFormat(Integer.toString(fList.getFullAgencyListId()), fList.getAgencyName()));
i++;
}
StringWriter out = new StringWriter();
try {
agencies.writeJSONString(out);
} catch (IOException e) {
logger.info("In class JSONFactory:AgenciesJSON()\n");
e.printStackTrace();
}
return out.toString();
}
@SuppressWarnings("unchecked")
public String tokenizedAgencyJSON(String agencyNumber) throws Exception
{
FullAgencyListService fls = new FullAgencyListServiceImpl();
JSONArray agencies = new JSONArray();
String agencyArray[];
StringTokenizer st = new StringTokenizer(agencyNumber, ",");
agencyArray = new String[st.countTokens()];
int i = 0;
while(st.hasMoreTokens())
{
agencyArray[i] = st.nextToken();
i++;
}
for(int j = 0; j < agencyArray.length; j++)
{
agencies.add(new JSONFormat(fls.loadFullAgencyList(Integer.valueOf(agencyArray[j])).getFullAgencyListId().toString(),
fls.loadFullAgencyList(Integer.valueOf(agencyArray[j])).getAgencyName()));
}
StringWriter out = new StringWriter();
agencies.writeJSONString(out);
return out.toString();
}
@SuppressWarnings({ "unchecked", "unused" })
public String publisherJSON(String publisher) throws Exception
{
FullAgencyListService fas = new FullAgencyListServiceImpl();
JSONArray agencies = new JSONArray();
List<FullAgencyList> list = fas.list4AutoComplete(publisher);
FullAgencyList fList = null;
int i = 0;
Iterator<FullAgencyList> it = list.iterator();
while (it.hasNext())
{
fList = (FullAgencyList)it.next();
agencies.add(new JSONFormat(Integer.toString(fList.getFullAgencyListId()), fList.getAgencyName()));
i++;
}
StringWriter out = new StringWriter();
try {
agencies.writeJSONString(out);
} catch (IOException e) {
logger.info("In class JSONFactory:publisherJSON()\n");
e.printStackTrace();
}
return out.toString();
}
@SuppressWarnings("unchecked")
public String prePopulatedAgency(String publicationID) throws Exception
{
FullAgencyListService fas = new FullAgencyListServiceImpl();
List<FullAgencyList> fList = fas.loadAgencyViaPublication(publicationID.trim());
JSONArray agencyJSON = new JSONArray();
Iterator<FullAgencyList> it = fList.iterator();
FullAgencyList agencyList = null;
while (it.hasNext())
{
agencyList = (FullAgencyList)it.next();
agencyJSON.add(new JSONFormat(agencyList.getFullAgencyListId().toString(),
agencyList.getAgencyName()));
}
StringWriter out = new StringWriter();
agencyJSON.writeJSONString(out);
return out.toString();
}
@SuppressWarnings("unchecked")
public String prePopulatedKeyword(String publicationID) throws Exception
{
KeywordService ks = new KeywordServiceImpl();
List<Keyword> kList = ks.loadKeywordViaPublication(publicationID.trim());
JSONArray keywordJSON = new JSONArray();
Iterator<Keyword> it = kList.iterator();
Keyword keyword = null;
while (it.hasNext())
{
keyword = (Keyword)it.next();
keywordJSON.add(new JSONFormat(keyword.getKeywordId().toString(),
keyword.getKeyword()));
}
StringWriter out = new StringWriter();
keywordJSON.writeJSONString(out);
return out.toString();
}
@SuppressWarnings("unchecked")
public String prePopulatedPublisher(String publicationID) throws Exception
{
PublisherPublicationService pps = new PublisherPublicationServiceImpl();
List<FullAgencyList> fList = pps.loadPublisherViaPublication(publicationID.trim());
JSONArray publisherJSON = new JSONArray();
Iterator<FullAgencyList> it = fList.iterator();
FullAgencyList fullAgencyList = null;
while (it.hasNext())
{
fullAgencyList = (FullAgencyList)it.next();
publisherJSON.add(new JSONFormat(fullAgencyList.getFullAgencyListId().toString(),
fullAgencyList.getAgencyName()));
}
StringWriter out = new StringWriter();
publisherJSON.writeJSONString(out);
return out.toString();
}
public String NYTReaderJSON() throws Exception
{
StringWriter out = new StringWriter();
JSONObject obj = new JSONObject();
LinkedHashMap m1 = new LinkedHashMap();
m1.put("id", "file");
m1.put("title", "file");
m1.put("pages", "131");
m1.put("description", "");
m1.put("canonical_url", "http://localhost:8080/DA-WEB/doc_opener?uid=21db6ba358dd421da8090b95752c6fde");
JSONValue.writeJSONString(m1, out);
String jsonString = out.toString();
return jsonString;
}
}
|
package com.healthyteam.android.healthylifers.Domain;
import android.graphics.Bitmap;
import java.util.List;
public class LocationBuilder implements Builder {
private Bitmap LocaitonPic;
private String Name;
private String Descripition;
private String DateAdded;
private List<String> TagList;
private UserLocation.Category Category;
private int likeCount;
private int dislikeCount;
private UserLocation.Rate UserRate;
private Double lan;
private Double lon;
// private List<Comments> Comments;
//ako je neophodno da se dovlace svi objekti komentara iz baze, onda atribut ispod nije potreban
private int commentCount;
private User Author;
@Override
public void setPicture(Bitmap locaitonPic){
this.LocaitonPic=locaitonPic;
}
@Override
public void setName(String Name) {
this.Name=Name;
}
@Override
public void setDescripition(String Desc) {
this.Descripition=Desc;
}
@Override
public void setDateAdded(String DateAdded) {
this.DateAdded=DateAdded;
}
@Override
public void setCategory(UserLocation.Category category) {
this.Category=category;
}
@Override
public void setLikeCount(int Count) {
this.likeCount=Count;
}
@Override
public void setDislikeCount(int Count) {
this.dislikeCount=Count;
}
@Override
public void setUserRate(UserLocation.Rate Rate) {
this.UserRate=Rate;
}
@Override
public void setLangitude(Double lan) {
this.lan=lan;
}
@Override
public void setLongitude(Double lon) {
this.lon=lon;
}
@Override
public void setCommentCount(int Count) {
this.commentCount=Count;
}
@Override
public void setAuthor(User Author){
this.Author=Author;
}
public UserLocation getResult(){
return new UserLocation();
}
@Override
public void setTags(List<String> tags) {
this.TagList=tags;
}
}
|
package de.denisvonscheidt.slickpong;
import java.util.Random;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
final class GameStateMenu extends BasicGameState {
public static final int ID = 1;
private static final int MENU1Y = 100;
private static final int MENU2Y = 120;
private static final int MENU3Y = 140;
private static final float BALL_SPEED = 1.5f;
private Ball ball;
private int selectorPosY = MENU1Y;
@Override
public void init(GameContainer arg0, StateBasedGame arg1)
throws SlickException {
// TODO Auto-generated method stub
ball = new Ball(SlickPong.WIDTH / 2, SlickPong.HEIGHT / 2);
Random r = new Random();
ball.setAngle(r.nextInt(360));
// ball.setAngle(200f);
ball.setSpeed(BALL_SPEED);
}
@Override
public void render(GameContainer gc, StateBasedGame game, Graphics g)
throws SlickException {
g.setColor(Color.white);
g.fill(ball.getShape());
g.drawString("SlickPong", 150, 10);
g.drawString("Select the game mode:", 150, 70);
g.fillOval(135, selectorPosY + 5, 10, 10);
g.drawString("Player vs. Player (Single Computer)", 150, MENU1Y);
g.drawString("Player vs. Player (LAN)", 150, MENU2Y);
g.drawString("Player vs. Computer", 150, MENU3Y);
}
@Override
public void update(GameContainer arg0, StateBasedGame arg1, int delta)
throws SlickException {
// TODO Auto-generated method stub
if (ball.getShape().getY() + 10 >= SlickPong.HEIGHT || ball.getShape().getY() <= 0) { //TODO extract radius constant
ball.setAngle(180 - (ball.getAngle() % 360));
}
if (ball.getShape().getX() + 10 >= SlickPong.WIDTH || ball.getShape().getX() <= 0) { //TODO extract radius constant
ball.setAngle(180 + (180-(ball.getAngle() % 360)));
}
float hip = 0.3f * delta + ball.getSpeed();
ball.getShape().setX((float) (ball.getShape().getX() + hip * Math.sin(Math.toRadians(ball.getAngle()))));
ball.getShape().setY((float) (ball.getShape().getY() - hip * Math.cos(Math.toRadians(ball.getAngle()))));
}
@Override
public void keyReleased(int key, char c) {
switch (key) {
case Input.KEY_DOWN:
switch(selectorPosY) {
case MENU1Y:
selectorPosY = MENU2Y;
break;
case MENU2Y:
selectorPosY = MENU3Y;
break;
}
break;
case Input.KEY_UP:
switch(selectorPosY) {
case MENU2Y:
selectorPosY = MENU1Y;
break;
case MENU3Y:
selectorPosY = MENU2Y;
break;
}
break;
case Input.KEY_ENTER:
switch(selectorPosY) {
case MENU1Y:
//TODO
break;
case MENU2Y:
//TODO
break;
case MENU3Y:
//TODO
break;
}
break;
}
}
@Override
public int getID() {
return ID;
}
}
|
/**
*
*/
package net.lantrack.framework.springplugin.component;
import org.springframework.core.convert.support.GenericConversionService;
/**
* @author 大法师
*/
public class string2MapConverter extends GenericConversionService {
}
|
package com.icanit.app_v2.sqlite;
import com.icanit.app_v2.entity.AppMerchant;
import com.icanit.app_v2.exception.AppException;
public interface UserBrowsingDao {
int COLLECTED=2,
VIEWED=1;
int getBrowsedMerchantCountByMerId(int merId,String phone) throws AppException;
void addToBrowsedMerchant(AppMerchant merchant,String phone) throws AppException;
void cancelBrowsedMerchant(int merId,String phone)throws AppException;
void clearBrowsedMerchant(String phone) throws AppException;
}
|
import org.hexworks.zircon.api.CP437TilesetResources;
import org.hexworks.zircon.api.DrawSurfaces;
import org.hexworks.zircon.api.GraphicalTilesetResources;
import org.hexworks.zircon.api.SwingApplications;
import org.hexworks.zircon.api.application.AppConfig;
import org.hexworks.zircon.api.color.ANSITileColor;
import org.hexworks.zircon.api.color.TileColor;
import org.hexworks.zircon.api.data.Position;
import org.hexworks.zircon.api.data.Tile;
import org.hexworks.zircon.api.graphics.Layer;
import org.hexworks.zircon.api.graphics.Symbols;
import org.hexworks.zircon.api.graphics.TileGraphics;
import org.hexworks.zircon.api.grid.TileGrid;
import org.hexworks.zircon.api.screen.Screen;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
public class App {
public static void main(String[] args) {
TileGrid tileGrid = SwingApplications
.startTileGrid(
AppConfig.newBuilder()
.withSize(50, 50)
// .withDefaultTileset(CP437TilesetResources.anikki16x16())
.withDefaultTileset(GraphicalTilesetResources.nethack16x16())
// .withDebugMode(true)
.build()
);
final Screen screen = Screen.create(tileGrid);
// List<Layer> layers = GraphicalTilesetResources.nethack16x16().get;
screen.display();
final TileGraphics background = DrawSurfaces.tileGraphicsBuilder()
.withSize(tileGrid.getSize()) // you can fetch the size of a TileGrid like this
.withFiller(Tile.newBuilder()
// .withCharacter(Symbols.BULLET)
.withBackgroundColor(ANSITileColor.WHITE)
.withForegroundColor(ANSITileColor.CYAN)
.build())
.build();
tileGrid.draw(background, Position.zero());
tileGrid.draw(
Tile.newBuilder()
.withTileset(GraphicalTilesetResources.nethack16x16())
.withName("Pyrolisk")
.buildGraphicalTile(), Position.create(2, 5)
);
}
}
|
package com.metoo.foundation.dao;
import org.springframework.stereotype.Repository;
import com.metoo.core.base.GenericDAO;
import com.metoo.foundation.domain.StorePoint;
@Repository("storePointDAO")
public class StorePointDAO extends GenericDAO<StorePoint> {
}
|
package tictactoe;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GameClass {
String[][] Board ={{"1","2","3"},{"4","5","6"},{"7","8","9"}};
int position;
boolean status;
public GameClass(String Board[][]) {
this.Board = Board;
}
public void BoardLook(String Board[][]){
for (int i = 0; i < Board.length; i++) {
for (int j = 0; j < Board[i].length; j++) {
System.out.print("| " + Board[i][j] + " ");
}
System.out.println("|");
if(i < 2){
System.out.print("-------------");
}
System.out.println();
}
}
public void playerTurn() {
ImageIcon TicTacToeBoard = new ImageIcon("images/TicTacToeBoard.png");
JOptionPane.showMessageDialog(null, " ", " ", JOptionPane.INFORMATION_MESSAGE, TicTacToeBoard);
int position = Integer.parseInt(JOptionPane.showInputDialog("Select a position to put an 'X'" + "\n" + "Remember not to select the same position more than one time!" + "\n" + "type the respective number."));
switch (position) {
case 1:
Board[0][0] = "X";
break;
case 2:
Board[0][1] = "X";
break;
case 3:
Board[0][2] = "X";
break;
case 4:
Board[1][0] = "X";
break;
case 5:
Board[1][1] = "X";
break;
case 6:
Board[1][2] = "X";
break;
case 7:
Board[2][0] = "X";
break;
case 8:
Board[2][1] = "X";
break;
case 9:
Board[2][2] = "X";
break;
}
}
/*public void status(boolean status, String Board[][]) {
if ((Board[0][0] = "X") && Board[0][1] = "X" && Board[0][2] = "X") || (Board[0][0] = "O" && Board[0][1] = "O" && Board[0][2] = "O")) {
status = false;
}
if ((Board[0][0] = "X" && Board[1][0] = "X" && Board[2][0] = "X") || (Board[0][0] = "O" && Board[1][0] = "O" && Board[2][0] = "O")) {
status = false;
}
if ((Board[1][0] = "X" && Board[1][1] = "X" && Board[1][2] = "X") || (Board[1][0] = "O" && Board[1][1] = "O" && Board[1][2] = "O")) {
status = false;
}
if ((Board[2][0] = "X" && Board[2][1] = "X" && Board[2][2] = "X") || (Board[2][0] = "O" && Board[2][1] = "O" && Board[2][2] = "O")) {
status = false;
}
if ((Board[0][1] = "X" && Board[1][1] = "X" && Board[2][1] = "X") || (Board[0][1] = "O" && Board[1][1] = "O" && Board[2][1] = "O")) {
status = false;
}
if ((Board[0][2] = "X" && Board[1][2] = "X" && Board[2][2] = "X") || (Board[0][2] = "O" && Board[1][2] = "O" && Board[2][2] = "O")) {
status = false;
}
if ((Board[0][0] = "X" && Board[1][1] = "X" && Board[2][2] = "X") || (Board[0][0] = "O" && Board[1][1] = "O" && Board[2][2] = "O")) {
status = false;
}
if ((Board[2][0] = "X" && Board[1][1] = "X" && Board[0][2] = "X") || (Board[2][0] = "O" && Board[1][1] = "O" && Board[0][2] = "O")) {
status = false;
}
}
*/
public void computerTurn() {
Random rand = new Random();
int position = rand.nextInt(9) + 1;
switch (position) {
case 1:
Board[0][0] = "O";
break;
case 2:
Board[0][1] = "O";
break;
case 3:
Board[0][2] = "O";
break;
case 4:
Board[1][0] = "O";
break;
case 5:
Board[1][1] = "O";
break;
case 6:
Board[1][2] = "O";
break;
case 7:
Board[2][0] = "O";
break;
case 8:
Board[2][1] = "O";
break;
case 9:
Board[2][2] = "O";
break;
}
}
}
|
/* ------------------------------------------------------------------------------
* 软件名称:BB语音
* 公司名称:乐多科技
* 开发作者:Yongchao.Yang
* 开发时间:2016年5月23日/2016
* All Rights Reserved 2012-2015
* ------------------------------------------------------------------------------
* 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发
* ------------------------------------------------------------------------------
* prj-name:com.ace.commucation.server
* fileName:RobotController.java
* -------------------------------------------------------------------------------
*/
package com.rednovo.ace.robot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.configuration.tree.ConfigurationNode;
import org.apache.log4j.Logger;
import com.alibaba.fastjson.JSONObject;
import com.rednovo.ace.constant.Constant.ChatMode;
import com.rednovo.ace.constant.Constant.InteractMode;
import com.rednovo.ace.constant.Constant.MsgType;
import com.rednovo.ace.entity.Message;
import com.rednovo.ace.entity.Summary;
import com.rednovo.ace.entity.User;
import com.rednovo.ace.globalData.LiveShowManager;
import com.rednovo.ace.globalData.OutMessageManager;
import com.rednovo.ace.globalData.UserManager;
import com.rednovo.tools.PPConfiguration;
import com.rednovo.tools.Validator;
/**
* 机器人控制线程
*
* @author yongchao.Yang/2016年5月23日
*/
public class NewLiveShowRobot extends Thread {
private Logger logger = Logger.getLogger(NewLiveShowRobot.class);
private String showId;
private static ArrayList<String> freedomUser = new ArrayList<String>();
static {
XMLConfiguration cf = (XMLConfiguration) PPConfiguration.getXML("robot.xml");
List<ConfigurationNode> list = cf.getRoot().getChildren();
for (ConfigurationNode node2 : list) {
freedomUser.add(String.valueOf(node2.getChild(1).getValue()));
}
}
/**
* @param name
*/
public NewLiveShowRobot(String showId) {
this.showId = showId;
}
@Override
public void run() {
Collections.shuffle(freedomUser);
// 进入房间
int index = 0;
// 如果房间为新开房间,则补满50人
long cnt = LiveShowManager.getRobotCnt(showId);
if (cnt < 50) {
for (int i = 0; i < 30 - cnt; i++) {
logger.info("[NewLiveShowRobot][-------往新房间里压入机器人" + showId + "------------]");
try {
Message enterInfo = createEnterMessage("1", freedomUser.get(index++), showId);
OutMessageManager.addMessage(enterInfo);
LiveShowManager.updateRobotCnt(showId, 1);
synchronized (this) {
this.wait(5000);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
/**
* 构建消息类型
*
* @param type
* @param showId
* @return
* @author Yongchao.Yang
* @since 2016年5月23日下午3:23:47
*/
private Message createEnterMessage(String type, String userId, String showId) {
Message msg = new Message();
// 进入房间
User u = UserManager.getUser(userId);
Summary smy = new Summary();
smy.setChatMode(ChatMode.GROUP.getValue());
smy.setInteractMode(InteractMode.REQUEST.getValue());
smy.setMsgId("9999-enter");
smy.setMsgType(MsgType.TXT_MSG.getValue());
smy.setReceiverId("");
smy.setReceiverName("");
smy.setRequestKey("002-001");
smy.setSenderId(userId);
smy.setSenderName(u.getNickName());
smy.setShowId(showId);
JSONObject jo = new JSONObject();
jo.put("userId", userId);
jo.put("nickName", u.getNickName());
jo.put("profile", u.getProfile());
jo.put("sex", Validator.isEmpty(u.getSex()) ? "0" : u.getSex());
jo.put("channel", u.getChannel());
msg.setBody(jo);
msg.setSumy(smy);
return msg;
}
}
|
package com.telcaria.kibana.dashboards;
import com.google.common.base.Charsets;
import com.google.common.collect.Maps;
import com.google.common.io.Resources;
import com.hubspot.jinjava.Jinjava;
import com.telcaria.kibana.dashboards.model.KibanaDashboardVisualization;
import com.telcaria.kibana.dashboards.model.KibanaDashboardDescription;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Generator {
//private static final Logger log = LoggerFactory.getLogger(DashboardController.class);
private String templateDirectory;
public Generator(String templateDirectory) {
this.templateDirectory = templateDirectory;
}
public Generator() {
this.templateDirectory = "dashboard-templates/";
}
public List<String> translate(KibanaDashboardDescription description){
List<String> objects = new ArrayList<>();
//Translate visualizations
description.getVisualizations().forEach(visualization ->
objects.add(createVisualizationObject(visualization))
);
//Translate dashboard
objects.add(createDashboard(description));
return objects;
}
public String createVisualizationObject(KibanaDashboardVisualization visualization) {
Jinjava jinjava = new Jinjava();
Map<String, Object> context = Maps.newHashMap();
//Retrieve data from Json and create context to fill in the templates
context.put("id", visualization.getId());
context.put("title", visualization.getTitle());
context.put("index", visualization.getIndex());
if(visualization.getAggregationType() != null)
context.put("aggregationType", visualization.getAggregationType());
if(visualization.getMetricNameX() != null)
context.put("metricNameX", visualization.getMetricNameX());
if(visualization.getMetricNameY() != null)
context.put("metricNameY", visualization.getMetricNameY());
if(visualization.getYlabel() != null)
context.put("ylabel", visualization.getYlabel());
if(visualization.getXlabel() != null)
context.put("xlabel", visualization.getXlabel());
//Retrieve Jinjava template
//TODO: enum with visualization type.
//TODO: Handle templates in a separate class
String template = null;
switch(visualization.getVisualizationType()) {
case "metric":
template = templateDirectory + "count-visualization-template.json";
break;
case "line":
template = templateDirectory + "line-visualization-template.json";
break;
case "pie":
template = templateDirectory + "pie-visualization-template.json";
break;
default:
//TODO: Handle unknown visualization type
break;
}
try {
template = Resources.toString(Resources.getResource(template), Charsets.UTF_8);
}
catch (IOException e) {
//log.warn(e.toString());
}
return jinjava.render(template, context);
}
public String createDashboard(KibanaDashboardDescription dashboard) {
Jinjava jinjava = new Jinjava();
Map<String, Object> context = Maps.newHashMap();
context.put("id", dashboard.getDashboardId());
context.put("title", dashboard.getDashboardTitle());
context.put("index", dashboard.getIndex());
//Add visualizations
//transform to string array
List<String> dashboardIdList = dashboard.getVisualizations().stream().map(v -> v.getId()).collect(Collectors.toList());
context.put("dashboard_id_list", dashboardIdList);
context.put("panelsJson", getPanelsJson(dashboardIdList));
//TODO: Handle template paths in a separate class
String template = templateDirectory + "dashboard-template.json";
try {
template = Resources.toString(Resources.getResource(template), Charsets.UTF_8);
}
catch (IOException e) {
//log.warn(e.toString());
}
return jinjava.render(template, context);
}
private String getPanelsJson(List<String> dashboardsList){
int x = 0,y = -15;
String panelsJson = "[";
for (int i = 0; i < dashboardsList.size(); i++) {
if( i % 2 == 0) {
x = 0;
y += 15;
}
else {
x = 24;
}
panelsJson = panelsJson.concat("{\\\"gridData\\\":{\\\"w\\\":24,\\\"h\\\":15,\\\"x\\\":" + x + ",\\\"y\\\":" + y + ",\\\"i\\\":\\\"" + (i+1) + "\\\"},\\\"panelIndex\\\"" +
":\\\"" + (i+1) + "\\\",\\\"embeddableConfig\\\":{},\\\"panelRefName\\\":\\\"panel_" + (i + 1) + "\\\"}");
if (i < dashboardsList.size() - 1) {
panelsJson = panelsJson.concat(",");
}
}
return panelsJson.concat("]");
}
}
|
package com.dongh.funplus.di.module;
import com.dongh.funplus.di.scope.FragmentScope;
import com.dongh.funplus.view.other.OtherContract;
import com.dongh.funplus.view.other.OtherModel;
import dagger.Module;
import dagger.Provides;
/**
* Created by chenxz on 2017/12/3.
*/
@Module
public class OtherFragmentModule {
private OtherContract.View view;
public OtherFragmentModule(OtherContract.View view) {
this.view = view;
}
@FragmentScope
@Provides
OtherContract.View provideOtherView() {
return this.view;
}
@FragmentScope
@Provides
OtherContract.Model provideOtherModel(OtherModel model) {
return model;
}
}
|
package com.alibaba.druid.bvt.sql.mysql.createTable;
import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.dialect.mysql.ast.statement.MySqlCreateTableStatement;
import com.alibaba.druid.sql.dialect.mysql.parser.MySqlStatementParser;
import junit.framework.TestCase;
import java.util.List;
public class MySqlCreateTableTest147_fulltext2 extends TestCase {
public void test_0() throws Exception {
String sql = "CREATE TABLE aliyun_poc_db.tbl_custom_analyzer2 (\n" +
" `id` int COMMENT '',\n" +
" `title` varchar COMMENT '',\n" +
" FULLTEXT INDEX title_fulltext_idx (title) WITH INDEX ANALYZER index_analyzer2 WITH QUERY ANALYZER query_analyzer2 WITH DICT user_dict,\n" +
" PRIMARY KEY (`id`)\n" +
")DISTRIBUTED BY HASH(`id`);";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
MySqlCreateTableStatement stmt = (MySqlCreateTableStatement) statementList.get(0);
assertEquals(1, statementList.size());
assertEquals("CREATE TABLE aliyun_poc_db.tbl_custom_analyzer2 (\n" +
"\t`id` int COMMENT '',\n" +
"\t`title` varchar COMMENT '',\n" +
"\tFULLTEXT INDEX title_fulltext_idx(title) WITH INDEX ANALYZER index_analyzer2 WITH QUERY ANALYZER query_analyzer2 WITH DICT user_dict,\n" +
"\tPRIMARY KEY (`id`)\n" +
")\n" +
"DISTRIBUTE BY HASH(`id`);", stmt.toString());
assertEquals("create table aliyun_poc_db.tbl_custom_analyzer2 (\n" +
"\t`id` int comment '',\n" +
"\t`title` varchar comment '',\n" +
"\tfulltext index title_fulltext_idx(title) with index analyzer index_analyzer2 with query analyzer query_analyzer2 with dict user_dict,\n" +
"\tprimary key (`id`)\n" +
")\n" +
"distribute by hash(`id`);", stmt.toLowerCaseString());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.